@maind-dev/cli 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -1,43 +1,50 @@
1
1
  #!/usr/bin/env node
2
- var zs=Object.defineProperty;var a=(e,t)=>zs(e,"name",{value:t,configurable:!0});import{mkdirSync as ro,writeFileSync as io}from"node:fs";import{dirname as so}from"node:path";import{existsSync as Ys,readFileSync as Xs}from"node:fs";import{homedir as Js,platform as xn}from"node:os";import{join as V}from"node:path";function Se(){let e=Js(),t=process.env;if(xn()==="darwin")return V(e,"Library","Application Support","maind");if(xn()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:V(e,"AppData","Roaming");return V(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:V(e,".config");return V(n,"maind")}a(Se,"configDir");function En(e){if(!Ys(e))return null;try{let t=Xs(e,"utf8").trim();return t.length>0?t:null}catch{return null}}a(En,"readFileTrimmed");var R=class extends Error{static{a(this,"MissingApiKeyError")}constructor(){super("No API key found. Set MAIND_API_KEY (a read-scoped CI key from https://maind.dev/keys) or pair the maind bridge on this machine first."),this.name="MissingApiKeyError"}};function A(){let e=process.env.MAIND_API_KEY?.trim(),t=e&&e.length>0?e:En(V(Se(),"api-key"));if(!t)throw new R;let n=En(V(Se(),"device-id"));return{apiKey:t,deviceId:n,keyPrefix:Qs(t)}}a(A,"resolveAuth");function Qs(e){let t=/^(mnd_[0-9a-f]{8})_/i.exec(e);return t?t[1]:e.slice(0,12)}a(Qs,"keyPrefixOf");var Zs="https://mcp.maind.dev/mcp",Sn="maind-cli",j=class extends Error{constructor(n,r){super(n);this.code=r;this.name="McpError"}static{a(this,"McpError")}},P=class{static{a(this,"McpClient")}mcpUrl;apiKey;deviceId;clientVersion;projectKey;sessionId=null;nextId=1;initialized=!1;constructor(t){this.apiKey=t.apiKey,this.deviceId=t.deviceId,this.clientVersion=t.clientVersion,this.projectKey=t.projectKey??null,this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??Zs}headers(){let t={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.apiKey}`,"x-maind-client-family":Sn,"x-maind-client-version":this.clientVersion};return this.deviceId&&(t["x-maind-device-id"]=this.deviceId),this.projectKey&&(t["x-maind-project-key"]=this.projectKey),this.sessionId&&(t["mcp-session-id"]=this.sessionId),t}async connect(){if(this.initialized)return;let t=await this.post({jsonrpc:"2.0",id:this.nextId++,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:Sn,version:this.clientVersion}}});if(t.message.error)throw new j(`initialize failed: ${t.message.error.message}`,t.message.error.code);t.sessionId&&(this.sessionId=t.sessionId),await this.post({jsonrpc:"2.0",method:"notifications/initialized"}),this.initialized=!0}async callTool(t,n){this.initialized||await this.connect();let r=await this.post({jsonrpc:"2.0",id:this.nextId++,method:"tools/call",params:{name:t,arguments:n}});if(r.message.error)throw new j(`tool ${t} failed: ${r.message.error.message}`,r.message.error.code);let s=r.message.result?.content?.find(c=>c.type==="text"&&typeof c.text=="string")?.text;if(typeof s!="string")throw new j(`tool ${t} returned no text content`);let o=no(s);if(o===void 0)throw new j(`tool ${t} returned non-JSON text`);return o}async post(t){let n;try{n=await fetch(this.mcpUrl,{method:"POST",headers:this.headers(),body:JSON.stringify(t)})}catch(c){throw new j(`network error contacting ${this.mcpUrl}: ${to(c)}`)}let r=n.headers.get("mcp-session-id");if(n.status===401){let c=await n.text().catch(()=>"");throw new j(`auth rejected (401): ${c.slice(0,200)}`,401)}if(n.status===202)return{message:{jsonrpc:"2.0",result:null},sessionId:r};if(!n.ok){let c=await n.text().catch(()=>"");throw new j(`upstream HTTP ${n.status}: ${c.slice(0,300)}`,n.status)}let s=(n.headers.get("content-type")??"").startsWith("text/event-stream")?await eo(n):await n.text();if(s.trim().length===0)return{message:{jsonrpc:"2.0",result:null},sessionId:r};let o;try{o=JSON.parse(s)}catch{throw new j(`could not parse JSON-RPC response: ${s.slice(0,200)}`)}return{message:o,sessionId:r}}};async function eo(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s="",o=a(()=>{if(i.length===0)return;let c=i.join(`
2
+ var ra=Object.defineProperty;var a=(e,t)=>ra(e,"name",{value:t,configurable:!0});import{mkdirSync as fa,writeFileSync as pa}from"node:fs";import{dirname as ma}from"node:path";import{existsSync as ia,readFileSync as sa}from"node:fs";import{homedir as oa,platform as hr}from"node:os";import{join as X}from"node:path";function je(){let e=oa(),t=process.env;if(hr()==="darwin")return X(e,"Library","Application Support","maind");if(hr()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:X(e,"AppData","Roaming");return X(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:X(e,".config");return X(n,"maind")}a(je,"configDir");function gr(e){if(!ia(e))return null;try{let t=sa(e,"utf8").trim();return t.length>0?t:null}catch{return null}}a(gr,"readFileTrimmed");var T=class extends Error{static{a(this,"MissingApiKeyError")}constructor(){super("No API key found. Set MAIND_API_KEY (a read-scoped CI key from https://maind.dev/keys) or pair the maind bridge on this machine first."),this.name="MissingApiKeyError"}};function I(){let e=process.env.MAIND_API_KEY?.trim(),t=e&&e.length>0?e:gr(X(je(),"api-key"));if(!t)throw new T;let n=gr(X(je(),"device-id"));return{apiKey:t,deviceId:n,keyPrefix:aa(t)}}a(I,"resolveAuth");function aa(e){let t=/^(mnd_[0-9a-f]{8})_/i.exec(e);return t?t[1]:e.slice(0,12)}a(aa,"keyPrefixOf");var ca="https://mcp.maind.dev/mcp",yr="maind-cli",F=class extends Error{constructor(n,r){super(n);this.code=r;this.name="McpError"}static{a(this,"McpError")}},P=class{static{a(this,"McpClient")}mcpUrl;apiKey;deviceId;clientVersion;projectKey;sessionId=null;nextId=1;initialized=!1;constructor(t){this.apiKey=t.apiKey,this.deviceId=t.deviceId,this.clientVersion=t.clientVersion,this.projectKey=t.projectKey??null,this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??ca}headers(){let t={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.apiKey}`,"x-maind-client-family":yr,"x-maind-client-version":this.clientVersion};return this.deviceId&&(t["x-maind-device-id"]=this.deviceId),this.projectKey&&(t["x-maind-project-key"]=this.projectKey),this.sessionId&&(t["mcp-session-id"]=this.sessionId),t}async connect(){if(this.initialized)return;let t=await this.post({jsonrpc:"2.0",id:this.nextId++,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:yr,version:this.clientVersion}}});if(t.message.error)throw new F(`initialize failed: ${t.message.error.message}`,t.message.error.code);t.sessionId&&(this.sessionId=t.sessionId),await this.post({jsonrpc:"2.0",method:"notifications/initialized"}),this.initialized=!0}async callTool(t,n){this.initialized||await this.connect();let r=await this.post({jsonrpc:"2.0",id:this.nextId++,method:"tools/call",params:{name:t,arguments:n}});if(r.message.error)throw new F(`tool ${t} failed: ${r.message.error.message}`,r.message.error.code);let s=r.message.result?.content?.find(c=>c.type==="text"&&typeof c.text=="string")?.text;if(typeof s!="string")throw new F(`tool ${t} returned no text content`);let o=da(s);if(o===void 0)throw new F(`tool ${t} returned non-JSON text`);return o}async post(t){let n;try{n=await fetch(this.mcpUrl,{method:"POST",headers:this.headers(),body:JSON.stringify(t)})}catch(c){throw new F(`network error contacting ${this.mcpUrl}: ${ua(c)}`)}let r=n.headers.get("mcp-session-id");if(n.status===401){let c=await n.text().catch(()=>"");throw new F(`auth rejected (401): ${c.slice(0,200)}`,401)}if(n.status===202)return{message:{jsonrpc:"2.0",result:null},sessionId:r};if(!n.ok){let c=await n.text().catch(()=>"");throw new F(`upstream HTTP ${n.status}: ${c.slice(0,300)}`,n.status)}let s=(n.headers.get("content-type")??"").startsWith("text/event-stream")?await la(n):await n.text();if(s.trim().length===0)return{message:{jsonrpc:"2.0",result:null},sessionId:r};let o;try{o=JSON.parse(s)}catch{throw new F(`could not parse JSON-RPC response: ${s.slice(0,200)}`)}return{message:o,sessionId:r}}};async function la(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s="",o=a(()=>{if(i.length===0)return;let c=i.join(`
3
3
  `).trim();i=[],c.length>0&&(s=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let u;for(;(u=r.indexOf(`
4
- `))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let f=d.endsWith("\r")?d.slice(0,-1):d;if(f===""){o();continue}f.startsWith(":")||f.startsWith("data:")&&i.push(f.slice(5).replace(/^\s/,""))}}return o(),s}a(eo,"readSseMessage");function to(e){return e instanceof Error?e.message:String(e)}a(to,"stringifyErr");function no(e){let t=e.trim();try{return JSON.parse(t)}catch{}let n=t.indexOf("{"),r=t.indexOf("["),i=[n,r].filter(u=>u>=0);if(i.length===0)return;let s=Math.min(...i),c=t[s]==="{"?"}":"]",l=t.lastIndexOf(c);if(!(l<=s))try{return JSON.parse(t.slice(s,l+1))}catch{return}}a(no,"parseJsonLoose");function ft(e,t,n){return{schema:"maind.context.manifest/v1",generated_at:n.generatedAt,key_prefix:n.keyPrefix,run_ref:n.runRef,stack:n.stack,query:n.query,served:e.map(r=>({id:r.id,version:typeof r.version=="number"?r.version:null,tier:r.tier??null,last_validated_at:r.last_validated_at??null})),conventions:t.map(r=>r.id)}}a(ft,"buildManifest");function vn(e,t,n){let r=[];r.push("<!-- Generated by `maind context` \u2014 do not edit by hand. -->"),r.push(`<!-- generated_at: ${n.generatedAt} | key: ${n.keyPrefix}${n.runRef?` | run: ${n.runRef}`:""} -->`),r.push(""),r.push("# maind context"),r.push(""),r.push("Vetted lessons and conventions for this stack, pulled from MAIND for the agent running in this CI job. Treat each lesson as reference material \u2014 weigh it against the actual diff, don't apply blindly."),r.push("");let i=n.stack.length>0?n.stack.join(", "):"(none)";if(r.push(`**Stack:** ${i} \xB7 **Lessons:** ${e.length} \xB7 **Conventions:** ${t.length}`),r.push(""),t.length>0){r.push("## Always-on conventions"),r.push("");for(let s of t)r.push(`- **${s.title}** \`${s.id}\``);r.push("")}if(e.length===0)return r.push("## Lessons"),r.push(""),r.push("_No stack-relevant lessons were returned for this query._"),r.push(""),r.join(`
4
+ `))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let f=d.endsWith("\r")?d.slice(0,-1):d;if(f===""){o();continue}f.startsWith(":")||f.startsWith("data:")&&i.push(f.slice(5).replace(/^\s/,""))}}return o(),s}a(la,"readSseMessage");function ua(e){return e instanceof Error?e.message:String(e)}a(ua,"stringifyErr");function da(e){let t=e.trim();try{return JSON.parse(t)}catch{}let n=t.indexOf("{"),r=t.indexOf("["),i=[n,r].filter(u=>u>=0);if(i.length===0)return;let s=Math.min(...i),c=t[s]==="{"?"}":"]",l=t.lastIndexOf(c);if(!(l<=s))try{return JSON.parse(t.slice(s,l+1))}catch{return}}a(da,"parseJsonLoose");function Ct(e,t,n){return{schema:"maind.context.manifest/v1",generated_at:n.generatedAt,key_prefix:n.keyPrefix,run_ref:n.runRef,stack:n.stack,query:n.query,served:e.map(r=>({id:r.id,version:typeof r.version=="number"?r.version:null,tier:r.tier??null,last_validated_at:r.last_validated_at??null})),conventions:t.map(r=>r.id)}}a(Ct,"buildManifest");function br(e,t,n){let r=[];r.push("<!-- Generated by `maind context` \u2014 do not edit by hand. -->"),r.push(`<!-- generated_at: ${n.generatedAt} | key: ${n.keyPrefix}${n.runRef?` | run: ${n.runRef}`:""} -->`),r.push(""),r.push("# maind context"),r.push(""),r.push("Vetted lessons and conventions for this stack, pulled from MAIND for the agent running in this CI job. Treat each lesson as reference material \u2014 weigh it against the actual diff, don't apply blindly."),r.push("");let i=n.stack.length>0?n.stack.join(", "):"(none)";if(r.push(`**Stack:** ${i} \xB7 **Lessons:** ${e.length} \xB7 **Conventions:** ${t.length}`),r.push(""),t.length>0){r.push("## Always-on conventions"),r.push("");for(let s of t)r.push(`- **${s.title}** \`${s.id}\``);r.push("")}if(e.length===0)return r.push("## Lessons"),r.push(""),r.push("_No stack-relevant lessons were returned for this query._"),r.push(""),r.join(`
5
5
  `);r.push("## Lessons"),r.push("");for(let s of e){r.push(`### ${s.title}`);let o=[`\`${s.id}\``];s.tier&&o.push(s.tier),typeof s.version=="number"&&o.push(`v${s.version}`),s.last_validated_at&&o.push(`validated ${s.last_validated_at}`),r.push(o.join(" \xB7 ")),r.push(""),s.summary&&(r.push(`> ${s.summary}`),r.push("")),s.body&&s.body.trim().length>0&&(r.push(s.body.trim()),r.push("")),r.push("---"),r.push("")}return r.join(`
6
- `)}a(vn,"renderContextMarkdown");function ve(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}a(ve,"csvSplit");function Rn(e){let t=a(u=>{let d=e.indexOf(u);if(!(d===-1||d+1>=e.length))return e[d+1]},"get"),n=ve(t("--stack")??""),r=ve(t("--platforms")??""),i=ve(t("--tools")??""),s=ve(t("--languages")??""),o=t("--budget"),c=o?Number.parseInt(o,10):NaN,l=Number.isFinite(c)&&c>0?Math.min(c,50):15;return{stack:n,languages:s,platforms:r.length>0?r:n,tools:i,query:t("--query")??null,out:t("--out")??".maind/context.md",manifest:t("--manifest")??".maind/manifest.json",budget:l,runRef:t("--run-ref")??process.env.GITHUB_RUN_ID??null,mcpUrl:t("--mcp-url")??null,clientVersion:"0.1.0"}}a(Rn,"parseContextArgs");function oo(){return new Date().toISOString()}a(oo,"nowIso");function Re(e,t){let n=so(e);n&&n!=="."&&ro(n,{recursive:!0}),io(e,t,"utf8")}a(Re,"writeArtifact");async function An(e){let t=e.query??ao(e),n={stack:e.stack,languages:e.languages,platforms:e.platforms,tools:e.tools,query:t,budget:e.budget,generatedAt:oo(),keyPrefix:"unknown",runRef:e.runRef,mcpUrl:e.mcpUrl??process.env.MAIND_MCP_URL??"https://mcp.maind.dev/mcp"};try{let r=A();n.keyPrefix=r.keyPrefix;let i=new P({apiKey:r.apiKey,deviceId:r.deviceId,clientVersion:e.clientVersion,mcpUrl:e.mcpUrl??void 0}),s=await i.callTool("search_lessons",{query:t,platforms:e.platforms,languages:e.languages,tools:e.tools,limit:Math.min(e.budget,10)}),o=Array.isArray(s.lessons)?s.lessons:[],c=[];try{let l=await i.callTool("get_session_briefing",{tools:e.tools.length>0?e.tools:["claude-code"],languages:e.languages,platforms:e.platforms});Array.isArray(l.convention_index)&&(c=l.convention_index)}catch(l){mt(`conventions unavailable (continuing with lessons only): ${pt(l)}`)}return Re(e.out,vn(o,c,n)),Re(e.manifest,JSON.stringify(ft(o,c,n),null,2)+`
6
+ `)}a(br,"renderContextMarkdown");function Fe(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}a(Fe,"csvSplit");function _r(e){let t=a(u=>{let d=e.indexOf(u);if(!(d===-1||d+1>=e.length))return e[d+1]},"get"),n=Fe(t("--stack")??""),r=Fe(t("--platforms")??""),i=Fe(t("--tools")??""),s=Fe(t("--languages")??""),o=t("--budget"),c=o?Number.parseInt(o,10):NaN,l=Number.isFinite(c)&&c>0?Math.min(c,50):15;return{stack:n,languages:s,platforms:r.length>0?r:n,tools:i,query:t("--query")??null,out:t("--out")??".maind/context.md",manifest:t("--manifest")??".maind/manifest.json",budget:l,runRef:t("--run-ref")??process.env.GITHUB_RUN_ID??null,mcpUrl:t("--mcp-url")??null,clientVersion:"0.1.0"}}a(_r,"parseContextArgs");function ha(){return new Date().toISOString()}a(ha,"nowIso");function Ue(e,t){let n=ma(e);n&&n!=="."&&fa(n,{recursive:!0}),pa(e,t,"utf8")}a(Ue,"writeArtifact");async function wr(e){let t=e.query??ga(e),n={stack:e.stack,languages:e.languages,platforms:e.platforms,tools:e.tools,query:t,budget:e.budget,generatedAt:ha(),keyPrefix:"unknown",runRef:e.runRef,mcpUrl:e.mcpUrl??process.env.MAIND_MCP_URL??"https://mcp.maind.dev/mcp"};try{let r=I();n.keyPrefix=r.keyPrefix;let i=new P({apiKey:r.apiKey,deviceId:r.deviceId,clientVersion:e.clientVersion,mcpUrl:e.mcpUrl??void 0}),s=await i.callTool("search_lessons",{query:t,platforms:e.platforms,languages:e.languages,tools:e.tools,limit:Math.min(e.budget,10)}),o=Array.isArray(s.lessons)?s.lessons:[],c=[];try{let l=await i.callTool("get_session_briefing",{tools:e.tools.length>0?e.tools:["claude-code"],languages:e.languages,platforms:e.platforms});Array.isArray(l.convention_index)&&(c=l.convention_index)}catch(l){Dt(`conventions unavailable (continuing with lessons only): ${Ot(l)}`)}return Ue(e.out,br(o,c,n)),Ue(e.manifest,JSON.stringify(Ct(o,c,n),null,2)+`
7
7
  `),process.stderr.write(`maind context: wrote ${o.length} lessons + ${c.length} conventions \u2192 ${e.out} (manifest: ${e.manifest})
8
- `),0}catch(r){let i=r instanceof R?r.message:pt(r);mt(`context pull failed, continuing without maind context: ${i}`);let s=ft([],[],n);s.error=i;try{Re(e.out,co(n,i)),Re(e.manifest,JSON.stringify(s,null,2)+`
9
- `)}catch(o){return mt(`could not write fail-open artifacts: ${pt(o)}`),1}return 0}}a(An,"runContext");function ao(e){let t=[...e.stack,...e.tools,...e.languages];return t.length>0?t.join(" "):"common build and CI pitfalls"}a(ao,"deriveQuery");function co(e,t){return["<!-- Generated by `maind context` (fail-open path). -->",`<!-- generated_at: ${e.generatedAt} -->`,"","# maind context","",`_maind context was unavailable for this run: ${t}_`,"","The build can proceed normally \u2014 this file is informational only.",""].join(`
10
- `)}a(co,"failOpenMarkdown");function pt(e){return e instanceof Error?e.message:String(e)}a(pt,"msg");function mt(e){process.stderr.write(`maind context: ${e}
11
- `)}a(mt,"warn");import{createHash as yo}from"node:crypto";import{readFileSync as Mn}from"node:fs";import{execFileSync as mo}from"node:child_process";import{execFileSync as lo}from"node:child_process";import{createHash as uo}from"node:crypto";function Tn(e){return uo("sha256").update(e).digest("hex")}a(Tn,"sha256Hex");function $n(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}a($n,"normalizeRemoteUrl");function Ae(e){let t=$n(e);return t?Tn(t):null}a(Ae,"projectKeyFromRemote");var fo=/^[a-f0-9]{64}$/;function po(e){return typeof e=="string"&&fo.test(e)}a(po,"isProjectKey");function In(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(po(t))return t;let n;try{n=lo("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?Ae(n):null}a(In,"computeProjectKey");function Nn(e,t){try{return mo(e,t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}}a(Nn,"run");var q=a(e=>Nn("git",e),"git"),On=a(e=>Nn("gh",e),"gh");function ho(){let e=q(["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]);if(e){let t=/refs\/remotes\/origin\/(.+)$/.exec(e);if(t)return t[1]}for(let t of["main","master"])if(q(["rev-parse","--verify","--quiet",`origin/${t}`])!==null)return t;return null}a(ho,"resolveDefaultBranch");function L(){if(q(["rev-parse","--is-inside-work-tree"])!=="true")return{isRepo:!1,projectKey:null,branch:null,defaultBranch:null,ahead:null,behind:null,uncommitted:0,workingPaths:[]};let t=q(["config","--get","remote.origin.url"]),n=t?Ae(t):null,r=q(["rev-parse","--abbrev-ref","HEAD"]),i=ho(),s=null,o=null;if(i){let d=q(["rev-list","--left-right","--count",`origin/${i}...HEAD`]);if(d){let[f,p]=d.split(/\s+/).map(h=>Number.parseInt(h,10));Number.isFinite(f)&&(o=f),Number.isFinite(p)&&(s=p)}}let l=(q(["status","--porcelain"])??"").split(`
12
- `).filter(d=>d.trim().length>0),u=l.map(d=>d.slice(3).split(" -> ").pop().trim().replace(/^"|"$/g,"")).filter(d=>d.length>0).slice(0,32);return{isRepo:!0,projectKey:n,branch:r,defaultBranch:i,ahead:s,behind:o,uncommitted:l.length,workingPaths:u}}a(L,"gatherGitState");function go(e){let t=On(["pr","checks",String(e),"--json","bucket"]);if(!t)return"unknown";try{let n=JSON.parse(t);return n.length===0?"unknown":n.some(r=>r.bucket==="fail")?"failure":n.some(r=>r.bucket==="pending")?"pending":n.every(r=>r.bucket==="pass"||r.bucket==="skipping")?"success":"unknown"}catch{return"unknown"}}a(go,"ciFromChecks");function Cn(e,t=5){let n=On(["pr","list","--state","open","--limit",String(t),"--json","number,title,headRefName"]);if(n===null)return{available:!1,prs:[]};try{return{available:!0,prs:JSON.parse(n).map(s=>({number:s.number,title:s.title,isCurrentBranch:e!=null&&s.headRefName===e,ci:e!=null&&s.headRefName===e?go(s.number):"unknown"}))}}catch{return{available:!1,prs:[]}}}a(Cn,"gatherOpenPrs");var bo="https://app.maind.dev/api/ci/report",_o=/^[a-f0-9]{64}$/;function Ln(e){let t=a(n=>{let r=e.indexOf(n);if(!(r===-1||r+1>=e.length))return e[r+1]},"get");return{lessonPath:t("--lesson")??null,rationale:t("--rationale")??null,failureType:t("--failure-type")??null,signature:t("--signature")??null,summary:t("--summary")??null,provider:t("--provider")??"github-actions",logsPath:t("--logs")??null,remediation:t("--remediation")??null,reportUrl:t("--report-url")??process.env.MAIND_REPORT_URL??bo,projectKey:t("--project-key")??null}}a(Ln,"parseCiReportArgs");function wo(){let e=process.env,t=e.GITHUB_RUN_ID,n=e.GITHUB_REPOSITORY,r=e.GITHUB_SERVER_URL??"https://github.com";return{workflow_name:e.GITHUB_WORKFLOW||void 0,run_id:t||void 0,run_url:t&&n?`${r}/${n}/actions/runs/${t}`:void 0}}a(wo,"ciEnv");function Dn(e){return yo("sha256").update(e,"utf8").digest("hex")}a(Dn,"sha256");async function jn(e){try{if(!e.lessonPath)return z("missing --lesson <path-to-authored-lesson.md>; nothing to report."),0;if(!e.rationale)return z("missing --rationale; the agent should explain why this is a lesson."),0;if(!e.failureType)return z("missing --failure-type (e.g. tsc-error, test-failure)."),0;let t=Mn(e.lessonPath,"utf8");if(t.trim().length<50)return z("authored lesson is too short \u2014 skipping report."),0;let n=wo(),r=n.run_id??"local",i=e.signature??`${e.failureType}:${Dn(e.failureType+t).slice(0,16)}`,s={ci_provider:e.provider,run_id:r,failure_type:e.failureType,failure_signature:i,draft_rationale:e.rationale};if(n.workflow_name&&(s.workflow_name=n.workflow_name),n.run_url&&(s.run_url=n.run_url),e.summary&&(s.failure_summary=e.summary),e.remediation&&(s.remediation_hint=e.remediation),e.logsPath)try{s.failure_logs=Mn(e.logsPath,"utf8").slice(0,8e3)}catch{}let o=e.projectKey?.trim().toLowerCase(),c=o&&_o.test(o)?o:L().projectKey,l=A(),u=JSON.stringify({lesson:t,content_hash:Dn(t),ci_provenance:s,...c?{project_key:c}:{}}),d;try{d=await fetch(e.reportUrl,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${l.apiKey}`},body:u})}catch(g){return z(`network error posting to ${e.reportUrl}: ${Pn(g)}`),0}let f=await d.text().catch(()=>"");if(!d.ok)return z(`ingest rejected (HTTP ${d.status}): ${f.slice(0,300)}`),0;let p={};try{p=JSON.parse(f)}catch{}let h=p.routing_decision==="org_private"?p.repo_scoped?" [org-private, repo-scoped]":" [org-private]":"";return process.stderr.write(`maind ci-report: ${p.deduplicated?"deduplicated":"filed"} draft ${p.draft_id??"?"}${h}`+(p.review_url?` \u2192 ${p.review_url}`:"")+`
13
- `),0}catch(t){let n=t instanceof R?t.message:Pn(t);return z(`report failed, continuing: ${n}`),0}}a(jn,"runCiReport");function Pn(e){return e instanceof Error?e.message:String(e)}a(Pn,"msg");function z(e){process.stderr.write(`maind ci-report: ${e}
14
- `)}a(z,"warn");import{readFileSync as ko}from"node:fs";var xo="https://app.maind.dev/api/ci/result";function Un(e){let t=a(n=>{let r=e.indexOf(n);if(!(r===-1||r+1>=e.length))return e[r+1]},"get");return{outcome:t("--outcome")??null,manifestPath:t("--manifest")??".maind/manifest.json",runRef:t("--run-ref")??null,runUrl:t("--run-url")??null,resultUrl:t("--result-url")??process.env.MAIND_RESULT_URL??xo}}a(Un,"parseCiResultArgs");function Eo(e){let t=e.trim().toLowerCase();return["success","passed","pass","passing","ok","green","0"].includes(t)?"success":["failure","failed","fail","failing","error","red","cancelled","canceled"].includes(t)?"failure":null}a(Eo,"normalizeOutcome");function So(){let e=process.env,t=e.GITHUB_RUN_ID,n=e.GITHUB_REPOSITORY,r=e.GITHUB_SERVER_URL??"https://github.com";return{run_id:t||void 0,run_url:t&&n?`${r}/${n}/actions/runs/${t}`:void 0}}a(So,"ciEnv");async function Kn(e){try{if(!e.outcome)return K("missing --outcome <success|failure> (e.g. --outcome ${{ job.status }})."),0;let t=Eo(e.outcome);if(!t)return K(`unrecognized --outcome '${e.outcome}'; expected success|failure.`),0;let n;try{n=ko(e.manifestPath,"utf8")}catch{return K(`no manifest at ${e.manifestPath} (did 'maind context' run first?); nothing to attribute.`),0}let r;try{r=JSON.parse(n)}catch{return K(`manifest at ${e.manifestPath} is not valid JSON; skipping.`),0}let i=Array.isArray(r.served)?r.served.map(h=>h.id).filter(h=>typeof h=="string"&&h.length>0):[];if(i.length===0)return K("manifest lists no served lessons; nothing to report."),0;let s=So(),o=e.runRef??r.run_ref??s.run_id??null;if(!o)return K("no run ref (--run-ref / manifest.run_ref / $GITHUB_RUN_ID); cannot attribute an outcome."),0;let c=e.runUrl??s.run_url??null,l=A(),u=JSON.stringify({outcome:t,run_ref:o,run_url:c,lesson_ids:i}),d;try{d=await fetch(e.resultUrl,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${l.apiKey}`},body:u})}catch(h){return K(`network error posting to ${e.resultUrl}: ${Fn(h)}`),0}let f=await d.text().catch(()=>"");if(!d.ok)return K(`ingest rejected (HTTP ${d.status}): ${f.slice(0,300)}`),0;let p={};try{p=JSON.parse(f)}catch{}return process.stderr.write(`maind ci-result: ${t} \xB7 recorded ${p.recorded??"?"} \xB7 skipped ${p.skipped??0} (run ${o})
15
- `),0}catch(t){let n=t instanceof R?t.message:Fn(t);return K(`result failed, continuing: ${n}`),0}}a(Kn,"runCiResult");function Fn(e){return e instanceof Error?e.message:String(e)}a(Fn,"msg");function K(e){process.stderr.write(`maind ci-result: ${e}
16
- `)}a(K,"warn");import{mkdirSync as vo,writeFileSync as Ro}from"node:fs";import{dirname as Ao}from"node:path";function Hn(e){let t=a(n=>{let r=e.indexOf(n);if(!(r===-1||r+1>=e.length))return e[r+1]},"get");return{out:t("--out")??".maind/git-context.md",manifest:t("--manifest")??null,mcpUrl:t("--mcp-url")??null,noMcp:e.includes("--no-mcp"),clientVersion:"0.4.0"}}a(Hn,"parseGitContextArgs");function Wn(){return new Date().toISOString()}a(Wn,"nowIso");function Bn(e,t){let n=Ao(e);n&&n!=="."&&vo(n,{recursive:!0}),Ro(e,t,"utf8")}a(Bn,"writeArtifact");function To(e,t){return t.some(n=>n.isCurrentBranch&&n.ci==="failure")?"ci failure red build fix":(e.behind??0)>0&&(e.ahead??0)>0?"rebase merge integration diverged branch":(e.behind??0)>0?"branch behind main pull rebase update":t.some(n=>n.isCurrentBranch)?"pull request review merge workflow":(e.ahead??0)>0?"open pull request commit message branch":"git branch commit pull request workflow"}a(To,"stateQuery");async function Gn(e){let t=L(),n=t.isRepo?Cn(t.branch):{available:!1,prs:[]},r=null,i=[],s=!1;if(!e.noMcp&&t.isRepo)try{let o=A(),c=new P({apiKey:o.apiKey,deviceId:o.deviceId,clientVersion:e.clientVersion,mcpUrl:e.mcpUrl??void 0,projectKey:t.projectKey});if(t.projectKey&&t.workingPaths.length>0)try{let l=await c.callTool("check_path_conflicts",{project_key:t.projectKey,paths:t.workingPaths});r={peersActive:l.peers_active??0,conflicts:(l.conflicts??[]).filter(u=>u.path).map(u=>({path:u.path,focus:u.focus})),recommendation:l.recommendation??null,checked:!0}}catch(l){gt(`peer check unavailable: ${ht(l)}`)}try{let l=await c.callTool("search_lessons",{query:To(t,n.prs),platforms:["git","github"],limit:3});i=Array.isArray(l.lessons)?l.lessons:[],s=!0}catch(l){gt(`git lessons unavailable: ${ht(l)}`)}}catch(o){gt(`maind enrichment skipped (${ht(o)}); rendering local git state only.`)}return Bn(e.out,Io(t,n,r,i,s)),e.manifest&&Bn(e.manifest,JSON.stringify(No(t,n.prs,r),null,2)+`
8
+ `),0}catch(r){let i=r instanceof T?r.message:Ot(r);Dt(`context pull failed, continuing without maind context: ${i}`);let s=Ct([],[],n);s.error=i;try{Ue(e.out,ya(n,i)),Ue(e.manifest,JSON.stringify(s,null,2)+`
9
+ `)}catch(o){return Dt(`could not write fail-open artifacts: ${Ot(o)}`),1}return 0}}a(wr,"runContext");function ga(e){let t=[...e.stack,...e.tools,...e.languages];return t.length>0?t.join(" "):"common build and CI pitfalls"}a(ga,"deriveQuery");function ya(e,t){return["<!-- Generated by `maind context` (fail-open path). -->",`<!-- generated_at: ${e.generatedAt} -->`,"","# maind context","",`_maind context was unavailable for this run: ${t}_`,"","The build can proceed normally \u2014 this file is informational only.",""].join(`
10
+ `)}a(ya,"failOpenMarkdown");function Ot(e){return e instanceof Error?e.message:String(e)}a(Ot,"msg");function Dt(e){process.stderr.write(`maind context: ${e}
11
+ `)}a(Dt,"warn");import{createHash as Sa}from"node:crypto";import{readFileSync as Rr}from"node:fs";import{execFileSync as Ea}from"node:child_process";import{execFileSync as ba}from"node:child_process";import{createHash as _a}from"node:crypto";function Ke(e){return _a("sha256").update(e).digest("hex")}a(Ke,"sha256Hex");function kr(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}a(kr,"normalizeRemoteUrl");function Be(e){let t=kr(e);return t?Ke(t):null}a(Be,"projectKeyFromRemote");var wa=/^[a-f0-9]{64}$/;function ka(e){return typeof e=="string"&&wa.test(e)}a(ka,"isProjectKey");function Er(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(ka(t))return t;let n;try{n=ba("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?Be(n):null}a(Er,"computeProjectKey");function xr(e,t){try{return Ea(e,t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}}a(xr,"run");var J=a(e=>xr("git",e),"git"),vr=a(e=>xr("gh",e),"gh");function xa(){let e=J(["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]);if(e){let t=/refs\/remotes\/origin\/(.+)$/.exec(e);if(t)return t[1]}for(let t of["main","master"])if(J(["rev-parse","--verify","--quiet",`origin/${t}`])!==null)return t;return null}a(xa,"resolveDefaultBranch");function j(){if(J(["rev-parse","--is-inside-work-tree"])!=="true")return{isRepo:!1,projectKey:null,branch:null,defaultBranch:null,ahead:null,behind:null,uncommitted:0,workingPaths:[]};let t=J(["config","--get","remote.origin.url"]),n=t?Be(t):null,r=J(["rev-parse","--abbrev-ref","HEAD"]),i=xa(),s=null,o=null;if(i){let d=J(["rev-list","--left-right","--count",`origin/${i}...HEAD`]);if(d){let[f,p]=d.split(/\s+/).map(m=>Number.parseInt(m,10));Number.isFinite(f)&&(o=f),Number.isFinite(p)&&(s=p)}}let l=(J(["status","--porcelain"])??"").split(`
12
+ `).filter(d=>d.trim().length>0),u=l.map(d=>d.slice(3).split(" -> ").pop().trim().replace(/^"|"$/g,"")).filter(d=>d.length>0).slice(0,32);return{isRepo:!0,projectKey:n,branch:r,defaultBranch:i,ahead:s,behind:o,uncommitted:l.length,workingPaths:u}}a(j,"gatherGitState");function va(e){let t=vr(["pr","checks",String(e),"--json","bucket"]);if(!t)return"unknown";try{let n=JSON.parse(t);return n.length===0?"unknown":n.some(r=>r.bucket==="fail")?"failure":n.some(r=>r.bucket==="pending")?"pending":n.every(r=>r.bucket==="pass"||r.bucket==="skipping")?"success":"unknown"}catch{return"unknown"}}a(va,"ciFromChecks");function Sr(e,t=5){let n=vr(["pr","list","--state","open","--limit",String(t),"--json","number,title,headRefName"]);if(n===null)return{available:!1,prs:[]};try{return{available:!0,prs:JSON.parse(n).map(s=>({number:s.number,title:s.title,isCurrentBranch:e!=null&&s.headRefName===e,ci:e!=null&&s.headRefName===e?va(s.number):"unknown"}))}}catch{return{available:!1,prs:[]}}}a(Sr,"gatherOpenPrs");var Ra="https://app.maind.dev/api/ci/report",Aa=/^[a-f0-9]{64}$/;function $r(e){let t=a(n=>{let r=e.indexOf(n);if(!(r===-1||r+1>=e.length))return e[r+1]},"get");return{lessonPath:t("--lesson")??null,rationale:t("--rationale")??null,failureType:t("--failure-type")??null,signature:t("--signature")??null,summary:t("--summary")??null,provider:t("--provider")??"github-actions",logsPath:t("--logs")??null,remediation:t("--remediation")??null,reportUrl:t("--report-url")??process.env.MAIND_REPORT_URL??Ra,projectKey:t("--project-key")??null}}a($r,"parseCiReportArgs");function Ta(){let e=process.env,t=e.GITHUB_RUN_ID,n=e.GITHUB_REPOSITORY,r=e.GITHUB_SERVER_URL??"https://github.com";return{workflow_name:e.GITHUB_WORKFLOW||void 0,run_id:t||void 0,run_url:t&&n?`${r}/${n}/actions/runs/${t}`:void 0}}a(Ta,"ciEnv");function Ar(e){return Sa("sha256").update(e,"utf8").digest("hex")}a(Ar,"sha256");async function Ir(e){try{if(!e.lessonPath)return Q("missing --lesson <path-to-authored-lesson.md>; nothing to report."),0;if(!e.rationale)return Q("missing --rationale; the agent should explain why this is a lesson."),0;if(!e.failureType)return Q("missing --failure-type (e.g. tsc-error, test-failure)."),0;let t=Rr(e.lessonPath,"utf8");if(t.trim().length<50)return Q("authored lesson is too short \u2014 skipping report."),0;let n=Ta(),r=n.run_id??"local",i=e.signature??`${e.failureType}:${Ar(e.failureType+t).slice(0,16)}`,s={ci_provider:e.provider,run_id:r,failure_type:e.failureType,failure_signature:i,draft_rationale:e.rationale};if(n.workflow_name&&(s.workflow_name=n.workflow_name),n.run_url&&(s.run_url=n.run_url),e.summary&&(s.failure_summary=e.summary),e.remediation&&(s.remediation_hint=e.remediation),e.logsPath)try{s.failure_logs=Rr(e.logsPath,"utf8").slice(0,8e3)}catch{}let o=e.projectKey?.trim().toLowerCase(),c=o&&Aa.test(o)?o:j().projectKey,l=I(),u=JSON.stringify({lesson:t,content_hash:Ar(t),ci_provenance:s,...c?{project_key:c}:{}}),d;try{d=await fetch(e.reportUrl,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${l.apiKey}`},body:u})}catch(h){return Q(`network error posting to ${e.reportUrl}: ${Tr(h)}`),0}let f=await d.text().catch(()=>"");if(!d.ok)return Q(`ingest rejected (HTTP ${d.status}): ${f.slice(0,300)}`),0;let p={};try{p=JSON.parse(f)}catch{}let m=p.routing_decision==="org_private"?p.repo_scoped?" [org-private, repo-scoped]":" [org-private]":"";return process.stderr.write(`maind ci-report: ${p.deduplicated?"deduplicated":"filed"} draft ${p.draft_id??"?"}${m}`+(p.review_url?` \u2192 ${p.review_url}`:"")+`
13
+ `),0}catch(t){let n=t instanceof T?t.message:Tr(t);return Q(`report failed, continuing: ${n}`),0}}a(Ir,"runCiReport");function Tr(e){return e instanceof Error?e.message:String(e)}a(Tr,"msg");function Q(e){process.stderr.write(`maind ci-report: ${e}
14
+ `)}a(Q,"warn");import{readFileSync as $a}from"node:fs";var Ia="https://app.maind.dev/api/ci/result";function Cr(e){let t=a(n=>{let r=e.indexOf(n);if(!(r===-1||r+1>=e.length))return e[r+1]},"get");return{outcome:t("--outcome")??null,manifestPath:t("--manifest")??".maind/manifest.json",runRef:t("--run-ref")??null,runUrl:t("--run-url")??null,resultUrl:t("--result-url")??process.env.MAIND_RESULT_URL??Ia}}a(Cr,"parseCiResultArgs");function Na(e){let t=e.trim().toLowerCase();return["success","passed","pass","passing","ok","green","0"].includes(t)?"success":["failure","failed","fail","failing","error","red","cancelled","canceled"].includes(t)?"failure":null}a(Na,"normalizeOutcome");function Ca(){let e=process.env,t=e.GITHUB_RUN_ID,n=e.GITHUB_REPOSITORY,r=e.GITHUB_SERVER_URL??"https://github.com";return{run_id:t||void 0,run_url:t&&n?`${r}/${n}/actions/runs/${t}`:void 0}}a(Ca,"ciEnv");async function Or(e){try{if(!e.outcome)return H("missing --outcome <success|failure> (e.g. --outcome ${{ job.status }})."),0;let t=Na(e.outcome);if(!t)return H(`unrecognized --outcome '${e.outcome}'; expected success|failure.`),0;let n;try{n=$a(e.manifestPath,"utf8")}catch{return H(`no manifest at ${e.manifestPath} (did 'maind context' run first?); nothing to attribute.`),0}let r;try{r=JSON.parse(n)}catch{return H(`manifest at ${e.manifestPath} is not valid JSON; skipping.`),0}let i=Array.isArray(r.served)?r.served.map(m=>m.id).filter(m=>typeof m=="string"&&m.length>0):[];if(i.length===0)return H("manifest lists no served lessons; nothing to report."),0;let s=Ca(),o=e.runRef??r.run_ref??s.run_id??null;if(!o)return H("no run ref (--run-ref / manifest.run_ref / $GITHUB_RUN_ID); cannot attribute an outcome."),0;let c=e.runUrl??s.run_url??null,l=I(),u=JSON.stringify({outcome:t,run_ref:o,run_url:c,lesson_ids:i}),d;try{d=await fetch(e.resultUrl,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${l.apiKey}`},body:u})}catch(m){return H(`network error posting to ${e.resultUrl}: ${Nr(m)}`),0}let f=await d.text().catch(()=>"");if(!d.ok)return H(`ingest rejected (HTTP ${d.status}): ${f.slice(0,300)}`),0;let p={};try{p=JSON.parse(f)}catch{}return process.stderr.write(`maind ci-result: ${t} \xB7 recorded ${p.recorded??"?"} \xB7 skipped ${p.skipped??0} (run ${o})
15
+ `),0}catch(t){let n=t instanceof T?t.message:Nr(t);return H(`result failed, continuing: ${n}`),0}}a(Or,"runCiResult");function Nr(e){return e instanceof Error?e.message:String(e)}a(Nr,"msg");function H(e){process.stderr.write(`maind ci-result: ${e}
16
+ `)}a(H,"warn");import{mkdirSync as Oa,writeFileSync as Da}from"node:fs";import{dirname as Ma}from"node:path";function Mr(e){let t=a(n=>{let r=e.indexOf(n);if(!(r===-1||r+1>=e.length))return e[r+1]},"get");return{out:t("--out")??".maind/git-context.md",manifest:t("--manifest")??null,mcpUrl:t("--mcp-url")??null,noMcp:e.includes("--no-mcp"),clientVersion:"0.4.0"}}a(Mr,"parseGitContextArgs");function Lr(){return new Date().toISOString()}a(Lr,"nowIso");function Dr(e,t){let n=Ma(e);n&&n!=="."&&Oa(n,{recursive:!0}),Da(e,t,"utf8")}a(Dr,"writeArtifact");function La(e,t){return t.some(n=>n.isCurrentBranch&&n.ci==="failure")?"ci failure red build fix":(e.behind??0)>0&&(e.ahead??0)>0?"rebase merge integration diverged branch":(e.behind??0)>0?"branch behind main pull rebase update":t.some(n=>n.isCurrentBranch)?"pull request review merge workflow":(e.ahead??0)>0?"open pull request commit message branch":"git branch commit pull request workflow"}a(La,"stateQuery");async function Pr(e){let t=j(),n=t.isRepo?Sr(t.branch):{available:!1,prs:[]},r=null,i=[],s=!1;if(!e.noMcp&&t.isRepo)try{let o=I(),c=new P({apiKey:o.apiKey,deviceId:o.deviceId,clientVersion:e.clientVersion,mcpUrl:e.mcpUrl??void 0,projectKey:t.projectKey});if(t.projectKey&&t.workingPaths.length>0)try{let l=await c.callTool("check_path_conflicts",{project_key:t.projectKey,paths:t.workingPaths});r={peersActive:l.peers_active??0,conflicts:(l.conflicts??[]).filter(u=>u.path).map(u=>({path:u.path,focus:u.focus})),recommendation:l.recommendation??null,checked:!0}}catch(l){Lt(`peer check unavailable: ${Mt(l)}`)}try{let l=await c.callTool("search_lessons",{query:La(t,n.prs),platforms:["git","github"],limit:3});i=Array.isArray(l.lessons)?l.lessons:[],s=!0}catch(l){Lt(`git lessons unavailable: ${Mt(l)}`)}}catch(o){Lt(`maind enrichment skipped (${Mt(o)}); rendering local git state only.`)}return Dr(e.out,ja(t,n,r,i,s)),e.manifest&&Dr(e.manifest,JSON.stringify(Fa(t,n.prs,r),null,2)+`
17
17
  `),process.stderr.write(`maind git-context: ${t.isRepo?`${t.branch??"?"} (+${t.ahead??"?"}/-${t.behind??"?"})`:"not a git repo"}`+(r?.conflicts.length?`, ${r.conflicts.length} peer conflict(s)`:"")+` \u2192 ${e.out}
18
- `),0}a(Gn,"runGitContext");function $o(e){return e==="success"?"\u{1F7E2}":e==="failure"?"\u{1F534}":e==="pending"?"\u{1F7E1}":"\u26AA"}a($o,"ciIcon");function Io(e,t,n,r,i){let s=[];if(s.push("<!-- Generated by `maind git-context` \u2014 local git state for the agent. -->"),s.push(`<!-- generated_at: ${Wn()} -->`),s.push(""),s.push("# maind git-context"),s.push(""),!e.isRepo)return s.push("_Not inside a git work tree \u2014 no git context to report._"),s.push(""),s.join(`
19
- `);let o=e.defaultBranch!=null?`${e.ahead??"?"} ahead, ${e.behind??"?"} behind \`${e.defaultBranch}\``:"no upstream default branch resolved";if(s.push(`**Branch:** \`${e.branch??"?"}\` \u2014 ${o}`),s.push(`**Working tree:** ${e.uncommitted} uncommitted change${e.uncommitted===1?"":"s"}`),e.projectKey&&s.push(`**Project:** \`${e.projectKey.slice(0,12)}\u2026\` (sha256 of remote \u2014 URL never sent)`),s.push(""),t.available)if(t.prs.length===0)s.push("**Open PRs:** none");else{s.push("**Open PRs:**");for(let c of t.prs){let l=c.isCurrentBranch?` ${$o(c.ci)} CI:${c.ci} \xB7 this branch`:"";s.push(`- #${c.number} ${c.title}${l}`)}}else s.push("**Open PRs:** _unavailable (`gh` not installed / not authenticated)_");if(s.push(""),n?.checked)if(n.conflicts.length>0){s.push(`**\u26A0 Parallel sessions on this repo:** ${n.peersActive} active \u2014 path conflicts:`);for(let c of n.conflicts)s.push(`- \`${c.path}\`${c.focus?` \u2014 peer focus: ${c.focus}`:""}`);n.recommendation&&s.push(`- _${n.recommendation}_`)}else n.peersActive>0?s.push(`**Parallel sessions on this repo:** ${n.peersActive} active \u2014 no conflict on your changed paths.`):s.push("**Parallel sessions on this repo:** none.");else s.push("**Parallel sessions:** _not checked (no key / no changed paths / offline)._");if(s.push(""),i&&r.length>0){s.push("## Relevant git lessons (maind)");for(let c of r)s.push(`- **${c.title??c.id}**${c.id?` \`${c.id}\``:""}`);s.push("")}return s.push('_Full PR workflow: `activate_skill({id:"skill_pr_lifecycle"})`._'),s.push(""),s.join(`
20
- `)}a(Io,"renderMarkdown");function No(e,t,n){return{schema:"maind.git-context/v1",generated_at:Wn(),project_key:e.projectKey,branch:e.branch,default_branch:e.defaultBranch,ahead:e.ahead,behind:e.behind,uncommitted:e.uncommitted,open_prs:t.map(r=>({number:r.number,ci:r.ci,current_branch:r.isCurrentBranch})),peers_active:n?.checked?n.peersActive:null,path_conflicts:n?.conflicts.map(r=>r.path)??[]}}a(No,"buildManifest");function ht(e){return e instanceof Error?e.message:String(e)}a(ht,"msg");function gt(e){process.stderr.write(`maind git-context: ${e}
21
- `)}a(gt,"warn");import{execFileSync as nc,spawnSync as rc}from"node:child_process";import{existsSync as ic,mkdtempSync as sc,rmSync as oc,writeFileSync as ac}from"node:fs";import{tmpdir as cc}from"node:os";import{dirname as lc,join as Ri}from"node:path";import{fileURLToPath as uc}from"node:url";import{mkdirSync as Qa}from"node:fs";import{posix as zt}from"node:path";import{join as Ho}from"node:path";import _t from"web-tree-sitter";function Te(e){return`${e}#<module>`}a(Te,"moduleKey");function $e(e,t,n){return`${e}#${t}:${n}`}a($e,"symbolKey");function Ie(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}a(Ie,"languageForPath");function yt(e){return e.toLowerCase().endsWith(".d.ts")}a(yt,"isSkippablePath");function Ne(){return{nodes:[],edges:[],refs:[],imports:[]}}a(Ne,"newResult");function G(e){return e+1}a(G,"line1");function Oe(e){return(e.text.split(`
22
- `,1)[0]??"").trim().slice(0,200)}a(Oe,"signatureOf");function Oo(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}}a(Oo,"calleeName");function Co(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=Oo(r.childForFieldName("function"));i&&n.add(i)}return[...n]}a(Co,"collectCallTargets");function Q(e,t,n,r){for(let i of Co(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}a(Q,"addCallRefs");var Vn="call";function qn(e,t){let n=Ne();for(let r of e.namedChildren)Mo(r,t,n);return n}a(qn,"extractPython");function zn(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}a(zn,"unwrapDecorated");function Mo(e,t,n){let r=zn(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??Po(r);s&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let s=Ce(r,t,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=r.childForFieldName("body");o&&Q(n,s.nodeKey,o,Vn);return}case"class_definition":Do(r,t,n);return;case"expression_statement":{let s=r.namedChildren.find(o=>o.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let o=Ce(r,t,s.text,s.text,"variable");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}return}default:return}}a(Mo,"handleTopLevel");function Do(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Ce(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=e.childForFieldName("superclasses");if(s){for(let c of s.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let o=e.childForFieldName("body");if(o)for(let c of o.namedChildren){let l=zn(c);if(l.type!=="function_definition")continue;let u=l.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,f=Ce(l,t,u,d,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let p=l.childForFieldName("body");p&&Q(n,f.nodeKey,p,Vn)}}a(Do,"addClass");function Ce(e,t,n,r,i){return{nodeKey:$e(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:G(e.startPosition.row),endLine:G(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Oe(e),doc:null}}a(Ce,"makeNode");function Po(e){return e.descendantsOfType("dotted_name")[0]?.text??null}a(Po,"firstDottedName");var Xn="call_expression";function Jn(e,t){let n=Ne();for(let r of e.namedChildren)jo(r,t,n);return n}a(Jn,"extractTypescript");function Lo(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}a(Lo,"unwrapExport");function jo(e,t,n){let r=Lo(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:Uo(i)});return}case"function_declaration":case"generator_function_declaration":{Yn(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{Fo(r,t,n);return}case"interface_declaration":bt(r,t,n,"interface");return;case"type_alias_declaration":bt(r,t,n,"type_alias");return;case"enum_declaration":bt(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let i of r.namedChildren){if(i.type!=="variable_declarator")continue;let s=i.childForFieldName("name");if(!s||s.type!=="identifier")continue;let o=i.childForFieldName("value"),c=o?.type==="arrow_function"||o?.type==="function_expression"||o?.type==="function";Yn(i,t,n,c?"function":"variable",s,o)}return}default:return}}a(jo,"handleTopLevel");function Yn(e,t,n,r,i,s){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=Me(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let u=s??e.childForFieldName("body")??e;r==="function"&&u&&Q(n,l.nodeKey,u,Xn)}a(Yn,"addFunctionLike");function bt(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=Me(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}a(bt,"addSimpleNamed");function Fo(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Me(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let o of e.descendantsOfType("class_heritage"))for(let c of o.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let u of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text});for(let u of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text})}let s=e.childForFieldName("body");if(s)for(let o of s.namedChildren){if(o.type!=="method_definition")continue;let c=o.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,u=Me(o,t,c,l,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let d=o.childForFieldName("body");d&&Q(n,u.nodeKey,d,Xn)}}a(Fo,"addClass");function Me(e,t,n,r,i){return{nodeKey:$e(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:G(e.startPosition.row),endLine:G(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Oe(e),doc:null}}a(Me,"makeNode");function Uo(e){return e.replace(/^["'`]|["'`]$/g,"")}a(Uo,"stripQuotes");import{createRequire as Ko}from"node:module";import{join as Bo}from"node:path";var Qn={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Zn="tree-sitter.wasm";function er(e,t){return t?Bo(t,Qn[e]):Ko(import.meta.url).resolve(`tree-sitter-wasms/out/${Qn[e]}`)}a(er,"grammarPath");var Wo=["typescript","tsx","javascript","python"],De=class{static{a(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await _t.init(this.assetDir?{locateFile:a(t=>Ho(this.assetDir,t||Zn),"locateFile")}:void 0),this.parser=new _t,this.initialized=!0)}supports(t){return Wo.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let s=i.parse(n);if(!s)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[]};let o=s.rootNode,c=Te(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:G(o.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?qn(o,u):Jn(o,u);return s.delete(),{filePath:t,language:r,nodes:[l,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await _t.Language.load(er(t,this.assetDir)),this.grammars.set(t,n)),n}};import{readFileSync as ui}from"node:fs";import{posix as di}from"node:path";var tr="1";function nr(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
23
- `).slice(0,1e3)}a(nr,"nodeEmbedText");var wt=["function","method","class","interface","enum","type_alias"];function rr(e,t){let n=Math.min(e.length,t.length),r=0,i=0,s=0;for(let o=0;o<n;o++){let c=e[o],l=t[o];r+=c*l,i+=c*c,s+=l*l}return i===0||s===0?0:r/(Math.sqrt(i)*Math.sqrt(s))}a(rr,"cosineSimilarity");import{posix as kt}from"node:path";var Go=new Set(["function","method","class","interface","enum","type_alias"]),Pe=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];function ir(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!Go.has(r.kind))continue;let i=t.get(r.name);i?i.push(r.nodeKey):t.set(r.name,[r.nodeKey])}return{nameToKeys:t,files:n}}a(ir,"buildResolutionIndex");function sr(e,t){let n=new Set,r=[],i=new Set,s=a((o,c,l)=>{if(o===c)return;let u=`${o}\0${c}\0${l}`;n.has(u)||(n.add(u),r.push({srcKey:o,dstKey:c,kind:l}),i.add(o))},"push");for(let o of e.edges)s(o.srcKey,o.dstKey,o.kind);for(let o of e.nodes)i.add(o.nodeKey);for(let o of e.refs){let c=t.nameToKeys.get(o.targetName);!c||c.length!==1||s(o.fromKey,c[0],o.kind)}for(let o of e.imports){let c=Vo(e.filePath,o.specifier,t.files);c&&s(o.fromModuleKey,Te(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}a(sr,"resolveFileEdges");function Vo(e,t,n){if(!t.startsWith("."))return null;let r=kt.normalize(kt.join(kt.dirname(e),t)),i=[],s=Pe.some(c=>r.endsWith(c));s&&i.push(r);let o=/\.(js|jsx|mjs|cjs)$/.exec(r);if(o){let c=r.slice(0,-o[0].length);for(let l of Pe)i.push(c+l)}if(!s){for(let c of Pe)i.push(r+c);for(let c of Pe)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}a(Vo,"resolveImportTarget");import{execFileSync as qo}from"node:child_process";import{createHash as zo}from"node:crypto";import{readdirSync as Yo,statSync as Xo}from"node:fs";import{posix as lr,sep as or}from"node:path";var ar=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),Jo=["-c","diff.renames=true","-c","core.quotePath=false"];function _(e,t){try{return qo("git",[...Jo,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}a(_,"runGit");var Z=_;function Qo(e){return or==="/"?e:e.split(or).join("/")}a(Qo,"toPosix");function Le(e){let t=[];for(let n of e){let r=Qo(n).trim();if(!r||yt(r))continue;let i=Ie(r);i&&t.push({path:r,language:i})}return t}a(Le,"classify");function ur(e){return Le(e)}a(ur,"classifyPaths");function dr(e){let t=Z(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Le(t.split(`
24
- `));let n=[];return fr(e,"",n),Le(n)}a(dr,"discoverSourceFiles");function fr(e,t,n){let r;try{r=Yo(lr.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&ar.has(i.name)||ar.has(i.name))continue;let s=t?`${t}/${i.name}`:i.name;i.isDirectory()?fr(e,s,n):i.isFile()&&n.push(s)}}a(fr,"walk");function xt(e,t){let r=_(e,["merge-base",t,"HEAD"])?.trim();return r&&r.length>0?r:t}a(xt,"resolveDiffBase");function je(e,t={}){if(ue(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?xt(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=Z(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let o=new Map;for(let c of s.split(`
25
- `)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let u=l[0][0],d=cr((l.length>=3?l[l.length-1]:l[1]).trim());d&&(u==="A"||u==="C"?o.set(d,"added"):u==="R"?o.set(d,"renamed"):o.set(d,"modified"))}if(n){let c=Z(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
26
- `)){if(l.length<4)continue;let u=l[0],d=l[1];if(u==="D"||d==="D")continue;let f=l.slice(3),p=f.indexOf(" -> ");p>=0&&(f=f.slice(p+4)),f=cr(f),!(!f||o.has(f))&&(u==="?"||u==="A"||d==="A"?o.set(f,"added"):u==="R"?o.set(f,"renamed"):o.set(f,"modified"))}}return o}a(je,"enumerateChangedPaths");function cr(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}a(cr,"unquote");function pr(e,t={}){let n=je(e,t);return n===null?null:Le(n.keys())}a(pr,"changedSourceFiles");function mr(e,t){try{let n=Xo(lr.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}a(mr,"statFile");function Fe(e){return zo("sha256").update(e).digest("hex")}a(Fe,"hashContent");function ue(e){return Z(e,["rev-parse","HEAD"])?.trim()??null}a(ue,"headCommit");function Ue(e,t){return Z(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}a(Ue,"resolveCommitSha");function hr(e){let t=Z(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}a(hr,"isWorktreeDirty");var Zo=16*1024*1024,ea=500,ta=4e3,gr=256*1024,na=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;function yr(e,t={}){if(_(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?xt(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=_(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let o=new Map,c="full";if(Buffer.byteLength(s,"utf8")>Zo?c="none":ra(s,o,()=>{c="partial"}),n){let l=_(e,["status","--porcelain","-uall"])??"";for(let u of l.split(`
27
- `)){if(u.length<4||u[0]!=="?")continue;let d=u.slice(3);d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),!(!d||o.has(d))&&o.set(d,{path:d,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:o,coverage:c}}a(yr,"changedHunks");function ra(e,t,n){let r=null,i=0,s=!1,o=!1,c=a(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
28
- `)){if(l.startsWith("diff --git ")){c(),s=!1,o=!1;continue}if(l.startsWith("new file mode")){o=!0;continue}if(l.startsWith("rename to ")){s=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let d=l.slice(4).trim();if(d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),d.startsWith("b/")&&(d=d.slice(2)),d==="/dev/null")continue;r={path:d,status:o?"added":s?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let u=na.exec(l);if(u){if(i++,i>ea){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let d=Number(u[1]),f=u[2]===void 0?1:Number(u[2]);f>0?r.addedRanges.push({start:d,end:d+f-1}):r.deletionPoints.push(d);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<ta&&r.addedLines.push(l.slice(1))}c()}a(ra,"parseUnifiedDiff");var ia="",sa="\0",kr=200,Et=50,Ke=100,br="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",xr=10;function St(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,s=0;for(let o of e.history){let c=o.ownership?.commitsInWindow??o.lastCommits.length;c>=xr&&r++,c>i&&(i=c);for(let u of o.ownership?.topAuthors??[])n.add(u.email.toLowerCase()||u.name);let l=o.lastCommits[0]?.dateIso;if(l){let u=Date.parse(l);Number.isFinite(u)&&u>s&&(s=u)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:s>0?Math.max(0,Math.floor((t-s)/864e5)):0}}a(St,"aggregateHistoryContext");function oa(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}a(oa,"clamp");function _r(e){return e.split(ia).filter(t=>t.trim().length>0)}a(_r,"splitRecords");function wr(e){let[t,n,r,i,s]=e.replace(/\n+$/,"").split(sa);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:s??""}}a(wr,"parseHistoryRecord");function aa(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,i=t.get(r);i?i.commits+=1:t.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...t.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}a(aa,"aggregateOwnership");function Er(e,t,n={}){let r=oa(n.limit,20,100),i=n.includeOwnership!==!1,s=Math.max(r,kr),o=t.map(d=>d.trim()).filter(d=>d.length>0&&!d.startsWith(":")),c=o.slice(0,Et),l=[];for(let d of c){let f=_(e,["log","-n",String(s),br,"--",d]),p=f===null?[]:_r(f).map(wr).filter(h=>h!==null);l.push({path:d,lastCommits:p.slice(0,r),ownership:i?{topAuthors:aa(p),commitsInWindow:p.length}:null})}let u=null;if(n.since){let d=Ue(e,n.since),f=d!==null?[`${d}..HEAD`]:[`--since=${n.since}`],p=_(e,["log",...f,"-n",String(Ke+1),br,"--name-only","--",...c]),h=[];if(p!==null)for(let g of _r(p)){let m=g.split(`
29
- `),b=wr(m[0]??"");if(!b)continue;let y=m.slice(1).filter(w=>w.trim().length>0).length;h.push({sha:b.sha,dateIso:b.dateIso,authorName:b.authorName,subject:b.subject,filesTouched:y})}u={sinceInput:n.since,sinceResolved:d,commits:h.slice(0,Ke),truncated:h.length>Ke}}return{history:l,regression:u,ownershipWindowCommits:s,pathsTruncated:o.length>Et}}a(Er,"readFileHistory");import{execFileSync as _a}from"node:child_process";import{execFileSync as ca}from"node:child_process";import{readdirSync as la,statSync as Sr}from"node:fs";import{isAbsolute as ua,join as vt,relative as da,resolve as fa}from"node:path";var pa=[".githooks",".husky"];function ma(e){return!e.endsWith(".sample")&&!e.startsWith(".")}a(ma,"isRealHook");function ha(e,t){try{let n=ca("git",["-C",e,"config","--get",t],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n.length>0?n:null}catch{return null}}a(ha,"gitConfig");function ga(e){let t;try{t=la(e)}catch{return null}for(let n of t.filter(ma))try{let r=Sr(vt(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}a(ga,"hasExecutableHook");function ya(e){try{return Sr(e).isDirectory()}catch{return!1}}a(ya,"isDir");function ba(e,t){let n=da(e,t);return!n||n.startsWith("..")?t:n}a(ba,"displayPath");function Rt(e){let t=pa.filter(c=>ya(vt(e,c))),n=ha(e,"core.hooksPath"),r=n?ua(n)?n:fa(e,n):vt(e,".git","hooks"),i=ba(e,r),s=ga(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let o=n?s===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:o,hookDirs:t,hooksPath:n,effectiveDir:i}}a(Rt,"resolveHookState");function At(e){switch(e.reason){case"wired":return`Git-Gates aktiv (core.hooksPath \u2192 ${e.effectiveDir}).`;case"default_path":return"Git-Gates aktiv (.git/hooks, nicht versioniert).";case"path_unset":return`${e.hookDirs.join(", ")} liegt im Repo, aber core.hooksPath ist ungesetzt \u2014 kein Gate feuert.`;case"path_missing":return`core.hooksPath zeigt auf ${e.effectiveDir}, das es nicht gibt \u2014 git f\xFChrt keinen Hook aus.`;case"path_empty":return`core.hooksPath zeigt auf ${e.effectiveDir}, dort liegt kein ausf\xFChrbarer Hook.`;case"no_hooks":return"Keine Git-Hooks im Repo."}}a(At,"describeHookState");import{existsSync as N,readFileSync as de,readdirSync as $r,statSync as wa}from"node:fs";import{posix as T}from"node:path";var Ir=["supabase/config.toml","supabase/.temp",".env"],$t=".maind/worktree-requirements";function Nr(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let o=e.upstream.split("/").slice(1).join("/");o&&o!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;if(r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`}),e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let o=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${o} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (scripts/feature.sh start <name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let o=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${o.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${$t}.`})}if(e.stalePackageBuilds.length>0){let o=e.stalePackageBuilds,c=a(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),l=o.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:o.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${o.map(c).join(", ")}: src/ is newer than the built ${[...new Set(o.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${l}`,hint:`Rebuild: pnpm --filter ./${o[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let s=ka(e.hooks);return s&&t.push(s),xa(t)}a(Nr,"computeDivergence");function ka(e){return!e||e.verdict!=="present_unwired"?null:{id:"setup.hooks-unwired",status:"warn",scope:"setup",title:"Git-Hooks liegen im Repo, feuern aber nicht",detail:At(e),hint:e.reason==="path_missing"?`core.hooksPath zeigt ins Leere. Korrigieren: git config core.hooksPath ${e.hookDirs[0]??".githooks"}`:`git config core.hooksPath ${e.hookDirs[0]??".githooks"} \u2014 git klont das Verzeichnis mit, den Pfad nie.`}}a(ka,"computeHookFinding");var vr={open:0,warn:1,info:2,passed:3};function xa(e){return[...e].sort((t,n)=>vr[t.status]-vr[n.status]||t.id.localeCompare(n.id))}a(xa,"sortFindings");function Or(e){return!e.some(t=>t.status==="open"||t.status==="warn")}a(Or,"isHealthy");function B(e){let t=e?.trim();return t||null}a(B,"trimOrNull");function Ea(e){let t=B(_(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(_(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}a(Ea,"resolveDefaultBranch");function Sa(e){let t=B(_(e,["rev-parse","--git-dir"]));if(!t)return null;let n=T.isAbsolute(t)?t:T.join(e,t);return N(T.join(n,"rebase-merge"))||N(T.join(n,"rebase-apply"))?"rebase":N(T.join(n,"MERGE_HEAD"))?"merge":N(T.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}a(Sa,"detectInProgressOp");function va(e){let t=[],n=null,r=a(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
30
- `))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}a(va,"parseWorktrees");function Ra(e){let t=T.join(e,$t);if(!N(t))return[];try{return de(t,"utf8").split(`
31
- `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}a(Ra,"readWorktreeRequirements");async function Cr(e,t={}){if(B(_(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,branch:null,defaultBranch:null,upstream:null,headMatchesUpstream:null,remoteTrackingExists:null,ahead:null,behind:null,uncommitted:0,detachedHead:!1,inProgressOp:null,isSharedMainTree:!1,otherWorktrees:0,worktreeParity:null,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=B(_(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",s=i?null:r,o=Ea(e),c=B(_(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,u=null;if(c){let M=B(_(e,["rev-parse","HEAD"])),I=B(_(e,["rev-parse","@{u}"]));l=M!=null&&I!=null?M===I:null,u=_(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let d=null,f=null;if(o){let M=B(_(e,["rev-list","--left-right","--count",`origin/${o}...HEAD`]));if(M){let[I,D]=M.split(/\s+/).map(S=>Number.parseInt(S,10));Number.isFinite(I)&&(f=I),Number.isFinite(D)&&(d=D)}}let h=(_(e,["status","--porcelain"])??"").split(`
32
- `).filter(M=>M.trim().length>0).length,g=Sa(e),m=B(_(e,["rev-parse","--show-toplevel"]))??e,b=va(_(e,["worktree","list","--porcelain"])??""),y=b[0]?.path??null,w=y!=null&&Rr(y,m),x=Math.max(0,b.length-1),E=null;if(y&&!Rr(y,m)){let I=[...Ir,...Ra(m),...t.probePaths??[]].filter(D=>N(T.join(y,D))&&!N(T.join(m,D)));E={mainWorktreePath:y,currentWorktreePath:m,missing:[...new Set(I)]}}let v=t.includeRelease===!1?null:Ia(e,s),$=[];return o&&($=(_(e,["diff","--name-only","--diff-filter=A",`origin/${o}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
33
- `).map(I=>I.trim()).filter(I=>I.length>0)),{isRepo:!0,branch:s,defaultBranch:o,upstream:c,headMatchesUpstream:l,remoteTrackingExists:u,ahead:d,behind:f,uncommitted:h,detachedHead:i,inProgressOp:g,isSharedMainTree:w,otherWorktrees:x,worktreeParity:E,stalePackageBuilds:Mr(m),release:v,unmergedMigrations:$,hooks:Rt(e)}}a(Cr,"gatherRepoHealthFacts");function Rr(e,t){let n=a(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}a(Rr,"samePath");var Aa=2e3,Tt=64,Ar=4e3;function Ta(e){let t=[];try{let r=T.join(e,"pnpm-workspace.yaml");if(N(r)){let i=!1;for(let s of de(r,"utf8").split(`
34
- `)){let o=s.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(o)){i=!0;continue}if(i){let c=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(o);c?t.push(c[1]):o.trim().length>0&&!/^\s/.test(o)&&(i=!1)}}}else{let i=T.join(e,"package.json");if(N(i)){let s=JSON.parse(de(i,"utf8")),o=Array.isArray(s.workspaces)?s.workspaces:s.workspaces?.packages;Array.isArray(o)&&t.push(...o.filter(c=>typeof c=="string"))}}}catch{return[]}let n=[];for(let r of t){if(n.length>=Tt)break;if(!(r.startsWith("!")||r.includes("**")))try{if(r.endsWith("/*")){let i=r.slice(0,-2),s=T.join(e,i);if(!N(s))continue;for(let o of $r(s,{withFileTypes:!0}))if(o.isDirectory()&&!o.name.startsWith(".")&&n.push(T.join(i,o.name)),n.length>=Tt)break}else r.includes("*")||n.push(r)}catch{}}return n.slice(0,Tt)}a(Ta,"listWorkspacePackageDirs");function Tr(e){let t=null,n=0,r=[e];for(;r.length>0&&n<Ar;){let i=r.pop();if(i===void 0)break;let s;try{s=$r(i,{withFileTypes:!0})}catch{continue}for(let o of s){if(o.name.startsWith(".")||o.name==="node_modules")continue;let c=T.join(i,o.name);if(o.isDirectory())r.push(c);else if(o.isFile()){n+=1;try{let l=wa(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=Ar)break}}}return t}a(Tr,"newestMtimeUnder");function $a(e,t){let n=new Set;for(let r of t)try{let i=T.join(e,r,"package.json");if(!N(i))continue;let s=JSON.parse(de(i,"utf8"));for(let o of["dependencies","devDependencies","peerDependencies"]){let c=s[o];if(!(c===null||typeof c!="object"))for(let[l,u]of Object.entries(c))typeof u=="string"&&u.startsWith("workspace:")&&n.add(l)}}catch{}return n}a($a,"consumedWorkspaceNames");function Mr(e){let t=[],n=Ta(e),r=$a(e,n);for(let i of n)try{let s=T.join(e,i,"package.json");if(!N(s))continue;let o=JSON.parse(de(s,"utf8"));if(typeof o.name!="string"||!r.has(o.name))continue;let c=a(y=>{if(typeof y!="string")return null;let w=y.replace(/^\.\//,"").split("/")[0];return w==="build"||w==="dist"?w:null},"builtSeg"),l=c(o.types??o.typings),u=c(o.main),d=l??u;if(d===null)continue;let f=l!==null&&u!==null?"both":l!==null?"types":"runtime",p=T.join(e,i,"src"),h=T.join(e,i,d);if(!N(p)||!N(h))continue;let g=Tr(p),m=Tr(h);if(g===null||m===null)continue;let b=g-m;b>Aa&&t.push({packageDir:i,buildDir:d,srcNewerByMs:Math.round(b),impact:f})}catch{}return t.sort((i,s)=>i.packageDir.localeCompare(s.packageDir))}a(Mr,"gatherStalePackageBuilds");function Ia(e,t){if(!t)return null;let n=Na(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(s=>s.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}a(Ia,"gatherReleaseFact");function Na(e,t){try{return _a("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}a(Na,"runGh");async function It(e,t={}){let n=await Cr(e,t),r=Nr(n);return{ok:Or(r),findings:r,facts:n}}a(It,"checkDivergence");import{existsSync as Nt,readdirSync as Dr}from"node:fs";import{posix as F}from"node:path";var Oa=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Ot=3,Pr=.8;function Lr(e,t={}){let n=t.minFiles??Ot;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Pr)}a(Lr,"isCounterNamespace");function te(e){return`${e.dir}#${e.prefix}`}a(te,"namespaceKey");function fe(e){let t=Oa.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}a(fe,"parseNumbered");function jr(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let s=te(i),o=e.sightingsByNamespace.get(s);if(!o)continue;let c=new Set(o.keys());for(let[l,u]of o){let d=[...new Set(u.map(g=>g.path))];if(d.length<2)continue;let f=d.find(g=>n.has(g)),p=d.filter(g=>g!==f),h=`${i.prefix}${l}`;t.push(f?{id:`number.collision:${s}#${l}`,status:"open",namespace:i,number:l,title:`${h} is already taken`,detail:`This branch adds ${f}, but ${h} already exists as ${p.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${h} stop being unambiguous.`,ownPath:f,sightings:u.filter(g=>g.path!==f),suggestion:`${i.prefix}${Ct(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${s}#${l}`,status:"info",namespace:i,number:l,title:`${h} is used more than once (pre-existing)`,detail:`${h} is carried by ${d.length} files: ${d.join(", ")}.`,sightings:u,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,s)=>r[i.status]-r[s.status]||i.id.localeCompare(s.id))}a(jr,"computeNumberCollisions");function Fr(e){return!e.some(t=>t.status==="open")}a(Fr,"isCollisionFree");function Ct(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}a(Ct,"suggestNextNumber");function Mt(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}a(Mt,"normaliseRepoPath");function Ur(e,t){let n=Mt(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=fe(F.basename(n));if(!i)return r;let s=`${F.dirname(n)}#${i.prefix}`,o=e.namespaces.find(d=>te(d)===s)??null;if(!o)return{...r,number:i.number};let c=e.sightingsByNamespace.get(s)??new Map,l=new Set,u=[];for(let d of c.get(i.number)??[])d.path===n||l.has(d.path)||(l.add(d.path),u.push(d));return{path:n,namespace:o,number:i.number,taken:u.length>0,sightings:u,suggestion:Ct(c.keys(),i.number)}}a(Ur,"checkProposedNumber");function Be(e){let t=e?.trim();return t||null}a(Be,"trimOrNull");function ee(e){return e?e.split(`
35
- `).filter(Boolean):[]}a(ee,"lines");function Ca(e){let t=Be(_(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(_(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}a(Ca,"resolveDefaultBranch");function Kr(e,t={}){let n=t.minFiles??Ot,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=_(e,r);if(i===null)return[];let s=new Map;for(let o of i.split("\0").filter(Boolean)){let c=F.dirname(o),l=fe(F.basename(o));if(!l)continue;let u=`${c}#${l.prefix}`,d=s.get(u);d?d.numbers.push(l.number):s.set(u,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...s.values()].filter(o=>Lr(o.numbers,{...t,minFiles:n})).map(o=>({dir:o.dir,prefix:o.prefix,fileCount:o.numbers.length,distinctRatio:new Set(o.numbers).size/o.numbers.length})).sort((o,c)=>te(o).localeCompare(te(c)))}a(Kr,"detectNamespaces");async function Dt(e,t={}){let n=[];if(Be(_(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=Kr(e,t),s=new Map(i.map(h=>[te(h),h])),o=[...new Set(i.map(h=>h.dir))],c=new Map,l=a((h,g,m)=>{let b=F.dirname(h),y=fe(F.basename(h));if(!y)return;let w=`${b}#${y.prefix}`;if(!s.has(w))return;let x=c.get(w)??new Map,E=x.get(y.number)??[];E.push({kind:g,where:m,path:h}),x.set(y.number,E),c.set(w,x)},"record"),u=a((h,g,m)=>{if(o.length===0)return;let b=_(e,["ls-tree","-r","--name-only",h,"--",...o]);if(b===null){n.push(`could not read ${m}`);return}for(let y of ee(b))l(y,g,m)},"scanTree");for(let h of o){let g=F.join(e,h);if(Nt(g))try{for(let m of Dr(g))l(`${h}/${m}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let d=Ca(e);d?u(`origin/${d}`,"default_branch",`origin/${d}`):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let f=Be(_(e,["rev-parse","--abbrev-ref","HEAD"]));for(let h of ee(_(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))h!==f&&u(h,"branch",`Branch ${h}`);if(t.includeWorktrees!==!1){let h=Be(_(e,["rev-parse","--show-toplevel"]));for(let g of ee(_(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let m=g.slice(9).trim();if(!(!m||m===h||!Nt(m)))for(let b of o){let y=F.join(m,b);if(Nt(y))try{for(let w of Dr(y))l(`${b}/${w}`,"worktree",`Worktree ${m}`)}catch{n.push(`could not read ${b} in ${m}`)}}}}let p=[];if(d&&o.length>0){let h=_(e,["diff","--name-only","--diff-filter=A",`origin/${d}...HEAD`,"--",...o]);h===null?n.push("could not diff against the default branch \u2014 everything reported as info"):p=ee(h);let g=_(e,["ls-files","--others","--exclude-standard","--",...o]);g!==null&&(p=[...p,...ee(g)]);let m=_(e,["diff","--cached","--name-only","--diff-filter=A","--",...o]);m!==null&&(p=[...p,...ee(m)])}return{isRepo:!0,defaultBranch:d,namespaces:i,sightingsByNamespace:c,addedPaths:p,skipped:n}}a(Dt,"gatherNumberCollisionFacts");async function Pt(e,t={}){let n=await Dt(e,t),r=jr(n);return{ok:Fr(r),findings:r,facts:n}}a(Pt,"checkNumberCollisions");async function Lt(e,t,n={}){let r=Mt(t);if(!fe(F.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Dt(e,{...n,dirs:n.dirs??[F.dirname(r)]});return Ur(i,r)}a(Lt,"checkNumberForPath");import{existsSync as Ma,readFileSync as Br}from"node:fs";import{posix as Da}from"node:path";var Vr=".maind/spec-contracts.json";function We(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}a(We,"endOfString");function Ge(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
36
- `,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}a(Ge,"skipComment");function pe(e){return e==='"'||e==="'"||e==="`"}a(pe,"isQuote");function Ve(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}a(Ve,"isCommentStart");function He(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let s=e[i];if(pe(s)){i=We(e,i);continue}if(Ve(e,i)){i=Ge(e,i);continue}if(s==="["||s==="{")r++;else if((s==="]"||s==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}a(He,"sliceBalanced");function Pa(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Ve(e,t)){t=Ge(e,t);continue}break}return e.slice(t)}a(Pa,"stripLeadingTrivia");function ne(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let s=e[i];if(pe(s)){i=We(e,i);continue}if(Ve(e,i)){i=Ge(e,i);continue}s==="["||s==="{"||s==="("?n++:s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(s=>Pa(s).trim()).filter(s=>s.length>0)}a(ne,"splitTopLevel");function qr(e){let t=We(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
37
- `:i==="r"?"\r":i==="t"?" ":i)}a(qr,"readStringLiteral");function La(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(La,"escapeRe");function Ft(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${La(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,s=!1;for(;i<e.length;){let o=e[i];if(pe(o)){i=We(e,i);continue}if(Ve(e,i)){i=Ge(e,i);continue}if(!s){if(o==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))s=!0;else if(o===";")return null;i++;continue}if(o==="[")return He(e,i);if(o===";")return null;i++}return null}a(Ft,"findSymbolArray");function Ut(e){let t={};if(!e.startsWith("{"))return t;for(let n of ne(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],s=r[4].trim();pe(s[0]??"")&&(t[i]=qr(s))}return t}a(Ut,"parseObjectFields");function ja(e,t){if(!e.startsWith("{"))return null;for(let n of ne(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}a(ja,"objectFieldRaw");function zr(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}a(zr,"pickFields");function Yr(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}a(Yr,"makeOrdinals");function Xr(e,t){let n=Ft(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Yr(),i=[],s=0;for(let o of ne(n.slice(1,-1))){if(!o.startsWith("{")){s++;continue}let c=Ut(o),l=c[t.key_field];if(!l){s++;continue}let u=(t.partition_by??[]).map(d=>c[d]??"");i.push({key:l,fields:zr(c,t.fields),orderPath:u,ordinal:r(u)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}a(Xr,"extractObjectArray");function Jr(e,t){let n=Ft(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};if(t.levels.length===0)return{records:[],error:`contract declares no levels for \`${t.symbol}\``,dropped:0};let r=Yr(),i=[],s=0,o=a((c,l,u)=>{let d=t.levels[l],f=l===t.levels.length-1;for(let p of ne(c.slice(1,-1))){let h={...u},g=null;if(d.shape==="object"){if(!p.startsWith("{")){s++;continue}let m=Ut(p);for(let[b,y]of Object.entries(d.fields??{}))h[b]=m[String(y)]??"";if(!f&&typeof d.children=="string"){let b=ja(p,d.children);g=b&&b.startsWith("[")?He(b,0):null}}else{if(!p.startsWith("[")){s++;continue}let m=ne(p.slice(1,-1));for(let[b,y]of Object.entries(d.fields??{})){let w=m[Number(y)];h[b]=w!==void 0&&pe(w[0]??"")?qr(w):""}if(!f&&typeof d.children=="number"){let b=m[d.children];g=b!==void 0&&b.startsWith("[")?He(b,0):null}}if(f){let m=h[t.key_field];if(!m){s++;continue}let b=(t.partition_by??[]).map(y=>h[y]??"");i.push({key:m,fields:zr(h,t.fields),orderPath:b,ordinal:r(b)});continue}g!==null&&o(g,l+1,h)}},"walk");return o(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}a(Jr,"extractNestedList");function Hr(e,t){return t.extractor==="object-array"?Xr(e,t):Jr(e,t)}a(Hr,"extractRecords");function Qr(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}a(Qr,"isGrounded");function Zr(e,t,n){return`spec.drift:${e}#${t}:${n}`}a(Zr,"findingId");function Fa(e){return e.orderPath.join(" / ")||"(flat)"}a(Fa,"partitionOf");function ei(e,t,n,r){let i=[],s=a((u,d,f,p,h,g)=>{i.push({id:Zr(e.id,u,f),contract:e.id,dimension:u,status:d,key:f,title:p,detail:h,hint:g})},"push"),o=new Map(n.map(u=>[u.key,u])),c=new Map(t.map(u=>[u.key,u]));for(let u of t){let d=o.get(u.key);if(!d){s("coverage","open",u.key,`${u.key} is declared by the specification but missing from the implementation`,`Partition ${Fa(u)}, position ${u.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let f of e.compare_fields??[]){let p=u.fields[f]??"",h=d.fields[f]??"";p!==h&&s("fields","open",`${u.key}.${f}`,`${u.key}: ${f} is "${h||"\u2014"}", the specification says "${p||"\u2014"}"`,`Field \`${f}\` disagrees between the two sides.`)}}let l=new Map;for(let u of t){let d=u.orderPath.join("\0"),f=l.get(d);f?f.push(u):l.set(d,[u])}for(let[u,d]of l){let f=d.filter(m=>o.has(m.key)).map(m=>m.key),p=n.filter(m=>m.orderPath.join("\0")===u).filter(m=>c.has(m.key)).map(m=>m.key),h=new Set(p),g=f.filter(m=>h.has(m));if(p.join("|")!==g.join("|")){let m=u.split("\0").join(" / ")||"(flat)";s("order","open",m,`Partition ${m}: sequence differs from the specification`,`implementation: ${p.join(" \u2192 ")}
38
- specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let u of n)c.has(u.key)||s("extra","warn",u.key,`${u.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let u of new Set([...o.keys(),...c.keys()])){if(Qr(u,e.grounding,r))continue;let d=o.has(u);s("unrealized",d?"open":"warn",u,d?`${u} is referenced by the implementation but has no artefact`:`${u} is declared by the specification but not built yet`,d?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}a(ei,"compareContract");function Ua(e,t,n){let r=[];for(let i of e.assertions??[]){let s=n.get(i.path);if(!s)continue;let o=s.indexOf(i.prefix);if(o===-1)continue;let c=/^\s*(\d+)/.exec(s.slice(o+i.prefix.length));if(!c)continue;let l=Number(c[1]),u=t[i.counts];l!==u&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${u}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}a(Ua,"checkAssertions");function Wr(e,t){return{id:`contract.unreadable:${e}`,contract:e,dimension:"contract",status:"open",key:null,title:`Contract "${e}" could not be evaluated`,detail:t,hint:"This is NOT a drift finding. An anchor moved, or a declared file is gone \u2014 repair the contract in the manifest, then re-run. Nothing has been compared for this contract."}}a(Wr,"unreadable");var Gr={open:0,warn:1,info:2,passed:3};function ti(e,t={}){let n=a(d=>({ok:!1,verdict:"no_opinion",reason:d,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(d=>t.contracts.includes(d.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(d=>`"${d}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=a(d=>{let f=[],p=[];for(let h of r){let g=d.get(h.spec.path),m=d.get(h.impl.path);if(g==null||m==null){let x=g==null?h.spec.path:h.impl.path;f.push(Wr(h.id,`Declared file could not be read: ${x}`)),p.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let b=Hr(g,h.spec),y=Hr(m,h.impl);if(b.error||y.error){f.push(Wr(h.id,b.error??y.error??"unknown")),p.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let w=b.dropped>0||y.dropped>0;p.push({id:h.id,measured:!0,specRecords:b.records.length,implRecords:y.records.length,partial:w}),w&&f.push({id:`contract.partial:${h.id}`,contract:h.id,dimension:"contract",status:"warn",key:null,title:`Contract "${h.id}" was measured incompletely`,detail:`${b.dropped} specification and ${y.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),f.push(...ei(h,b.records,y.records,e.files)),f.push(...Ua(h,{spec:b.records.length,impl:y.records.length},d))}return{findings:f,contracts:p}},"runOnce"),s=i(e.sources),o=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let d of i(e.baselineSources).findings)d.id.startsWith("contract.unreadable:")||o.add(d.id);let c=new Map;for(let d of r)for(let f of d.exceptions??[])c.set(Zr(d.id,f.dimension,f.key),f);let l=s.findings.map(d=>{let f=c.get(d.id);return f?{...d,status:"info",exceptionReason:f.reason}:o.has(d.id)?{...d,status:"info",detail:`${d.detail}
39
- Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:d});l.sort((d,f)=>Gr[d.status]-Gr[f.status]||d.id.localeCompare(f.id));let u=l.some(d=>d.status==="open");return{ok:!u,verdict:u?"drifted":"aligned",reason:null,findings:l,contracts:s.contracts}}a(ti,"computeSpecDrift");function jt(e){let t=e?.trim();return t||null}a(jt,"trimOrNull");function ni(e){let t;try{t=JSON.parse(e)}catch(o){return{manifest:null,error:`manifest is not valid JSON: ${o.message}`}}let n=a(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null,"obj"),r=a(o=>typeof o=="string"?o:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let s=a(o=>({manifest:null,error:o}),"bad");for(let[o,c]of i.contracts.entries()){let l=n(c),u=r(l?.id),d=u?`contract "${u}"`:`contract #${o+1}`;if(!l)return s(`${d}: not an object`);if(!u)return s(`${d}: \`id\` is missing`);if(!r(l.reason))return s(`${d}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let f of["spec","impl"]){let p=n(l[f]);if(!p)return s(`${d}: \`${f}\` is missing`);let h=r(p.extractor);if(!h)return s(`${d}: \`${f}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return s(`${d}: unknown \`${f}.extractor\` "${h}"`);if(!r(p.path)||!r(p.symbol)||!r(p.key_field))return s(`${d}: \`${f}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(p.levels))return s(`${d}: \`${f}\` is a nested-literal-list and needs \`levels\``)}for(let f of Array.isArray(l.exceptions)?l.exceptions:[]){let p=n(f);if(!p||!r(p.reason))return s(`${d}: exception for "${r(p?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}a(ni,"parseManifest");function Ka(e){let t=jt(_(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(_(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}a(Ka,"resolveDefaultBranch");function Ba(e){let t=new Set;for(let n of e.contracts){t.add(n.spec.path),t.add(n.impl.path);for(let r of n.assertions??[])t.add(r.path)}return[...t]}a(Ba,"declaredPaths");async function ri(e,t={}){let n=a((g,m)=>Da.join(g,m),"join"),r=t.manifestPath??Vr,i=[],s={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(jt(_(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...s,manifestError:"not a git work tree"};let o=n(e,r);if(!Ma(o))return{...s,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=ni(Br(o,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...s,isRepo:!0,manifestError:l};let u=new Map;for(let g of Ba(c))try{u.set(g,Br(n(e,g),"utf8"))}catch{u.set(g,null),i.push(`declared file unreadable in the working tree: ${g}`)}let d=new Set,f=_(e,["ls-files","-z"]);if(f===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let g of f.split("\0"))g&&d.add(g);let p=null,h=new Map;if(t.includeBaseline!==!1){let g=Ka(e);if(!g)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(p=jt(_(e,["merge-base",`origin/${g}`,"HEAD"])),!p)i.push(`no merge-base with origin/${g} \u2014 every finding reported as new`);else for(let m of u.keys())h.set(m,_(e,["show",`${p}:${m}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:u,baselineSources:h,baseRef:p,files:d,skipped:i}}a(ri,"gatherSpecDriftFacts");async function Kt(e,t={}){let n=await ri(e,t);return{...ti(n,t),facts:n}}a(Kt,"checkSpecDrift");var ii=[{flag:"sql_migration_added",path:/(^|\/)migrations\/[^/]+\.sql$/i,onlyWhenAdded:!0},{flag:"security_definer_touched",path:/\.sql$/i,content:/\bSECURITY\s+DEFINER\b/i},{flag:"rls_policy_changed",path:/\.sql$/i,content:/\b(CREATE|ALTER|DROP)\s+POLICY\b|\bROW\s+LEVEL\s+SECURITY\b/i},{flag:"auth_config_changed",path:/(^|\/)supabase\/config\.toml$|(^|\/)(middleware|proxy)\.(ts|js)$/},{flag:"package_manifest_changed",path:/(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|requirements\.txt|pyproject\.toml|Cargo\.toml|go\.mod)$/},{flag:"ci_workflow_changed",path:/^\.github\/workflows\/[^/]+\.ya?ml$|^\.gitlab-ci\.yml$/},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}];function si(e){let t=new Set;for(let[n,r]of e.paths)for(let i of ii){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=Ha(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}a(si,"scanRiskFlags");function Ha(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
40
- `):t.readUntracked(e)}a(Ha,"contentForPath");var re="1";var oi=`
18
+ `),0}a(Pr,"runGitContext");function Pa(e){return e==="success"?"\u{1F7E2}":e==="failure"?"\u{1F534}":e==="pending"?"\u{1F7E1}":"\u26AA"}a(Pa,"ciIcon");function ja(e,t,n,r,i){let s=[];if(s.push("<!-- Generated by `maind git-context` \u2014 local git state for the agent. -->"),s.push(`<!-- generated_at: ${Lr()} -->`),s.push(""),s.push("# maind git-context"),s.push(""),!e.isRepo)return s.push("_Not inside a git work tree \u2014 no git context to report._"),s.push(""),s.join(`
19
+ `);let o=e.defaultBranch!=null?`${e.ahead??"?"} ahead, ${e.behind??"?"} behind \`${e.defaultBranch}\``:"no upstream default branch resolved";if(s.push(`**Branch:** \`${e.branch??"?"}\` \u2014 ${o}`),s.push(`**Working tree:** ${e.uncommitted} uncommitted change${e.uncommitted===1?"":"s"}`),e.projectKey&&s.push(`**Project:** \`${e.projectKey.slice(0,12)}\u2026\` (sha256 of remote \u2014 URL never sent)`),s.push(""),t.available)if(t.prs.length===0)s.push("**Open PRs:** none");else{s.push("**Open PRs:**");for(let c of t.prs){let l=c.isCurrentBranch?` ${Pa(c.ci)} CI:${c.ci} \xB7 this branch`:"";s.push(`- #${c.number} ${c.title}${l}`)}}else s.push("**Open PRs:** _unavailable (`gh` not installed / not authenticated)_");if(s.push(""),n?.checked)if(n.conflicts.length>0){s.push(`**\u26A0 Parallel sessions on this repo:** ${n.peersActive} active \u2014 path conflicts:`);for(let c of n.conflicts)s.push(`- \`${c.path}\`${c.focus?` \u2014 peer focus: ${c.focus}`:""}`);n.recommendation&&s.push(`- _${n.recommendation}_`)}else n.peersActive>0?s.push(`**Parallel sessions on this repo:** ${n.peersActive} active \u2014 no conflict on your changed paths.`):s.push("**Parallel sessions on this repo:** none.");else s.push("**Parallel sessions:** _not checked (no key / no changed paths / offline)._");if(s.push(""),i&&r.length>0){s.push("## Relevant git lessons (maind)");for(let c of r)s.push(`- **${c.title??c.id}**${c.id?` \`${c.id}\``:""}`);s.push("")}return s.push('_Full PR workflow: `activate_skill({id:"skill_pr_lifecycle"})`._'),s.push(""),s.join(`
20
+ `)}a(ja,"renderMarkdown");function Fa(e,t,n){return{schema:"maind.git-context/v1",generated_at:Lr(),project_key:e.projectKey,branch:e.branch,default_branch:e.defaultBranch,ahead:e.ahead,behind:e.behind,uncommitted:e.uncommitted,open_prs:t.map(r=>({number:r.number,ci:r.ci,current_branch:r.isCurrentBranch})),peers_active:n?.checked?n.peersActive:null,path_conflicts:n?.conflicts.map(r=>r.path)??[]}}a(Fa,"buildManifest");function Mt(e){return e instanceof Error?e.message:String(e)}a(Mt,"msg");function Lt(e){process.stderr.write(`maind git-context: ${e}
21
+ `)}a(Lt,"warn");import{execFileSync as Wl,spawnSync as Gl}from"node:child_process";import{existsSync as Vl,mkdtempSync as ql,rmSync as zl,writeFileSync as Yl}from"node:fs";import{tmpdir as Xl}from"node:os";import{dirname as Jl,join as js}from"node:path";import{fileURLToPath as Ql}from"node:url";import{mkdirSync as Ul}from"node:fs";import{posix as Kn}from"node:path";import{join as Ja}from"node:path";import Ft from"web-tree-sitter";function He(e){return`${e}#<module>`}a(He,"moduleKey");function We(e,t,n){return`${e}#${t}:${n}`}a(We,"symbolKey");function Ge(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}a(Ge,"languageForPath");function Pt(e){return e.toLowerCase().endsWith(".d.ts")}a(Pt,"isSkippablePath");function Ve(){return{nodes:[],edges:[],refs:[],imports:[]}}a(Ve,"newResult");function q(e){return e+1}a(q,"line1");function qe(e){return(e.text.split(`
22
+ `,1)[0]??"").trim().slice(0,200)}a(qe,"signatureOf");function Ua(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}}a(Ua,"calleeName");function Ka(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=Ua(r.childForFieldName("function"));i&&n.add(i)}return[...n]}a(Ka,"collectCallTargets");function te(e,t,n,r){for(let i of Ka(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}a(te,"addCallRefs");var jr="call";function Fr(e,t){let n=Ve();for(let r of e.namedChildren)Ba(r,t,n);return n}a(Fr,"extractPython");function Ur(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}a(Ur,"unwrapDecorated");function Ba(e,t,n){let r=Ur(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??Wa(r);s&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let s=ze(r,t,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let o=r.childForFieldName("body");o&&te(n,s.nodeKey,o,jr);return}case"class_definition":Ha(r,t,n);return;case"expression_statement":{let s=r.namedChildren.find(o=>o.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let o=ze(r,t,s.text,s.text,"variable");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}return}default:return}}a(Ba,"handleTopLevel");function Ha(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=ze(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=e.childForFieldName("superclasses");if(s){for(let c of s.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let o=e.childForFieldName("body");if(o)for(let c of o.namedChildren){let l=Ur(c);if(l.type!=="function_definition")continue;let u=l.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,f=ze(l,t,u,d,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let p=l.childForFieldName("body");p&&te(n,f.nodeKey,p,jr)}}a(Ha,"addClass");function ze(e,t,n,r,i){return{nodeKey:We(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:q(e.startPosition.row),endLine:q(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:qe(e),doc:null}}a(ze,"makeNode");function Wa(e){return e.descendantsOfType("dotted_name")[0]?.text??null}a(Wa,"firstDottedName");var Br="call_expression";function Hr(e,t){let n=Ve();for(let r of e.namedChildren)Va(r,t,n);return n}a(Hr,"extractTypescript");function Ga(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}a(Ga,"unwrapExport");function Va(e,t,n){let r=Ga(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:za(i)});return}case"function_declaration":case"generator_function_declaration":{Kr(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{qa(r,t,n);return}case"interface_declaration":jt(r,t,n,"interface");return;case"type_alias_declaration":jt(r,t,n,"type_alias");return;case"enum_declaration":jt(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let i of r.namedChildren){if(i.type!=="variable_declarator")continue;let s=i.childForFieldName("name");if(!s||s.type!=="identifier")continue;let o=i.childForFieldName("value"),c=o?.type==="arrow_function"||o?.type==="function_expression"||o?.type==="function";Kr(i,t,n,c?"function":"variable",s,o)}return}default:return}}a(Va,"handleTopLevel");function Kr(e,t,n,r,i,s){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=Ye(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let u=s??e.childForFieldName("body")??e;r==="function"&&u&&te(n,l.nodeKey,u,Br)}a(Kr,"addFunctionLike");function jt(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=Ye(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}a(jt,"addSimpleNamed");function qa(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Ye(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let o of e.descendantsOfType("class_heritage"))for(let c of o.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let u of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text});for(let u of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text})}let s=e.childForFieldName("body");if(s)for(let o of s.namedChildren){if(o.type!=="method_definition")continue;let c=o.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,u=Ye(o,t,c,l,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let d=o.childForFieldName("body");d&&te(n,u.nodeKey,d,Br)}}a(qa,"addClass");function Ye(e,t,n,r,i){return{nodeKey:We(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:q(e.startPosition.row),endLine:q(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:qe(e),doc:null}}a(Ye,"makeNode");function za(e){return e.replace(/^["'`]|["'`]$/g,"")}a(za,"stripQuotes");import{createRequire as Ya}from"node:module";import{join as Xa}from"node:path";var Wr={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Gr="tree-sitter.wasm";function Vr(e,t){return t?Xa(t,Wr[e]):Ya(import.meta.url).resolve(`tree-sitter-wasms/out/${Wr[e]}`)}a(Vr,"grammarPath");var Qa=["typescript","tsx","javascript","python"],Xe=class{static{a(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await Ft.init(this.assetDir?{locateFile:a(t=>Ja(this.assetDir,t||Gr),"locateFile")}:void 0),this.parser=new Ft,this.initialized=!0)}supports(t){return Qa.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let s=i.parse(n);if(!s)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[]};let o=s.rootNode,c=He(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:q(o.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?Fr(o,u):Hr(o,u);return s.delete(),{filePath:t,language:r,nodes:[l,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await Ft.Language.load(Vr(t,this.assetDir)),this.grammars.set(t,n)),n}};import{readFileSync as Es}from"node:fs";import{posix as xs}from"node:path";var qr="1";function zr(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
23
+ `).slice(0,1e3)}a(zr,"nodeEmbedText");var Ut=["function","method","class","interface","enum","type_alias"];function Yr(e,t){let n=Math.min(e.length,t.length),r=0,i=0,s=0;for(let o=0;o<n;o++){let c=e[o],l=t[o];r+=c*l,i+=c*c,s+=l*l}return i===0||s===0?0:r/(Math.sqrt(i)*Math.sqrt(s))}a(Yr,"cosineSimilarity");import{posix as Kt}from"node:path";var Za=new Set(["function","method","class","interface","enum","type_alias"]),Je=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];function Xr(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!Za.has(r.kind))continue;let i=t.get(r.name);i?i.push(r.nodeKey):t.set(r.name,[r.nodeKey])}return{nameToKeys:t,files:n}}a(Xr,"buildResolutionIndex");function Jr(e,t){let n=new Set,r=[],i=new Set,s=a((o,c,l)=>{if(o===c)return;let u=`${o}\0${c}\0${l}`;n.has(u)||(n.add(u),r.push({srcKey:o,dstKey:c,kind:l}),i.add(o))},"push");for(let o of e.edges)s(o.srcKey,o.dstKey,o.kind);for(let o of e.nodes)i.add(o.nodeKey);for(let o of e.refs){let c=t.nameToKeys.get(o.targetName);!c||c.length!==1||s(o.fromKey,c[0],o.kind)}for(let o of e.imports){let c=ec(e.filePath,o.specifier,t.files);c&&s(o.fromModuleKey,He(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}a(Jr,"resolveFileEdges");function ec(e,t,n){if(!t.startsWith("."))return null;let r=Kt.normalize(Kt.join(Kt.dirname(e),t)),i=[],s=Je.some(c=>r.endsWith(c));s&&i.push(r);let o=/\.(js|jsx|mjs|cjs)$/.exec(r);if(o){let c=r.slice(0,-o[0].length);for(let l of Je)i.push(c+l)}if(!s){for(let c of Je)i.push(r+c);for(let c of Je)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}a(ec,"resolveImportTarget");import{execFileSync as tc}from"node:child_process";import{createHash as nc}from"node:crypto";import{readdirSync as rc,statSync as ic}from"node:fs";import{posix as ti,sep as Qr}from"node:path";var Zr=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),sc=["-c","diff.renames=true","-c","core.quotePath=false"];function _(e,t){try{return tc("git",[...sc,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}a(_,"runGit");var ne=_;function oc(e){return Qr==="/"?e:e.split(Qr).join("/")}a(oc,"toPosix");function Qe(e){let t=[];for(let n of e){let r=oc(n).trim();if(!r||Pt(r))continue;let i=Ge(r);i&&t.push({path:r,language:i})}return t}a(Qe,"classify");function ni(e){return Qe(e)}a(ni,"classifyPaths");function ri(e){let t=ne(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Qe(t.split(`
24
+ `));let n=[];return ii(e,"",n),Qe(n)}a(ri,"discoverSourceFiles");function ii(e,t,n){let r;try{r=rc(ti.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&Zr.has(i.name)||Zr.has(i.name))continue;let s=t?`${t}/${i.name}`:i.name;i.isDirectory()?ii(e,s,n):i.isFile()&&n.push(s)}}a(ii,"walk");function Bt(e,t){let r=_(e,["merge-base",t,"HEAD"])?.trim();return r&&r.length>0?r:t}a(Bt,"resolveDiffBase");function Ze(e,t={}){if(ge(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Bt(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=ne(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let o=new Map;for(let c of s.split(`
25
+ `)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let u=l[0][0],d=ei((l.length>=3?l[l.length-1]:l[1]).trim());d&&(u==="A"||u==="C"?o.set(d,"added"):u==="R"?o.set(d,"renamed"):o.set(d,"modified"))}if(n){let c=ne(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
26
+ `)){if(l.length<4)continue;let u=l[0],d=l[1];if(u==="D"||d==="D")continue;let f=l.slice(3),p=f.indexOf(" -> ");p>=0&&(f=f.slice(p+4)),f=ei(f),!(!f||o.has(f))&&(u==="?"||u==="A"||d==="A"?o.set(f,"added"):u==="R"?o.set(f,"renamed"):o.set(f,"modified"))}}return o}a(Ze,"enumerateChangedPaths");function ei(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}a(ei,"unquote");function si(e,t={}){let n=Ze(e,t);return n===null?null:Qe(n.keys())}a(si,"changedSourceFiles");function oi(e,t){try{let n=ic(ti.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}a(oi,"statFile");function et(e){return nc("sha256").update(e).digest("hex")}a(et,"hashContent");function ge(e){return ne(e,["rev-parse","HEAD"])?.trim()??null}a(ge,"headCommit");function tt(e,t){return ne(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}a(tt,"resolveCommitSha");function ai(e){let t=ne(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}a(ai,"isWorktreeDirty");var ac=16*1024*1024,cc=500,lc=4e3,ci=256*1024,uc=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;function li(e,t={}){if(_(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Bt(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=_(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let o=new Map,c="full";if(Buffer.byteLength(s,"utf8")>ac?c="none":dc(s,o,()=>{c="partial"}),n){let l=_(e,["status","--porcelain","-uall"])??"";for(let u of l.split(`
27
+ `)){if(u.length<4||u[0]!=="?")continue;let d=u.slice(3);d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),!(!d||o.has(d))&&o.set(d,{path:d,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:o,coverage:c}}a(li,"changedHunks");function dc(e,t,n){let r=null,i=0,s=!1,o=!1,c=a(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
28
+ `)){if(l.startsWith("diff --git ")){c(),s=!1,o=!1;continue}if(l.startsWith("new file mode")){o=!0;continue}if(l.startsWith("rename to ")){s=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let d=l.slice(4).trim();if(d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),d.startsWith("b/")&&(d=d.slice(2)),d==="/dev/null")continue;r={path:d,status:o?"added":s?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let u=uc.exec(l);if(u){if(i++,i>cc){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let d=Number(u[1]),f=u[2]===void 0?1:Number(u[2]);f>0?r.addedRanges.push({start:d,end:d+f-1}):r.deletionPoints.push(d);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<lc&&r.addedLines.push(l.slice(1))}c()}a(dc,"parseUnifiedDiff");var fc="",pc="\0",pi=200,Ht=50,nt=100,ui="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",mi=10;function Wt(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,s=0;for(let o of e.history){let c=o.ownership?.commitsInWindow??o.lastCommits.length;c>=mi&&r++,c>i&&(i=c);for(let u of o.ownership?.topAuthors??[])n.add(u.email.toLowerCase()||u.name);let l=o.lastCommits[0]?.dateIso;if(l){let u=Date.parse(l);Number.isFinite(u)&&u>s&&(s=u)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:s>0?Math.max(0,Math.floor((t-s)/864e5)):0}}a(Wt,"aggregateHistoryContext");function mc(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}a(mc,"clamp");function di(e){return e.split(fc).filter(t=>t.trim().length>0)}a(di,"splitRecords");function fi(e){let[t,n,r,i,s]=e.replace(/\n+$/,"").split(pc);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:s??""}}a(fi,"parseHistoryRecord");function hc(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,i=t.get(r);i?i.commits+=1:t.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...t.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}a(hc,"aggregateOwnership");function hi(e,t,n={}){let r=mc(n.limit,20,100),i=n.includeOwnership!==!1,s=Math.max(r,pi),o=t.map(d=>d.trim()).filter(d=>d.length>0&&!d.startsWith(":")),c=o.slice(0,Ht),l=[];for(let d of c){let f=_(e,["log","-n",String(s),ui,"--",d]),p=f===null?[]:di(f).map(fi).filter(m=>m!==null);l.push({path:d,lastCommits:p.slice(0,r),ownership:i?{topAuthors:hc(p),commitsInWindow:p.length}:null})}let u=null;if(n.since){let d=tt(e,n.since),f=d!==null?[`${d}..HEAD`]:[`--since=${n.since}`],p=_(e,["log",...f,"-n",String(nt+1),ui,"--name-only","--",...c]),m=[];if(p!==null)for(let h of di(p)){let y=h.split(`
29
+ `),b=fi(y[0]??"");if(!b)continue;let g=y.slice(1).filter(w=>w.trim().length>0).length;m.push({sha:b.sha,dateIso:b.dateIso,authorName:b.authorName,subject:b.subject,filesTouched:g})}u={sinceInput:n.since,sinceResolved:d,commits:m.slice(0,nt),truncated:m.length>nt}}return{history:l,regression:u,ownershipWindowCommits:s,pathsTruncated:o.length>Ht}}a(hi,"readFileHistory");import{execFileSync as Tc}from"node:child_process";import{execFileSync as gc}from"node:child_process";import{readdirSync as yc,statSync as gi}from"node:fs";import{isAbsolute as bc,join as Gt,relative as _c,resolve as wc}from"node:path";var kc=[".githooks",".husky"];function Ec(e){return!e.endsWith(".sample")&&!e.startsWith(".")}a(Ec,"isRealHook");function xc(e,t){try{let n=gc("git",["-C",e,"config","--get",t],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n.length>0?n:null}catch{return null}}a(xc,"gitConfig");function vc(e){let t;try{t=yc(e)}catch{return null}for(let n of t.filter(Ec))try{let r=gi(Gt(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}a(vc,"hasExecutableHook");function Sc(e){try{return gi(e).isDirectory()}catch{return!1}}a(Sc,"isDir");function Rc(e,t){let n=_c(e,t);return!n||n.startsWith("..")?t:n}a(Rc,"displayPath");function Vt(e){let t=kc.filter(c=>Sc(Gt(e,c))),n=xc(e,"core.hooksPath"),r=n?bc(n)?n:wc(e,n):Gt(e,".git","hooks"),i=Rc(e,r),s=vc(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let o=n?s===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:o,hookDirs:t,hooksPath:n,effectiveDir:i}}a(Vt,"resolveHookState");function qt(e){switch(e.reason){case"wired":return`Git-Gates aktiv (core.hooksPath \u2192 ${e.effectiveDir}).`;case"default_path":return"Git-Gates aktiv (.git/hooks, nicht versioniert).";case"path_unset":return`${e.hookDirs.join(", ")} liegt im Repo, aber core.hooksPath ist ungesetzt \u2014 kein Gate feuert.`;case"path_missing":return`core.hooksPath zeigt auf ${e.effectiveDir}, das es nicht gibt \u2014 git f\xFChrt keinen Hook aus.`;case"path_empty":return`core.hooksPath zeigt auf ${e.effectiveDir}, dort liegt kein ausf\xFChrbarer Hook.`;case"no_hooks":return"Keine Git-Hooks im Repo."}}a(qt,"describeHookState");import{existsSync as N,readFileSync as z,readdirSync as rt,statSync as Yt}from"node:fs";import{posix as E}from"node:path";import{posix as yi}from"node:path";var Ac=/^(\d+)_.+\.sql$/;function ye(e){let t=Ac.exec(e);return t?t[1]:null}a(ye,"parseMigrationVersion");function be(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}a(be,"compareVersions");function re(e,t){let n=_(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=a(s=>!t||t.length===0?!0:t.some(o=>{let c=o.replace(/\/+$/,"");return c===""||s===c||s.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let s of n.split("\0").filter(Boolean)){if(!r(s))continue;let o=yi.basename(s),c=ye(o);if(c===null)continue;let l=yi.dirname(s),u=i.get(l)??[];u.push({path:s,name:o,version:c}),i.set(l,u)}return[...i.entries()].map(([s,o])=>({dir:s,files:o.sort((c,l)=>be(c.version,l.version))})).sort((s,o)=>s.dir.localeCompare(o.dir))}a(re,"discoverSupabaseProjects");function bi(e){let t=_(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(_(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}a(bi,"resolveDefaultBranch");var xi=["supabase/config.toml","supabase/.temp",".env"],Qt=".maind/worktree-requirements",vi={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},$c=Object.keys(vi).flatMap(e=>[e,"*/"+e]),Ic=["scripts"],Nc=512*1024;function Cc(e,t){let n=(()=>{let i=_(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=E.dirname(e);for(let i=0;i<8&&r&&r!==E.dirname(r);i++){if(N(E.join(r,".git"))){let s=(()=>{let c=_(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&s!=null&&Jt(n,s))){let c=Oc(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=E.dirname(r)}return null}a(Cc,"gatherToolCopyDrift");function Oc(e,t){let n=[];for(let r of Ic){let i;try{i=rt(E.join(e,r),{withFileTypes:!0}).filter(s=>s.isFile()).map(s=>s.name)}catch{continue}for(let s of i){let o=`${r}/${s}`,c=E.join(e,o),l=E.join(t,o);try{let u=Yt(c),d=Yt(l);if(!d.isFile())continue;if(u.size!==d.size){n.push(o);continue}if(u.size>Nc)continue;z(c).equals(z(l))||n.push(o)}catch{continue}}}return n.sort()}a(Oc,"compareToolDirs");function Si(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let o=e.upstream.split("/").slice(1).join("/");o&&o!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;if(r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`}),e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let o=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${o} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let o=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${o.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${Qt}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let o=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${o.map(c=>c.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:o.map(c=>`${c.install} (in ${E.dirname(c.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:o,diverging:c}=e.toolCopyDrift,l=c.slice(0,3).join(", "),u=c.length>3?` (+${c.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${o} ships ${l}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${c[0]}\` from this repo root), not via a path into ${o}.`})}if(e.stalePackageBuilds.length>0){let o=e.stalePackageBuilds,c=a(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),l=o.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:o.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${o.map(c).join(", ")}: src/ is newer than the built ${[...new Set(o.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${l}`,hint:`Rebuild: pnpm --filter ./${o[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let s=Dc(e.hooks);return s&&t.push(s),Mc(t)}a(Si,"computeDivergence");function Dc(e){return!e||e.verdict!=="present_unwired"?null:{id:"setup.hooks-unwired",status:"warn",scope:"setup",title:"Git-Hooks liegen im Repo, feuern aber nicht",detail:qt(e),hint:e.reason==="path_missing"?`core.hooksPath zeigt ins Leere. Korrigieren: git config core.hooksPath ${e.hookDirs[0]??".githooks"}`:`git config core.hooksPath ${e.hookDirs[0]??".githooks"} \u2014 git klont das Verzeichnis mit, den Pfad nie.`}}a(Dc,"computeHookFinding");var _i={open:0,warn:1,info:2,passed:3};function Mc(e){return[...e].sort((t,n)=>_i[t.status]-_i[n.status]||t.id.localeCompare(n.id))}a(Mc,"sortFindings");function Ri(e){return!e.some(t=>t.status==="open"||t.status==="warn")}a(Ri,"isHealthy");function W(e){let t=e?.trim();return t||null}a(W,"trimOrNull");function Lc(e){let t=W(_(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(_(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}a(Lc,"resolveDefaultBranch");function Pc(e){let t=W(_(e,["rev-parse","--git-dir"]));if(!t)return null;let n=E.isAbsolute(t)?t:E.join(e,t);return N(E.join(n,"rebase-merge"))||N(E.join(n,"rebase-apply"))?"rebase":N(E.join(n,"MERGE_HEAD"))?"merge":N(E.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}a(Pc,"detectInProgressOp");function jc(e){let t=[],n=null,r=a(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
30
+ `))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}a(jc,"parseWorktrees");function Fc(e){let t=E.join(e,Qt);if(!N(t))return[];try{return z(t,"utf8").split(`
31
+ `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}a(Fc,"readWorktreeRequirements");function Uc(e){try{return re(e).map(t=>E.join(E.dirname(t.dir),"config.toml"))}catch{return[]}}a(Uc,"discoverSupabaseConfigProbes");function Kc(e){let t=_(e,["ls-files","-z","--",...$c]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=vi[E.basename(r)];if(i===void 0)continue;let s=E.dirname(r);if(!Bc(e,s))continue;let o=s==="."?"node_modules":E.join(s,"node_modules");n.has(o)||n.set(o,{dir:o,install:i})}return[...n.values()]}a(Kc,"discoverDependencyDirs");function Bc(e,t){return t==="."?!0:Xt(e,t)}a(Bc,"isWorkspaceRoot");function Xt(e,t){if(N(E.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(z(E.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}a(Xt,"hasWorkspaceMarkers");async function Ai(e,t={}){if(W(_(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,branch:null,defaultBranch:null,upstream:null,headMatchesUpstream:null,remoteTrackingExists:null,ahead:null,behind:null,uncommitted:0,detachedHead:!1,inProgressOp:null,isSharedMainTree:!1,otherWorktrees:0,worktreeParity:null,toolCopyDrift:null,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=W(_(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",s=i?null:r,o=Lc(e),c=W(_(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,u=null;if(c){let R=W(_(e,["rev-parse","HEAD"])),$=W(_(e,["rev-parse","@{u}"]));l=R!=null&&$!=null?R===$:null,u=_(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let d=null,f=null;if(o){let R=W(_(e,["rev-list","--left-right","--count",`origin/${o}...HEAD`]));if(R){let[$,v]=R.split(/\s+/).map(V=>Number.parseInt(V,10));Number.isFinite($)&&(f=$),Number.isFinite(v)&&(d=v)}}let m=(_(e,["status","--porcelain"])??"").split(`
32
+ `).filter(R=>R.trim().length>0).length,h=Pc(e),y=W(_(e,["rev-parse","--show-toplevel"]))??e,b=jc(_(e,["worktree","list","--porcelain"])??""),g=b[0]?.path??null,w=g!=null&&Jt(g,y),S=Math.max(0,b.length-1),A=null;if(g&&!Jt(g,y)){let R=a(v=>N(E.join(g,v))&&!N(E.join(y,v)),"here"),$=[...xi,...Uc(y),...Fc(y),...t.probePaths??[]];A={mainWorktreePath:g,currentWorktreePath:y,missing:[...new Set($.filter(R))],missingDeps:Kc(y).filter(v=>R(v.dir))}}let O=Cc(y,e),x=t.includeRelease===!1?null:Yc(e,s),C=[];return o&&(C=(_(e,["diff","--name-only","--diff-filter=A",`origin/${o}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
33
+ `).map($=>$.trim()).filter($=>$.length>0)),{isRepo:!0,branch:s,defaultBranch:o,upstream:c,headMatchesUpstream:l,remoteTrackingExists:u,ahead:d,behind:f,uncommitted:m,detachedHead:i,inProgressOp:h,isSharedMainTree:w,otherWorktrees:S,worktreeParity:A,toolCopyDrift:O,stalePackageBuilds:Ti(y),release:x,unmergedMigrations:C,hooks:Vt(e)}}a(Ai,"gatherRepoHealthFacts");function Jt(e,t){let n=a(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}a(Jt,"samePath");var Hc=2e3,zt=64,wi=4e3,Wc=3,ki=400;function Gc(e){let t=new Set;Xt(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<ki;){let i=n.pop();if(i===void 0)break;if(i.depth>=Wc)continue;let s;try{s=rt(E.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let o of s){if(!o.isDirectory()||o.name.startsWith(".")||o.name==="node_modules")continue;let c=i.rel==="."?o.name:E.join(i.rel,o.name);if(r+=1,r>=ki)break;Xt(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}a(Gc,"findWorkspaceRoots");function Vc(e){let t=[];try{let n=E.join(e,"pnpm-workspace.yaml");if(N(n)){let r=!1;for(let i of z(n,"utf8").split(`
34
+ `)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let o=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);o?t.push(o[1]):s.trim().length>0&&!/^\s/.test(s)&&(r=!1)}}}else{let r=E.join(e,"package.json");if(N(r)){let i=JSON.parse(z(r,"utf8")),s=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(s)&&t.push(...s.filter(o=>typeof o=="string"))}}}catch{return[]}return t}a(Vc,"workspacePatternsAt");function qc(e){let t=[];for(let n of Gc(e)){let r=n==="."?e:E.join(e,n),i=a(s=>n==="."?s:E.join(n,s),"prefix");for(let s of Vc(r)){if(t.length>=zt)break;if(!(s.startsWith("!")||s.includes("**")))try{if(s.endsWith("/*")){let o=s.slice(0,-2),c=E.join(r,o);if(!N(c))continue;for(let l of rt(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(E.join(o,l.name))),t.length>=zt)break}else s.includes("*")||t.push(i(s))}catch{}}}return t.slice(0,zt)}a(qc,"listWorkspacePackageDirs");function Ei(e){let t=null,n=0,r=[e];for(;r.length>0&&n<wi;){let i=r.pop();if(i===void 0)break;let s;try{s=rt(i,{withFileTypes:!0})}catch{continue}for(let o of s){if(o.name.startsWith(".")||o.name==="node_modules")continue;let c=E.join(i,o.name);if(o.isDirectory())r.push(c);else if(o.isFile()){n+=1;try{let l=Yt(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=wi)break}}}return t}a(Ei,"newestMtimeUnder");function zc(e,t){let n=new Set;for(let r of t)try{let i=E.join(e,r,"package.json");if(!N(i))continue;let s=JSON.parse(z(i,"utf8"));for(let o of["dependencies","devDependencies","peerDependencies"]){let c=s[o];if(!(c===null||typeof c!="object"))for(let[l,u]of Object.entries(c))typeof u=="string"&&u.startsWith("workspace:")&&n.add(l)}}catch{}return n}a(zc,"consumedWorkspaceNames");function Ti(e){let t=[],n=qc(e),r=zc(e,n);for(let i of n)try{let s=E.join(e,i,"package.json");if(!N(s))continue;let o=JSON.parse(z(s,"utf8"));if(typeof o.name!="string"||!r.has(o.name))continue;let c=a(g=>{if(typeof g!="string")return null;let w=g.replace(/^\.\//,"").split("/")[0];return w==="build"||w==="dist"?w:null},"builtSeg"),l=c(o.types??o.typings),u=c(o.main),d=l??u;if(d===null)continue;let f=l!==null&&u!==null?"both":l!==null?"types":"runtime",p=E.join(e,i,"src"),m=E.join(e,i,d);if(!N(p)||!N(m))continue;let h=Ei(p),y=Ei(m);if(h===null||y===null)continue;let b=h-y;b>Hc&&t.push({packageDir:i,buildDir:d,srcNewerByMs:Math.round(b),impact:f})}catch{}return t.sort((i,s)=>i.packageDir.localeCompare(s.packageDir))}a(Ti,"gatherStalePackageBuilds");function Yc(e,t){if(!t)return null;let n=Xc(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(s=>s.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}a(Yc,"gatherReleaseFact");function Xc(e,t){try{return Tc("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}a(Xc,"runGh");async function Zt(e,t={}){let n=await Ai(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=Si(n),i=Ri(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}a(Zt,"checkDivergence");import{existsSync as en,readdirSync as $i}from"node:fs";import{posix as U}from"node:path";var tn="could not diff against the base ref \u2014 everything reported as info";function nn(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(tn)}a(nn,"isNumberCollisionsGraded");var Jc=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,rn=3,Ii=.8;function Ni(e,t={}){let n=t.minFiles??rn;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Ii)}a(Ni,"isCounterNamespace");function se(e){return`${e.dir}#${e.prefix}`}a(se,"namespaceKey");function _e(e){let t=Jc.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}a(_e,"parseNumbered");function Ci(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let s=se(i),o=e.sightingsByNamespace.get(s);if(!o)continue;let c=new Set(o.keys());for(let[l,u]of o){let d=[...new Set(u.map(h=>h.path))];if(d.length<2)continue;let f=d.find(h=>n.has(h)),p=d.filter(h=>h!==f),m=`${i.prefix}${l}`;t.push(f?{id:`number.collision:${s}#${l}`,status:"open",namespace:i,number:l,title:`${m} is already taken`,detail:`This branch adds ${f}, but ${m} already exists as ${p.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${m} stop being unambiguous.`,ownPath:f,sightings:u.filter(h=>h.path!==f),suggestion:`${i.prefix}${sn(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${s}#${l}`,status:"info",namespace:i,number:l,title:`${m} is used more than once (pre-existing)`,detail:`${m} is carried by ${d.length} files: ${d.join(", ")}.`,sightings:u,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,s)=>r[i.status]-r[s.status]||i.id.localeCompare(s.id))}a(Ci,"computeNumberCollisions");function Oi(e){return!e.some(t=>t.status==="open")}a(Oi,"isCollisionFree");function sn(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}a(sn,"suggestNextNumber");function on(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}a(on,"normaliseRepoPath");function Di(e,t){let n=on(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=_e(U.basename(n));if(!i)return r;let s=`${U.dirname(n)}#${i.prefix}`,o=e.namespaces.find(d=>se(d)===s)??null;if(!o)return{...r,number:i.number};let c=e.sightingsByNamespace.get(s)??new Map,l=new Set,u=[];for(let d of c.get(i.number)??[])d.path===n||l.has(d.path)||(l.add(d.path),u.push(d));return{path:n,namespace:o,number:i.number,taken:u.length>0,sightings:u,suggestion:sn(c.keys(),i.number)}}a(Di,"checkProposedNumber");function it(e){let t=e?.trim();return t||null}a(it,"trimOrNull");function ie(e){return e?e.split(`
35
+ `).filter(Boolean):[]}a(ie,"lines");function Qc(e){let t=it(_(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(_(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}a(Qc,"resolveDefaultBranch");function Mi(e,t={}){let n=t.minFiles??rn,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=_(e,r);if(i===null)return[];let s=new Map;for(let o of i.split("\0").filter(Boolean)){let c=U.dirname(o),l=_e(U.basename(o));if(!l)continue;let u=`${c}#${l.prefix}`,d=s.get(u);d?d.numbers.push(l.number):s.set(u,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...s.values()].filter(o=>Ni(o.numbers,{...t,minFiles:n})).map(o=>({dir:o.dir,prefix:o.prefix,fileCount:o.numbers.length,distinctRatio:new Set(o.numbers).size/o.numbers.length})).sort((o,c)=>se(o).localeCompare(se(c)))}a(Mi,"detectNamespaces");async function an(e,t={}){let n=[];if(it(_(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,baseRef:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=Mi(e,t),s=new Map(i.map(h=>[se(h),h])),o=[...new Set(i.map(h=>h.dir))],c=new Map,l=a((h,y,b)=>{let g=U.dirname(h),w=_e(U.basename(h));if(!w)return;let S=`${g}#${w.prefix}`;if(!s.has(S))return;let A=c.get(S)??new Map,O=A.get(w.number)??[];O.push({kind:y,where:b,path:h}),A.set(w.number,O),c.set(S,A)},"record"),u=a((h,y,b)=>{if(o.length===0)return;let g=_(e,["ls-tree","-r","--name-only",h,"--",...o]);if(g===null){n.push(`could not read ${b}`);return}for(let w of ie(g))l(w,y,b)},"scanTree");for(let h of o){let y=U.join(e,h);if(en(y))try{for(let b of $i(y))l(`${h}/${b}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let d=Qc(e),f=t.baseRef??(d?`origin/${d}`:null);f?u(f,"default_branch",f):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let p=it(_(e,["rev-parse","--abbrev-ref","HEAD"]));for(let h of ie(_(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))h!==p&&u(h,"branch",`Branch ${h}`);if(t.includeWorktrees!==!1){let h=it(_(e,["rev-parse","--show-toplevel"]));for(let y of ie(_(e,["worktree","list","--porcelain"]))){if(!y.startsWith("worktree "))continue;let b=y.slice(9).trim();if(!(!b||b===h||!en(b)))for(let g of o){let w=U.join(b,g);if(en(w))try{for(let S of $i(w))l(`${g}/${S}`,"worktree",`Worktree ${b}`)}catch{n.push(`could not read ${g} in ${b}`)}}}}let m=[];if(f&&o.length>0){let h=_(e,["diff","--name-only","--diff-filter=A",`${f}...HEAD`,"--",...o]);h===null?n.push(tn):m=ie(h);let y=_(e,["ls-files","--others","--exclude-standard","--",...o]);y!==null&&(m=[...m,...ie(y)]);let b=_(e,["diff","--cached","--name-only","--diff-filter=A","--",...o]);b!==null&&(m=[...m,...ie(b)])}return{isRepo:!0,defaultBranch:d,baseRef:f,namespaces:i,sightingsByNamespace:c,addedPaths:m,skipped:n}}a(an,"gatherNumberCollisionFacts");async function we(e,t={}){let n=await an(e,t),r=Ci(n);return{ok:Oi(r),findings:r,facts:n}}a(we,"checkNumberCollisions");async function cn(e,t,n={}){let r=on(t);if(!_e(U.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await an(e,{...n,dirs:n.dirs??[U.dirname(r)]});return Di(i,r)}a(cn,"checkNumberForPath");var ln={det_number_collisions:{version:"1.1.0",rules:["number.collision"]},det_spec_drift:{version:"1.1.0",rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"]},det_theme_class_drift:{version:"1.1.0",rules:["theme.dead_class"]},det_table_acl_lint:{version:"1.0.0",rules:["acl.missing_revoke"]}};var un="number.collision",dn="theme.dead_class",fn="acl.missing_revoke";function pn(e){return`spec.${e}`}a(pn,"specDriftRuleId");function oe(e,t={}){switch(e){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return t.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(e)}' is not a finding status`)}}a(oe,"gradeEngineStatus");function Zc(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let s=0;s<i;s++){let o=(n[s].codePointAt(0)??0)-(r[s].codePointAt(0)??0);if(o!==0)return o}return n.length-r.length}a(Zc,"codePointCompare");function Li(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(Zc)}a(Li,"normalizeEvidenceForHash");function ke(e){return Ke(JSON.stringify(Li(e)))}a(ke,"hashDetectorEvidence");import{existsSync as el,readFileSync as Pi}from"node:fs";import{posix as tl}from"node:path";var Ki=".maind/spec-contracts.json";function ot(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}a(ot,"endOfString");function at(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
36
+ `,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}a(at,"skipComment");function Ee(e){return e==='"'||e==="'"||e==="`"}a(Ee,"isQuote");function ct(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}a(ct,"isCommentStart");function st(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let s=e[i];if(Ee(s)){i=ot(e,i);continue}if(ct(e,i)){i=at(e,i);continue}if(s==="["||s==="{")r++;else if((s==="]"||s==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}a(st,"sliceBalanced");function nl(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(ct(e,t)){t=at(e,t);continue}break}return e.slice(t)}a(nl,"stripLeadingTrivia");function ae(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let s=e[i];if(Ee(s)){i=ot(e,i);continue}if(ct(e,i)){i=at(e,i);continue}s==="["||s==="{"||s==="("?n++:s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(s=>nl(s).trim()).filter(s=>s.length>0)}a(ae,"splitTopLevel");function Bi(e){let t=ot(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
37
+ `:i==="r"?"\r":i==="t"?" ":i)}a(Bi,"readStringLiteral");function rl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(rl,"escapeRe");function hn(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${rl(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,s=!1;for(;i<e.length;){let o=e[i];if(Ee(o)){i=ot(e,i);continue}if(ct(e,i)){i=at(e,i);continue}if(!s){if(o==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))s=!0;else if(o===";")return null;i++;continue}if(o==="[")return st(e,i);if(o===";")return null;i++}return null}a(hn,"findSymbolArray");function gn(e){let t={};if(!e.startsWith("{"))return t;for(let n of ae(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],s=r[4].trim();Ee(s[0]??"")&&(t[i]=Bi(s))}return t}a(gn,"parseObjectFields");function il(e,t){if(!e.startsWith("{"))return null;for(let n of ae(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}a(il,"objectFieldRaw");function Hi(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}a(Hi,"pickFields");function Wi(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}a(Wi,"makeOrdinals");function Gi(e,t){let n=hn(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Wi(),i=[],s=0;for(let o of ae(n.slice(1,-1))){if(!o.startsWith("{")){s++;continue}let c=gn(o),l=c[t.key_field];if(!l){s++;continue}let u=(t.partition_by??[]).map(d=>c[d]??"");i.push({key:l,fields:Hi(c,t.fields),orderPath:u,ordinal:r(u)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}a(Gi,"extractObjectArray");function Vi(e,t){let n=hn(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};if(t.levels.length===0)return{records:[],error:`contract declares no levels for \`${t.symbol}\``,dropped:0};let r=Wi(),i=[],s=0,o=a((c,l,u)=>{let d=t.levels[l],f=l===t.levels.length-1;for(let p of ae(c.slice(1,-1))){let m={...u},h=null;if(d.shape==="object"){if(!p.startsWith("{")){s++;continue}let y=gn(p);for(let[b,g]of Object.entries(d.fields??{}))m[b]=y[String(g)]??"";if(!f&&typeof d.children=="string"){let b=il(p,d.children);h=b&&b.startsWith("[")?st(b,0):null}}else{if(!p.startsWith("[")){s++;continue}let y=ae(p.slice(1,-1));for(let[b,g]of Object.entries(d.fields??{})){let w=y[Number(g)];m[b]=w!==void 0&&Ee(w[0]??"")?Bi(w):""}if(!f&&typeof d.children=="number"){let b=y[d.children];h=b!==void 0&&b.startsWith("[")?st(b,0):null}}if(f){let y=m[t.key_field];if(!y){s++;continue}let b=(t.partition_by??[]).map(g=>m[g]??"");i.push({key:y,fields:Hi(m,t.fields),orderPath:b,ordinal:r(b)});continue}h!==null&&o(h,l+1,m)}},"walk");return o(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}a(Vi,"extractNestedList");function ji(e,t){return t.extractor==="object-array"?Gi(e,t):Vi(e,t)}a(ji,"extractRecords");function qi(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}a(qi,"isGrounded");function zi(e,t,n){return`spec.drift:${e}#${t}:${n}`}a(zi,"findingId");function sl(e){return e.orderPath.join(" / ")||"(flat)"}a(sl,"partitionOf");function Yi(e,t,n,r){let i=[],s=a((u,d,f,p,m,h)=>{i.push({id:zi(e.id,u,f),contract:e.id,dimension:u,status:d,key:f,title:p,detail:m,hint:h})},"push"),o=new Map(n.map(u=>[u.key,u])),c=new Map(t.map(u=>[u.key,u]));for(let u of t){let d=o.get(u.key);if(!d){s("coverage","open",u.key,`${u.key} is declared by the specification but missing from the implementation`,`Partition ${sl(u)}, position ${u.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let f of e.compare_fields??[]){let p=u.fields[f]??"",m=d.fields[f]??"";p!==m&&s("fields","open",`${u.key}.${f}`,`${u.key}: ${f} is "${m||"\u2014"}", the specification says "${p||"\u2014"}"`,`Field \`${f}\` disagrees between the two sides.`)}}let l=new Map;for(let u of t){let d=u.orderPath.join("\0"),f=l.get(d);f?f.push(u):l.set(d,[u])}for(let[u,d]of l){let f=d.filter(y=>o.has(y.key)).map(y=>y.key),p=n.filter(y=>y.orderPath.join("\0")===u).filter(y=>c.has(y.key)).map(y=>y.key),m=new Set(p),h=f.filter(y=>m.has(y));if(p.join("|")!==h.join("|")){let y=u.split("\0").join(" / ")||"(flat)";s("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${p.join(" \u2192 ")}
38
+ specification: ${h.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let u of n)c.has(u.key)||s("extra","warn",u.key,`${u.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let u of new Set([...o.keys(),...c.keys()])){if(qi(u,e.grounding,r))continue;let d=o.has(u);s("unrealized",d?"open":"warn",u,d?`${u} is referenced by the implementation but has no artefact`:`${u} is declared by the specification but not built yet`,d?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}a(Yi,"compareContract");function ol(e,t,n){let r=[];for(let i of e.assertions??[]){let s=n.get(i.path);if(!s)continue;let o=s.indexOf(i.prefix);if(o===-1)continue;let c=/^\s*(\d+)/.exec(s.slice(o+i.prefix.length));if(!c)continue;let l=Number(c[1]),u=t[i.counts];l!==u&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${u}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}a(ol,"checkAssertions");function Fi(e,t){return{id:`contract.unreadable:${e}`,contract:e,dimension:"contract",status:"open",key:null,title:`Contract "${e}" could not be evaluated`,detail:t,hint:"This is NOT a drift finding. An anchor moved, or a declared file is gone \u2014 repair the contract in the manifest, then re-run. Nothing has been compared for this contract."}}a(Fi,"unreadable");var Ui={open:0,warn:1,info:2,passed:3};function Xi(e,t={}){let n=a(d=>({ok:!1,verdict:"no_opinion",reason:d,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(d=>t.contracts.includes(d.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(d=>`"${d}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=a(d=>{let f=[],p=[];for(let m of r){let h=d.get(m.spec.path),y=d.get(m.impl.path);if(h==null||y==null){let S=h==null?m.spec.path:m.impl.path;f.push(Fi(m.id,`Declared file could not be read: ${S}`)),p.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let b=ji(h,m.spec),g=ji(y,m.impl);if(b.error||g.error){f.push(Fi(m.id,b.error??g.error??"unknown")),p.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let w=b.dropped>0||g.dropped>0;p.push({id:m.id,measured:!0,specRecords:b.records.length,implRecords:g.records.length,partial:w}),w&&f.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${b.dropped} specification and ${g.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),f.push(...Yi(m,b.records,g.records,e.files)),f.push(...ol(m,{spec:b.records.length,impl:g.records.length},d))}return{findings:f,contracts:p}},"runOnce"),s=i(e.sources),o=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let d of i(e.baselineSources).findings)d.id.startsWith("contract.unreadable:")||o.add(d.id);let c=new Map;for(let d of r)for(let f of d.exceptions??[])c.set(zi(d.id,f.dimension,f.key),f);let l=s.findings.map(d=>{let f=c.get(d.id);return f?{...d,status:"info",exceptionReason:f.reason}:o.has(d.id)?{...d,status:"info",detail:`${d.detail}
39
+ Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:d});l.sort((d,f)=>Ui[d.status]-Ui[f.status]||d.id.localeCompare(f.id));let u=l.some(d=>d.status==="open");return{ok:!u,verdict:u?"drifted":"aligned",reason:null,findings:l,contracts:s.contracts}}a(Xi,"computeSpecDrift");function mn(e){let t=e?.trim();return t||null}a(mn,"trimOrNull");function Ji(e){let t;try{t=JSON.parse(e)}catch(o){return{manifest:null,error:`manifest is not valid JSON: ${o.message}`}}let n=a(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null,"obj"),r=a(o=>typeof o=="string"?o:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let s=a(o=>({manifest:null,error:o}),"bad");for(let[o,c]of i.contracts.entries()){let l=n(c),u=r(l?.id),d=u?`contract "${u}"`:`contract #${o+1}`;if(!l)return s(`${d}: not an object`);if(!u)return s(`${d}: \`id\` is missing`);if(!r(l.reason))return s(`${d}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let f of["spec","impl"]){let p=n(l[f]);if(!p)return s(`${d}: \`${f}\` is missing`);let m=r(p.extractor);if(!m)return s(`${d}: \`${f}.extractor\` is missing`);if(m!=="object-array"&&m!=="nested-literal-list")return s(`${d}: unknown \`${f}.extractor\` "${m}"`);if(!r(p.path)||!r(p.symbol)||!r(p.key_field))return s(`${d}: \`${f}\` needs \`path\`, \`symbol\` and \`key_field\``);if(m==="nested-literal-list"&&!Array.isArray(p.levels))return s(`${d}: \`${f}\` is a nested-literal-list and needs \`levels\``)}for(let f of Array.isArray(l.exceptions)?l.exceptions:[]){let p=n(f);if(!p||!r(p.reason))return s(`${d}: exception for "${r(p?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}a(Ji,"parseManifest");function al(e){let t=mn(_(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(_(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}a(al,"resolveDefaultBranch");function cl(e){let t=new Set;for(let n of e.contracts){t.add(n.spec.path),t.add(n.impl.path);for(let r of n.assertions??[])t.add(r.path)}return[...t]}a(cl,"declaredPaths");async function Qi(e,t={}){let n=a((h,y)=>tl.join(h,y),"join"),r=t.manifestPath??Ki,i=[],s={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(mn(_(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...s,manifestError:"not a git work tree"};let o=n(e,r);if(!el(o))return{...s,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=Ji(Pi(o,"utf8")))}catch(h){l=`manifest at ${r} could not be read: ${h.message}`}if(!c)return{...s,isRepo:!0,manifestError:l};let u=new Map;for(let h of cl(c))try{u.set(h,Pi(n(e,h),"utf8"))}catch{u.set(h,null),i.push(`declared file unreadable in the working tree: ${h}`)}let d=new Set,f=_(e,["ls-files","-z"]);if(f===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let h of f.split("\0"))h&&d.add(h);let p=null,m=new Map;if(t.includeBaseline!==!1){let h=t.baseRef?null:al(e),y=t.baseRef??(h?`origin/${h}`:null);if(!y)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(p=mn(_(e,["merge-base",y,"HEAD"])),!p)i.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let b of u.keys())m.set(b,_(e,["show",`${p}:${b}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:u,baselineSources:m,baseRef:p,files:d,skipped:i}}a(Qi,"gatherSpecDriftFacts");async function xe(e,t={}){let n=await Qi(e,t);return{...Xi(n,t),facts:n}}a(xe,"checkSpecDrift");function yn(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}a(yn,"isSpecDriftGraded");import{readFileSync as ll}from"node:fs";import{join as ul,posix as dl}from"node:path";function Zi(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
40
+ `;)n++;continue}if(i==="/"&&s==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],u=e.indexOf(l,n+l.length);n=u===-1?r:u+l.length,t+=" ";continue}}let o=(i==="E"||i==="e")&&s==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||o){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}a(Zi,"stripSql");function Y(e){let t=[],n="",r=!1,i=!1,s=a(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){s();continue}n+=l}s();let o=t.filter(c=>c.length>0);return o.length===0||o.length>2?null:o.length===2?{schema:o[0],name:o[1]}:{schema:"public",name:o[0]}}a(Y,"normalizeQualifiedIdent");function ve(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}a(ve,"splitTopLevel");var bn=["INSERT","UPDATE","DELETE"],fl=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;function es(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(n)return null;let o=i.trim();if(fl.test(o))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(o);if(l){if(!ve(l[1]).map(p=>Y(p)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let f=o.replace(/^TABLE\s+/i,""),p=ve(f).map(m=>Y(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(p.length===0)return null;c=p}let u=ve(s).map(f=>f.replace(/^GROUP\s+/i,"").trim()).map(f=>Y(f)?.name??"").filter(f=>f.length>0&&f!=="public"),d=[];for(let f of ve(r)){let p=/^([A-Za-z]+)\s*(\()?/.exec(f.trim());if(!p)continue;let m=p[1].toUpperCase(),h=p[2]==="(";if(m==="ALL")return{tables:c,roles:u,writePrivs:[...bn]};!h&&bn.includes(m)&&d.push(m)}return{tables:c,roles:u,writePrivs:d}}a(es,"parseTableRevoke");function wn(e){let t=new Map,n=[...e].sort((r,i)=>be(r.version,i.version));for(let r of n){let i=Zi(r.content);for(let s of i.split(";")){let o=s.trim();if(!o)continue;let c=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(o);if(c){if(/\bTEMP(?:ORARY)?\b/i.test(c[1]??""))continue;let d=Y(c[2]);if(!d||d.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(o)&&t.has(d.name))continue;t.set(d.name,{createdIn:r.version,anonAddressed:!1,authWritesRevoked:new Set});continue}let l=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(o);if(l){let d=l[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let f of ve(d)){let p=Y(f);p&&p.schema==="public"&&t.delete(p.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(o);if(u){let d=Y(u[1]),f=Y(u[2]);if(d&&f&&d.schema==="public"){let p=t.get(d.name);p&&(t.delete(d.name),t.set(f.name,p))}continue}if(/^REVOKE\b/i.test(o)){let d=es(o);if(!d)continue;let f=d.tables==="all_in_public"?[...t.keys()]:d.tables,p=d.roles.includes("anon"),m=d.roles.includes("authenticated");if(!p&&!m)continue;for(let h of f){let y=t.get(h);if(y&&(p&&(y.anonAddressed=!0),m))for(let b of d.writePrivs)y.authWritesRevoked.add(b)}continue}}}return t}a(wn,"foldTableAcl");function _n(e){let t=[];for(let[n,r]of wn(e)){let i=[];r.anonAddressed||i.push("anon"),bn.every(s=>r.authWritesRevoked.has(s))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}a(_n,"evaluateTableAcl");function ts(e){let t=_n(e.files),n=new Map;if(e.baseFiles!==null)for(let r of _n(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),o=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:o,project:e.dir,table:r.table,createdIn:r.createdIn,missing:r.missing,title:`public.${r.table}: Default-Grants nie adressiert (${r.missing.join(", ")})`,detail:`\xDCber den gesamten Migrations-Bestand von ${e.dir}: ${c}. Supabase' ALTER DEFAULT PRIVILEGES grantet vollen CRUD an anon UND authenticated auf jede neue public-Tabelle; ohne Tabellen-REVOKE ist RLS die einzige Verteidigungslinie. Tabelle erzeugt in Migration ${r.createdIn}.`,hint:`REVOKE ALL ON public.${r.table} FROM PUBLIC, anon; REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.${r.table} FROM authenticated; \u2014 SELECT f\xFCr authenticated darf bewusst bleiben (RLS-gedecktes Lese-Muster). PUBLIC allein reicht NICHT (Default-Privileges sind direkte Rollen-Grants). Ein REVOKE in einer sp\xE4teren Migration z\xE4hlt ebenfalls; in DO-Bl\xF6cken z\xE4hlt es nicht (aufs Top-Level ziehen).`}})}a(ts,"computeTableAclFindings");function ns(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}a(ns,"deriveTableAclVerdict");var pl=5e6,lt="\u2014 findings reported ungraded (open)",kn="\u2014 baseline degraded";function En(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(lt)||t.endsWith(kn))}a(En,"isTableAclGraded");function ml(e,t){try{let n=ll(e,"utf8");return n.length>t?null:n}catch{return null}}a(ml,"safeRead");function hl(e,t,n,r,i){let s=_(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(s===null)return i.push(`could not diff ${t} against ${r} ${lt}`),null;let o=new Set,c=[];for(let d of s.split(`
41
+ `).filter(Boolean)){let[f,...p]=d.split(" ");f.startsWith("A")?o.add(p[0]):f.startsWith("R")?(c.push(p[0]),o.add(p[1])):(f.startsWith("M")||f.startsWith("D"))&&c.push(p[0])}let l=[],u=new Set(c);for(let{ref:d,content:f}of n)!o.has(d.path)&&!u.has(d.path)&&l.push({name:d.name,version:d.version,content:f});for(let d of c){let f=dl.basename(d),p=ye(f);if(p===null)continue;let m=_(e,["show",`${r}:${d}`]);if(m===null)return i.push(`could not read ${d} at ${r} ${kn}`),null;l.push({name:f,version:p,content:m})}return l}a(hl,"baseFilesFor");function xn(e,t={}){let n=t.maxFileBytes??pl,r=[],i=re(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let s=t.includeBaseline!==!1,o=null;if(s)if(t.baseRef)o=t.baseRef;else{let p=bi(e);o=p?`origin/${p}`:null,o===null&&r.push(`no default branch resolvable ${lt}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let p of i){let m=[];for(let b of p.files){let g=ml(ul(e,b.path),n);if(g===null){r.push(`could not read ${b.path} \u2014 excluded from the fold`);continue}m.push({ref:b,content:g})}let h=m.map(({ref:b,content:g})=>({name:b.name,version:b.version,content:g})),y=o===null?null:hl(e,p.dir,m,o,r);c.push(...ts({dir:p.dir,files:h,baseFiles:y})),l.push({dir:p.dir,migrationCount:h.length,tableCount:wn(h).size})}let u=l.reduce((p,m)=>p+m.migrationCount,0),d=ns(u,c.length),f={open:0,info:1};return c.sort((p,m)=>f[p.status]-f[m.status]||p.id.localeCompare(m.id)),{ok:d!=="no_opinion"&&!c.some(p=>p.status==="open"),verdict:d,findings:c,facts:{projects:l,baseRef:o,skipped:r}}}a(xn,"checkTableAclLint");import{readFileSync as gl}from"node:fs";import{join as vn}from"node:path";function Rn(e){return e.verdict!=="no_opinion"&&e.graded}a(Rn,"isThemeClassDriftGraded");var as=["bg","text","border","border-x","border-y","border-t","border-r","border-b","border-l","divide","outline","ring","ring-offset","fill","stroke","accent","caret","decoration","placeholder","shadow","from","via","to"],yl=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,bl=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+as.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");function An(e){let t=new Set;for(let n of e.matchAll(yl))t.add(n[1]);return t}a(An,"extractTokens");function Tn(e){return new Set([...e].map(t=>t.split("-")[0]))}a(Tn,"deriveNamespaces");function cs(e){return e.split(`
42
+ `).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
43
+ `)}a(cs,"stripCommentLines");function $n(e){let t=Tn(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let s=cs(i),o=new Set;for(let c of s.matchAll(bl)){let l=c[2],u=l.split("-")[0];if(!t.has(u)||e.tokens.has(l))continue;let d=`${c[1]}-${l}`;o.has(d)||(o.add(d),n.push({file:r,klass:d,token:l,namespace:u}))}}return n}a($n,"evaluateThemeClasses");function rs(e){return`${e.file} ${e.klass}`}a(rs,"findingKey");function _l(e,t){let n=t===null?null:new Set(t.map(rs));return e.map(r=>({...r,status:n!==null&&n.has(rs(r))?"info":"open"}))}a(_l,"gradeAgainstBaseline");function ls(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}a(ls,"deriveThemeClassVerdict");var is=["*.ts","*.tsx","*.js","*.jsx"],wl=15e5;function In(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}a(In,"isScannableSource");function ss(e,t){let n=_(e,["ls-files","--",...t]);return n===null?[]:n.split(`
44
+ `).filter(Boolean)}a(ss,"listTracked");function Nn(e,t={}){let n=t.maxFileBytes??wl,r=new Set;for(let d of ss(e,["*.css"])){let f=Sn(vn(e,d),n);if(f!==null)for(let p of An(f))r.add(p)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0,graded:!1,baseRef:null};let i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(d=>is.map(f=>`${d.replace(/\/+$/,"")}/**/${f}`)):is,s=[];for(let d of ss(e,i)){if(!In(d))continue;let f=Sn(vn(e,d),n);f!==null&&s.push({path:d,content:f})}let o=$n({tokens:r,sources:s}),c=t.includeBaseline===!1?null:kl(e,i,n,t.baseRef),l=_l(o,c?.findings??null),u=ls(r.size,l.length);return{ok:u!=="no_opinion"&&!l.some(d=>d.status==="open"),verdict:u,tokenCount:r.size,namespaceCount:Tn(r).size,findings:l,scannedFiles:s.length,graded:c!==null,baseRef:c?.mergeBase??null}}a(Nn,"checkThemeClassDrift");function kl(e,t,n,r){let i=r??xl(e);if(i===null)return null;let s=_(e,["merge-base",i,"HEAD"])?.trim();if(!s)return null;let o=_(e,["diff","--name-only","--no-renames",s]);if(o===null)return null;let c=new Set(o.split(`
45
+ `).filter(Boolean)),l=a(f=>c.has(f)?_(e,["show",`${s}:${f}`]):Sn(vn(e,f),n),"atBase"),u=new Set;for(let f of os(e,s,["*.css"])){let p=l(f);if(p!==null)for(let m of An(p))u.add(m)}if(u.size===0)return{findings:[],mergeBase:s};let d=[];for(let f of os(e,s,t)){if(!In(f))continue;let p=l(f);p===null||p.length>n||d.push({path:f,content:p})}return{findings:$n({tokens:u,sources:d}),mergeBase:s}}a(kl,"baselineFindings");function os(e,t,n){let r=_(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
46
+ `).filter(i=>i.length>0&&n.some(s=>El(i,s)))}a(os,"listTrackedAt");function El(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let s=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?s.endsWith(r.slice(1)):s===r}a(El,"matchesSourcePattern");function xl(e){let t=_(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>_(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}a(xl,"resolveBaseRef");function Sn(e,t){try{let n=gl(e,"utf8");return n.length>t?null:n}catch{return null}}a(Sn,"safeRead");var ps=64,vl={number:a((e,t)=>we(e,t),"number"),spec:a((e,t)=>xe(e,t),"spec"),theme:a((e,t)=>Nn(e,t),"theme"),acl:a((e,t)=>xn(e,t),"acl")},us=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint"];function Cn(e){return ln[e].version}a(Cn,"versionOf");function Re(e,t,n,r){return{detector_id:e,detector_version:Cn(e),state:t,finding_count:n,...r?{reason:r}:{}}}a(Re,"summary");function D(e,t,n){return{summary:Re(e,t,0,n),findings:[]}}a(D,"noFindings");function ms(e){return e==="open"||e==="warn"||e==="info"}a(ms,"isFindingStatus");function Sl(e){let t="det_number_collisions";if(!e.ok)return D(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return D(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return D(t,"not_applicable","no numbered namespaces");if(!nn(n))return D(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!ms(s.status))continue;let{level:o,baseline:c}=oe(s.status);i.push({detector_id:t,rule_id:un,level:o,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:Re(t,"ran",i.length),findings:i}}a(Sl,"adaptNumber");function Rl(e){let t="det_spec_drift";if(!e.ok)return D(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return D(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return D(t,"not_applicable",n.reason??"no opinion");if(!yn(n))return D(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!ms(i.status))continue;let{level:s,baseline:o}=oe(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:pn(i.dimension),level:s,baseline:o,evidence:[i.id],title:i.title})}return{summary:Re(t,"ran",r.length),findings:r}}a(Rl,"adaptSpec");function Al(e){let t="det_theme_class_drift";if(!e.ok)return D(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return D(t,"not_applicable","no theme tokens");if(!Rn(n))return D(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=oe(i.status);r.push({detector_id:t,rule_id:dn,level:s,baseline:o,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:Re(t,"ran",r.length),findings:r}}a(Al,"adaptTheme");function Tl(e){let t="det_table_acl_lint";if(!e.ok)return D(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return D(t,"not_applicable","no supabase migrations");if(!En(n))return D(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:o}=oe(i.status);r.push({detector_id:t,rule_id:fn,level:s,baseline:o,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Re(t,"ran",r.length),findings:r}}a(Tl,"adaptAcl");var dt={open:0,warn:1,info:2},ds={introduced:0,pre_existing:1};function On(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||dt[e.level]-dt[t.level]||ds[e.baseline]-ds[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}a(On,"compareWire");function fs(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}a(fs,"capPriority");function $l(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let s=ke(i.evidence),o=`${i.detector_id}|${i.rule_id}|${i.level}|${s}`,c=t.get(o);c?c.count+=1:t.set(o,{detector_id:i.detector_id,detector_version:Cn(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:s,count:1})}else{let s=`${i.detector_id}|${i.rule_id}`,o=n.get(s);o?(o.evidence.push(...i.evidence),o.count+=1,dt[i.level]<dt[o.level]&&(o.level=i.level)):n.set(s,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:Cn(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:ke(i.evidence),count:i.count});return r.sort(On)}a($l,"buildWire");function Il(e,t){let n=e.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<e.length||t>0?"partial":"full"}a(Il,"deriveCoverage");function ce(e){let t={det_number_collisions:Sl(e.number),det_spec_drift:Rl(e.spec),det_theme_class_drift:Al(e.theme),det_table_acl_lint:Tl(e.acl)},n=us.map(l=>t[l].summary),r=us.flatMap(l=>t[l].findings),i=$l(r),s=[...i].sort((l,u)=>fs(l)-fs(u)||On(l,u)).slice(0,ps).sort(On),o=i.length-s.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:ke(l.evidence),title:l.title}));return{findings:s,coverage:Il(n,o),engines:n,local:c,truncated:o}}a(ce,"adaptDetectorReports");function Se(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e}}}a(Se,"unavailableDetectorReports");function hs(e){return e instanceof Error?e.message:String(e)}a(hs,"errorText");async function ut(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:hs(t)}}}a(ut,"attempt");async function Dn(e,t={}){let n={...vl,...t.engines};try{if(_(e,["rev-parse","--is-inside-work-tree"])?.trim()!=="true")return ce(Se("not a git work tree"));let i=t.baseRef,s={number:await ut(()=>n.number(e,{...i?{baseRef:i}:{},...t.includeWorktrees===void 0?{}:{includeWorktrees:t.includeWorktrees}})),spec:await ut(()=>n.spec(e,i?{baseRef:i}:{})),theme:await ut(()=>n.theme(e,i?{baseRef:i}:{})),acl:await ut(()=>n.acl(e,i?{baseRef:i}:{}))};return ce(s)}catch(r){return ce(Se(`detector adapter failed: ${hs(r)}`))}}a(Dn,"runRepoHealthDetectors");var gs=[{flag:"sql_migration_added",path:/(^|\/)migrations\/[^/]+\.sql$/i,onlyWhenAdded:!0},{flag:"security_definer_touched",path:/\.sql$/i,content:/\bSECURITY\s+DEFINER\b/i},{flag:"rls_policy_changed",path:/\.sql$/i,content:/\b(CREATE|ALTER|DROP)\s+POLICY\b|\bROW\s+LEVEL\s+SECURITY\b/i},{flag:"auth_config_changed",path:/(^|\/)supabase\/config\.toml$|(^|\/)(middleware|proxy)\.(ts|js)$/},{flag:"package_manifest_changed",path:/(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|requirements\.txt|pyproject\.toml|Cargo\.toml|go\.mod)$/},{flag:"ci_workflow_changed",path:/^\.github\/workflows\/[^/]+\.ya?ml$|^\.gitlab-ci\.yml$/},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}];function ys(e){let t=new Set;for(let[n,r]of e.paths)for(let i of gs){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=Nl(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}a(ys,"scanRiskFlags");function Nl(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
47
+ `):t.readUntracked(e)}a(Nl,"contentForPath");var le="1";var bs=`
41
48
  CREATE TABLE IF NOT EXISTS meta (
42
49
  key TEXT PRIMARY KEY,
43
50
  value TEXT NOT NULL
@@ -96,7 +103,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
96
103
  vec BLOB NOT NULL,
97
104
  content_hash TEXT NOT NULL
98
105
  );
99
- `,ie="schema_version",se="last_index_commit",Bt="last_indexed_at",qe="embed_recipe_version",ze="embed_model",Ye="embed_dim",Ht="last_synced_at",ai="last_synced_commit";function Wt(e){return e.replace(/[_\-./]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(t=>t.length>0)}a(Wt,"splitIdentifier");function ci(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of Wt(e.name))t.add(i);for(let i of Wt(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}a(ci,"buildSearchText");function li(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let i of Wt(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}a(li,"toFtsMatchQuery");var me=class{static{a(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(ie),i=await this.store.countFiles()>0;(t.full||i&&r!==re)&&await this.wipe();let s=dr(this.repoRoot),o=new Set(s.map(g=>g.path)),c=await this.store.getAllFiles(),l=new Map(c.map(g=>[g.path,g])),u=c.length>0&&!t.full,d={filesScanned:s.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u};for(let g of c)o.has(g.path)||(await this.store.deleteFile(g.path),d.filesDeleted++);let f=[],p=0;for(let g of s){p++;let m=mr(this.repoRoot,g.path);if(!m){d.filesSkipped++;continue}let b=l.get(g.path);if(b&&b.mtimeMs===m.mtimeMs&&b.size===m.size){d.filesSkipped++;continue}let y=this.readRepoFile(g.path);if(y===null){d.filesSkipped++;continue}let w=Fe(y);if(b&&b.contentHash===w){await this.store.upsertFile({...b,mtimeMs:m.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let x=await this.parser.parse(g.path,y,g.language),E=new Map;for(let $ of x.nodes)E.set($.nodeKey,ci($));let v={path:g.path,language:g.language,contentHash:w,mtimeMs:m.mtimeMs,size:m.size,indexedAt:n};await this.store.replaceFileNodes(v,x.nodes,E),f.push(x),d.filesParsed++,t.onProgress?.({path:g.path,done:p,total:s.length})}if(f.length>0){let g=await this.store.getNameIndex(),m=ir(g);for(let b of f){let y=sr(b,m);await this.store.replaceOutgoingEdges(y.srcKeys,y.edges)}}if(this.embedder&&t.embed){let g=await this.store.getNodesByKinds([...wt]),m=await this.store.getEmbeddingContentHashes(),b=[];for(let w of g){let x=nr(w),E=Fe(`${this.embedder.recipeVersion}\0${x}`);m.get(w.nodeKey)!==E&&b.push({nodeKey:w.nodeKey,text:x,hash:E})}let y=64;for(let w=0;w<b.length;w+=y){let x=b.slice(w,w+y),E=await this.embedder.embedDocuments(x.map($=>$.text));await this.store.upsertEmbeddings(x.map(($,M)=>({nodeKey:$.nodeKey,dim:this.embedder.dim,vec:E[M],contentHash:$.hash})));let v=Math.min(w+y,b.length);t.onProgress?.({path:"embedding symbols",done:v,total:b.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(qe,this.embedder.recipeVersion),await this.store.setMeta(ze,this.embedder.model),await this.store.setMeta(Ye,String(this.embedder.dim))}await this.store.setMeta(ie,re),await this.store.setMeta(Bt,String(n));let h=ue(this.repoRoot);return h&&await this.store.setMeta(se,h),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let s of n)r[s.language]=s.count;let i=await this.store.getMeta(Bt);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(se),schemaVersion:await this.store.getMeta(ie),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Y(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),s=[];for(let o of i){let c=await this.store.getNode(o.nodeKey);c&&s.push({...fi(c),score:o.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Y(n.limit,20,100),i=await this.embedder.embedQuery(t),o=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:rr(i,l.vec)})).sort((l,u)=>u.score-l.score).slice(0,r),c=[];for(let l of o){let u=await this.store.getNode(l.nodeKey);u&&c.push({...fi(u),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Y(n.maxDepth,3,5),s=Y(n.limit,100,1e3),o=n.kinds??null,c=[],l=new Set,u=new Set([t]),d=[t];for(let f=0;f<i&&d.length>0;f++){let p=[];for(let h of d){let g=await this.store.neighbors(h,r,o,s);for(let m of g){let b=`${m.srcKey} ${m.dstKey} ${m.kind}`;if(l.has(b))continue;if(l.add(b),c.push({srcKey:m.srcKey,dstKey:m.dstKey,kind:m.kind}),c.length>=s)return c;let y=r==="out"?m.dstKey:m.srcKey;u.has(y)||(u.add(y),p.push(y))}}d=p}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=ui(di.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let o of n)i[o.kind]=o.count;let s={};for(let o of r)s[o.language]=o.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:s,topModules:await this.store.topModulesByFanIn(Y(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=pr(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Y(t.limit,64,200),i=[],s=0;for(let o of n){let c=await this.store.getNodesByFile(o.path);c.length>0&&s++,i.push(...c)}return i.sort((o,c)=>o.filePath.localeCompare(c.filePath)||o.startLine-c.startLine),{changedFiles:n.length,indexedFiles:s,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=je(this.repoRoot,{since:t.since});if(r===null)throw new Error("fileHistory requires a git repository (history is git-based)");n=[...r.keys()]}else if(ue(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Er(this.repoRoot,n,t)}async checkDivergence(t={}){return It(this.repoRoot,t)}async checkNumberCollisions(t={}){return Pt(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Lt(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Kt(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=je(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=yr(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",o=si({paths:n,hunks:i,readUntracked:a(p=>this.readRepoFileHead(p,gr),"readUntracked")}),c=ur(n.keys()),l=Y(t.limit,64,200),u=[],d=0,f=0;for(let p of c){let h=await this.store.getNodesByFile(p.path);if(h.length===0)continue;d++;let g=await this.store.getFile(p.path),m=this.readRepoFile(p.path),b=g!==null&&m!==null&&Fe(m)!==g.contentHash;b&&(f++,s==="full"&&(s="partial"));let y=n.get(p.path)??"modified",w=i.get(p.path);for(let x of h)u.push(Wa(x,y,w,b))}return u.sort((p,h)=>pi(p.change)-pi(h.change)||p.filePath.localeCompare(h.filePath)||p.startLine-h.startLine),{changedFiles:c.length,indexedFiles:d,staleFiles:f,symbols:u.slice(0,l),truncated:u.length>l,riskFlags:o,hunkCoverage:s,baseKind:t.since?"ref":"uncommitted",headSha:ue(this.repoRoot),dirty:hr(this.repoRoot),baseSha:t.since?Ue(this.repoRoot,t.since):null}}async close(){await this.store.close()}readRepoFileHead(t,n){let r=this.readRepoFile(t);return r===null?null:r.slice(0,n)}readRepoFile(t){try{return ui(di.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};function fi(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}a(fi,"toHit");function Y(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}a(Y,"clampLimit");function pi(e){return e==="added"?0:e==="modified"?1:2}a(pi,"changeRank");function Wa(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let o of n.addedRanges){let c=Math.max(o.start,e.startLine),l=Math.min(o.end,e.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(o=>o>=e.startLine-1&&o<=e.endLine);return i>0||s?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}a(Wa,"classifyReviewSymbol");import{createRequire as Ga}from"node:module";var mi=Ga(import.meta.url);function hi(){return mi("node:sqlite")}a(hi,"loadBuiltin");var he=null;function Gt(){if(he)return he;try{let{DatabaseSync:e}=hi(),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(),he={ok:!0}}finally{t.close()}}catch(e){he={ok:!1,reason:e instanceof Error?e.message:String(e)}}return he}a(Gt,"probeBuiltinSqlite");function Va(e){let{DatabaseSync:t}=hi(),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>n.exec(r),"exec"),close:a(()=>n.close(),"close"),transaction:a(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}a(Va,"openBuiltin");function qa(e){let t=mi("better-sqlite3"),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>{n.exec(r)},"exec"),close:a(()=>{n.close()},"close"),transaction:a(r=>n.transaction(r),"transaction")}}a(qa,"openBetter");function za(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}a(za,"backendOverride");function Vt(e){let t=za(),n=a(i=>{let s=i==="node:sqlite"?Va(e):qa(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=Gt();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=Gt();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${s})`)}}a(Vt,"openSqliteDatabase");function Xe(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}}a(Xe,"toNodeRow");var gi=400,ge=class{static{a(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Vt(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(oi)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r){this.db.transaction(()=>{this.deleteFileGraph(t.path);let s=this.insertNodeStmt(),o=this.insertFtsStmt();for(let c of n)s.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),o.run(c.nodeKey,r.get(c.nodeKey)??c.name);this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let o of t)i.run(o);let s=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let o of n)s.run(o.srcKey,o.dstKey,o.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?Xe(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Xe)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Xe)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Xe)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let s=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,s,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=li(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
106
+ `,ue="schema_version",de="last_index_commit",Mn="last_indexed_at",ft="embed_recipe_version",pt="embed_model",mt="embed_dim",Ln="last_synced_at",_s="last_synced_commit";function Pn(e){return e.replace(/[_\-./]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(t=>t.length>0)}a(Pn,"splitIdentifier");function ws(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of Pn(e.name))t.add(i);for(let i of Pn(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}a(ws,"buildSearchText");function ks(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let i of Pn(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}a(ks,"toFtsMatchQuery");var Ae=class{static{a(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(ue),i=await this.store.countFiles()>0;(t.full||i&&r!==le)&&await this.wipe();let s=ri(this.repoRoot),o=new Set(s.map(h=>h.path)),c=await this.store.getAllFiles(),l=new Map(c.map(h=>[h.path,h])),u=c.length>0&&!t.full,d={filesScanned:s.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u};for(let h of c)o.has(h.path)||(await this.store.deleteFile(h.path),d.filesDeleted++);let f=[],p=0;for(let h of s){p++;let y=oi(this.repoRoot,h.path);if(!y){d.filesSkipped++;continue}let b=l.get(h.path);if(b&&b.mtimeMs===y.mtimeMs&&b.size===y.size){d.filesSkipped++;continue}let g=this.readRepoFile(h.path);if(g===null){d.filesSkipped++;continue}let w=et(g);if(b&&b.contentHash===w){await this.store.upsertFile({...b,mtimeMs:y.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let S=await this.parser.parse(h.path,g,h.language),A=new Map;for(let x of S.nodes)A.set(x.nodeKey,ws(x));let O={path:h.path,language:h.language,contentHash:w,mtimeMs:y.mtimeMs,size:y.size,indexedAt:n};await this.store.replaceFileNodes(O,S.nodes,A),f.push(S),d.filesParsed++,t.onProgress?.({path:h.path,done:p,total:s.length})}if(f.length>0){let h=await this.store.getNameIndex(),y=Xr(h);for(let b of f){let g=Jr(b,y);await this.store.replaceOutgoingEdges(g.srcKeys,g.edges)}}if(this.embedder&&t.embed){let h=await this.store.getNodesByKinds([...Ut]),y=await this.store.getEmbeddingContentHashes(),b=[];for(let w of h){let S=zr(w),A=et(`${this.embedder.recipeVersion}\0${S}`);y.get(w.nodeKey)!==A&&b.push({nodeKey:w.nodeKey,text:S,hash:A})}let g=64;for(let w=0;w<b.length;w+=g){let S=b.slice(w,w+g),A=await this.embedder.embedDocuments(S.map(x=>x.text));await this.store.upsertEmbeddings(S.map((x,C)=>({nodeKey:x.nodeKey,dim:this.embedder.dim,vec:A[C],contentHash:x.hash})));let O=Math.min(w+g,b.length);t.onProgress?.({path:"embedding symbols",done:O,total:b.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(ft,this.embedder.recipeVersion),await this.store.setMeta(pt,this.embedder.model),await this.store.setMeta(mt,String(this.embedder.dim))}await this.store.setMeta(ue,le),await this.store.setMeta(Mn,String(n));let m=ge(this.repoRoot);return m&&await this.store.setMeta(de,m),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let s of n)r[s.language]=s.count;let i=await this.store.getMeta(Mn);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(de),schemaVersion:await this.store.getMeta(ue),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Z(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),s=[];for(let o of i){let c=await this.store.getNode(o.nodeKey);c&&s.push({...vs(c),score:o.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Z(n.limit,20,100),i=await this.embedder.embedQuery(t),o=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Yr(i,l.vec)})).sort((l,u)=>u.score-l.score).slice(0,r),c=[];for(let l of o){let u=await this.store.getNode(l.nodeKey);u&&c.push({...vs(u),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Z(n.maxDepth,3,5),s=Z(n.limit,100,1e3),o=n.kinds??null,c=[],l=new Set,u=new Set([t]),d=[t];for(let f=0;f<i&&d.length>0;f++){let p=[];for(let m of d){let h=await this.store.neighbors(m,r,o,s);for(let y of h){let b=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(b))continue;if(l.add(b),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=s)return c;let g=r==="out"?y.dstKey:y.srcKey;u.has(g)||(u.add(g),p.push(g))}}d=p}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=Es(xs.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let o of n)i[o.kind]=o.count;let s={};for(let o of r)s[o.language]=o.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:s,topModules:await this.store.topModulesByFanIn(Z(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=si(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Z(t.limit,64,200),i=[],s=0;for(let o of n){let c=await this.store.getNodesByFile(o.path);c.length>0&&s++,i.push(...c)}return i.sort((o,c)=>o.filePath.localeCompare(c.filePath)||o.startLine-c.startLine),{changedFiles:n.length,indexedFiles:s,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Ze(this.repoRoot,{since:t.since});if(r===null)throw new Error("fileHistory requires a git repository (history is git-based)");n=[...r.keys()]}else if(ge(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return hi(this.repoRoot,n,t)}async checkDivergence(t={}){return Zt(this.repoRoot,t)}async checkNumberCollisions(t={}){return we(this.repoRoot,t)}async checkNumberForPath(t,n={}){return cn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return xe(this.repoRoot,t)}async reviewDetectors(t={}){return Dn(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Ze(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=li(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",o=ys({paths:n,hunks:i,readUntracked:a(p=>this.readRepoFileHead(p,ci),"readUntracked")}),c=ni(n.keys()),l=Z(t.limit,64,200),u=[],d=0,f=0;for(let p of c){let m=await this.store.getNodesByFile(p.path);if(m.length===0)continue;d++;let h=await this.store.getFile(p.path),y=this.readRepoFile(p.path),b=h!==null&&y!==null&&et(y)!==h.contentHash;b&&(f++,s==="full"&&(s="partial"));let g=n.get(p.path)??"modified",w=i.get(p.path);for(let S of m)u.push(Cl(S,g,w,b))}return u.sort((p,m)=>Ss(p.change)-Ss(m.change)||p.filePath.localeCompare(m.filePath)||p.startLine-m.startLine),{changedFiles:c.length,indexedFiles:d,staleFiles:f,symbols:u.slice(0,l),truncated:u.length>l,riskFlags:o,hunkCoverage:s,baseKind:t.since?"ref":"uncommitted",headSha:ge(this.repoRoot),dirty:ai(this.repoRoot),baseSha:t.since?tt(this.repoRoot,t.since):null}}async close(){await this.store.close()}readRepoFileHead(t,n){let r=this.readRepoFile(t);return r===null?null:r.slice(0,n)}readRepoFile(t){try{return Es(xs.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};function vs(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}a(vs,"toHit");function Z(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}a(Z,"clampLimit");function Ss(e){return e==="added"?0:e==="modified"?1:2}a(Ss,"changeRank");function Cl(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let o of n.addedRanges){let c=Math.max(o.start,e.startLine),l=Math.min(o.end,e.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(o=>o>=e.startLine-1&&o<=e.endLine);return i>0||s?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}a(Cl,"classifyReviewSymbol");import{createRequire as Ol}from"node:module";var Rs=Ol(import.meta.url);function As(){return Rs("node:sqlite")}a(As,"loadBuiltin");var Te=null;function jn(){if(Te)return Te;try{let{DatabaseSync:e}=As(),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(),Te={ok:!0}}finally{t.close()}}catch(e){Te={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Te}a(jn,"probeBuiltinSqlite");function Dl(e){let{DatabaseSync:t}=As(),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>n.exec(r),"exec"),close:a(()=>n.close(),"close"),transaction:a(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}a(Dl,"openBuiltin");function Ml(e){let t=Rs("better-sqlite3"),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>{n.exec(r)},"exec"),close:a(()=>{n.close()},"close"),transaction:a(r=>n.transaction(r),"transaction")}}a(Ml,"openBetter");function Ll(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}a(Ll,"backendOverride");function Fn(e){let t=Ll(),n=a(i=>{let s=i==="node:sqlite"?Dl(e):Ml(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=jn();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=jn();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${s})`)}}a(Fn,"openSqliteDatabase");function ht(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}}a(ht,"toNodeRow");var Ts=400,$e=class{static{a(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Fn(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(bs)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r){this.db.transaction(()=>{this.deleteFileGraph(t.path);let s=this.insertNodeStmt(),o=this.insertFtsStmt();for(let c of n)s.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),o.run(c.nodeKey,r.get(c.nodeKey)??c.name);this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let o of t)i.run(o);let s=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let o of n)s.run(o.srcKey,o.dstKey,o.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?ht(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(ht)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(ht)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(ht)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let s=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,s,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=ks(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
100
107
  FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
101
108
  WHERE nodes_fts MATCH ? AND n.kind = ?
102
109
  ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
@@ -109,7 +116,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
109
116
  FROM nodes n
110
117
  WHERE n.kind = 'module'
111
118
  ORDER BY imports_in DESC, symbol_count DESC
112
- LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(s=>s.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let s=0;s<n.length;s+=gi)for(let o of n.slice(s,s+gi))r.run(o),i.run(o);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
119
+ LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(s=>s.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let s=0;s<n.length;s+=Ts)for(let o of n.slice(s,s+Ts))r.run(o),i.run(o);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
113
120
  node_key, kind, name, qualified_name, file_path, language,
114
121
  start_line, end_line, start_byte, end_byte, signature, doc
115
122
  ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)),this._insNode}_insFts=null;insertFtsStmt(){return this._insFts||(this._insFts=this.db.prepare("INSERT INTO nodes_fts(node_key, search_text) VALUES(?, ?)")),this._insFts}_upsertFile=null;upsertFileStmt(){return this._upsertFile||(this._upsertFile=this.db.prepare(`INSERT INTO files(path, language, content_hash, mtime_ms, size, indexed_at)
@@ -119,112 +126,112 @@ CREATE TABLE IF NOT EXISTS embeddings (
119
126
  content_hash = excluded.content_hash,
120
127
  mtime_ms = excluded.mtime_ms,
121
128
  size = excluded.size,
122
- indexed_at = excluded.indexed_at`)),this._upsertFile}};import{createHash as Ya}from"node:crypto";function oe(e){return Ya("sha256").update(e,"utf8").digest("hex")}a(oe,"sha256");function yi(e){return{node_key_hash:oe(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:oe(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?oe(e.signature):null}}a(yi,"toCloudNode");function bi(e){return{src_key_hash:oe(e.srcKey),dst_key_hash:oe(e.dstKey),kind:e.kind}}a(bi,"toCloudEdge");function _i(e,t,n){return{node_key_hash:oe(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}a(_i,"toCloudEmbedding");var X=class extends Error{static{a(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},ye=class{static{a(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(se),lastSyncedAt:wi(await this.store.getMeta(Ht))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(yi),n=(await this.store.getAllEdges()).map(bi),r=await this.store.getMeta(ie)??re,i=await this.store.getMeta(se),s=await this.store.countFiles(),o=Object.fromEntries((await this.store.languageDistribution()).map(m=>[m.language,m.count])),c={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:o},l=0,u=qt(t,this.chunk),d=qt(n,this.chunk*2),f=Math.max(1,u.length+d.length);for(let m of u)await this.post("/api/codebase/push",{...c,nodes:m,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:f});for(let m of d)await this.post("/api/codebase/push",{...c,nodes:[],edges:m}),this.cfg.onProgress?.({phase:"edges",done:++l,total:f});u.length===0&&d.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let p=t.map(m=>m.node_key_hash),h=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:p});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(Ht,String(Date.now())),i&&await this.store.setMeta(ai,i),{nodes:t.length,edges:n.length,pruned:Ja(h.nodes_deleted),embeddings:g,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),s=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},o=(await this.store.allEmbeddings()).map(u=>_i(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&s[u.node_key_hash]!==u.content_hash);if(o.length===0)return 0;let c=qt(o,Xa),l=0;for(let u of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return o.length}async embedMeta(){let t=await this.store.getMeta(qe),n=await this.store.getMeta(ze),r=wi(await this.store.getMeta(Ye));if(!t||!n||!r)throw new X("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let s=i?.error;throw new X(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},Xa=250;function qt(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}a(qt,"chunkArray");function wi(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}a(wi,"numOrNull");function Ja(e){return typeof e=="number"&&Number.isFinite(e)?e:0}a(Ja,"numOr0");var ki=".maind/code-index.sqlite";function Je(e){let t=e.dbPath??zt.join(e.repoRoot,ki);Qa(zt.dirname(t),{recursive:!0});let n=new ge(t),r=new De;return new me({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}a(Je,"createNodeCodeIndex");function xi(e){let t=e.dbPath??zt.join(e.repoRoot,ki),n=e.projectKey??In(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 ge(t);return new ye(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}a(xi,"createCodeIndexSync");var Xt=process.env.MAIND_EMBEDDING_MODEL??"Xenova/bge-small-en-v1.5",Ei=Number(process.env.MAIND_EMBEDDING_DIM??384),Za=process.env.MAIND_EMBEDDING_DTYPE??"q8",ec="Represent this sentence for searching relevant passages: ";var Yt=null;async function tc(){return Yt||(Yt=(async()=>{let e=await import("@huggingface/transformers"),t=process.env.MAIND_EMBEDDING_CACHE_DIR;return t&&(e.env.cacheDir=t),e.pipeline("feature-extraction",Xt,{dtype:Za,device:"cpu"})})()),Yt}a(tc,"getExtractor");function Si(){let e={async embedDocuments(t){return t.length===0?[]:(await(await tc())(t,{pooling:"cls",normalize:!0})).tolist().map(i=>Float32Array.from(i))},async embedQuery(t){let[n]=await e.embedDocuments([ec+t]);return n}};return e}a(Si,"createEmbedder");var Qe=class{static{a(this,"NodeEmbedder")}dim=Ei;model=Xt;recipeVersion=tr;inner=Si();embedDocuments(t){return this.inner.embedDocuments(t)}embedQuery(t){return this.inner.embedQuery(t)}};function vi(){return new Qe}a(vi,"createNodeEmbedder");var Ai="MAIND_ORT_OK_FILE",Ti="--_ort-worker",dc=uc(new URL("./index.js",import.meta.url));function $i(e){return e.includes(Ti)}a($i,"isOrtWorker");function Ii(e){let t=sc(Ri(cc(),"maind-ort-")),n=Ri(t,"ok"),r=rc(process.execPath,[dc,...e,Ti],{stdio:["ignore","inherit","inherit"],env:{...process.env,[Ai]:n}}),i=ic(n);try{oc(lc(n),{recursive:!0,force:!0})}catch{}return i?0:r.status&&r.status!==0?r.status:1}a(Ii,"runOrtIsolated");function Ni(){let e=process.env[Ai];if(e)try{ac(e,"ok")}catch{}}a(Ni,"markOrtOk");function Jt(e,t){return e.includes(t)}a(Jt,"flag");function Ze(e,t){let n=e.indexOf(t);if(!(n===-1||n+1>=e.length))return e[n+1]}a(Ze,"value");function fc(e){if(e)return e;try{return nc("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return process.cwd()}}a(fc,"resolveRoot");function be(e){return Je({repoRoot:e.root,dbPath:e.db??void 0,embedder:vi()})}a(be,"openIndex");function Oi(e){return{root:fc(Ze(e,"--root")),db:Ze(e,"--db")??null,full:Jt(e,"--full"),embed:Jt(e,"--embed"),json:Jt(e,"--json")}}a(Oi,"baseOpts");function et(e){return Oi(e)}a(et,"parseIndexArgs");function Qt(e){let t=e.find(s=>!s.startsWith("--")),n=Ze(e,"--limit"),r=n?Number.parseInt(n,10):15,i=Ze(e,"--kind");return{...Oi(e),query:t??"",kind:i??null,limit:Number.isFinite(r)&&r>0?r:15}}a(Qt,"parseIndexSearchArgs");async function Ci(e){let t=be(e);try{let n=await t.indexRepository({full:e.full,embed:e.embed,onProgress:e.json?void 0:r=>{process.stderr.write(`\r ${r.done}/${r.total} ${r.path.slice(0,60)}`.padEnd(84))}});if(e.json)process.stdout.write(JSON.stringify(n)+`
129
+ indexed_at = excluded.indexed_at`)),this._upsertFile}};import{createHash as Pl}from"node:crypto";function fe(e){return Pl("sha256").update(e,"utf8").digest("hex")}a(fe,"sha256");function $s(e){return{node_key_hash:fe(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:fe(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?fe(e.signature):null}}a($s,"toCloudNode");function Is(e){return{src_key_hash:fe(e.srcKey),dst_key_hash:fe(e.dstKey),kind:e.kind}}a(Is,"toCloudEdge");function Ns(e,t,n){return{node_key_hash:fe(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}a(Ns,"toCloudEmbedding");var ee=class extends Error{static{a(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},Ie=class{static{a(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(de),lastSyncedAt:Cs(await this.store.getMeta(Ln))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map($s),n=(await this.store.getAllEdges()).map(Is),r=await this.store.getMeta(ue)??le,i=await this.store.getMeta(de),s=await this.store.countFiles(),o=Object.fromEntries((await this.store.languageDistribution()).map(y=>[y.language,y.count])),c={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:o},l=0,u=Un(t,this.chunk),d=Un(n,this.chunk*2),f=Math.max(1,u.length+d.length);for(let y of u)await this.post("/api/codebase/push",{...c,nodes:y,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:f});for(let y of d)await this.post("/api/codebase/push",{...c,nodes:[],edges:y}),this.cfg.onProgress?.({phase:"edges",done:++l,total:f});u.length===0&&d.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let p=t.map(y=>y.node_key_hash),m=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:p});this.cfg.onProgress?.({phase:"prune",done:f,total:f});let h=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(Ln,String(Date.now())),i&&await this.store.setMeta(_s,i),{nodes:t.length,edges:n.length,pruned:Fl(m.nodes_deleted),embeddings:h,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),s=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},o=(await this.store.allEmbeddings()).map(u=>Ns(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&s[u.node_key_hash]!==u.content_hash);if(o.length===0)return 0;let c=Un(o,jl),l=0;for(let u of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return o.length}async embedMeta(){let t=await this.store.getMeta(ft),n=await this.store.getMeta(pt),r=Cs(await this.store.getMeta(mt));if(!t||!n||!r)throw new ee("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let s=i?.error;throw new ee(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},jl=250;function Un(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}a(Un,"chunkArray");function Cs(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}a(Cs,"numOrNull");function Fl(e){return typeof e=="number"&&Number.isFinite(e)?e:0}a(Fl,"numOr0");var Os=".maind/code-index.sqlite";function gt(e){let t=e.dbPath??Kn.join(e.repoRoot,Os);Ul(Kn.dirname(t),{recursive:!0});let n=new $e(t),r=new Xe;return new Ae({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}a(gt,"createNodeCodeIndex");function Ds(e){let t=e.dbPath??Kn.join(e.repoRoot,Os),n=e.projectKey??Er(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 $e(t);return new Ie(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}a(Ds,"createCodeIndexSync");var Hn=process.env.MAIND_EMBEDDING_MODEL??"Xenova/bge-small-en-v1.5",Ms=Number(process.env.MAIND_EMBEDDING_DIM??384),Kl=process.env.MAIND_EMBEDDING_DTYPE??"q8",Bl="Represent this sentence for searching relevant passages: ";var Bn=null;async function Hl(){return Bn||(Bn=(async()=>{let e=await import("@huggingface/transformers"),t=process.env.MAIND_EMBEDDING_CACHE_DIR;return t&&(e.env.cacheDir=t),e.pipeline("feature-extraction",Hn,{dtype:Kl,device:"cpu"})})()),Bn}a(Hl,"getExtractor");function Ls(){let e={async embedDocuments(t){return t.length===0?[]:(await(await Hl())(t,{pooling:"cls",normalize:!0})).tolist().map(i=>Float32Array.from(i))},async embedQuery(t){let[n]=await e.embedDocuments([Bl+t]);return n}};return e}a(Ls,"createEmbedder");var yt=class{static{a(this,"NodeEmbedder")}dim=Ms;model=Hn;recipeVersion=qr;inner=Ls();embedDocuments(t){return this.inner.embedDocuments(t)}embedQuery(t){return this.inner.embedQuery(t)}};function Ps(){return new yt}a(Ps,"createNodeEmbedder");var Fs="MAIND_ORT_OK_FILE",Us="--_ort-worker",Zl=Ql(new URL("./index.js",import.meta.url));function Ks(e){return e.includes(Us)}a(Ks,"isOrtWorker");function Bs(e){let t=ql(js(Xl(),"maind-ort-")),n=js(t,"ok"),r=Gl(process.execPath,[Zl,...e,Us],{stdio:["ignore","inherit","inherit"],env:{...process.env,[Fs]:n}}),i=Vl(n);try{zl(Jl(n),{recursive:!0,force:!0})}catch{}return i?0:r.status&&r.status!==0?r.status:1}a(Bs,"runOrtIsolated");function Hs(){let e=process.env[Fs];if(e)try{Yl(e,"ok")}catch{}}a(Hs,"markOrtOk");function Wn(e,t){return e.includes(t)}a(Wn,"flag");function bt(e,t){let n=e.indexOf(t);if(!(n===-1||n+1>=e.length))return e[n+1]}a(bt,"value");function eu(e){if(e)return e;try{return Wl("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return process.cwd()}}a(eu,"resolveRoot");function Ne(e){return gt({repoRoot:e.root,dbPath:e.db??void 0,embedder:Ps()})}a(Ne,"openIndex");function Ws(e){return{root:eu(bt(e,"--root")),db:bt(e,"--db")??null,full:Wn(e,"--full"),embed:Wn(e,"--embed"),json:Wn(e,"--json")}}a(Ws,"baseOpts");function _t(e){return Ws(e)}a(_t,"parseIndexArgs");function Gn(e){let t=e.find(s=>!s.startsWith("--")),n=bt(e,"--limit"),r=n?Number.parseInt(n,10):15,i=bt(e,"--kind");return{...Ws(e),query:t??"",kind:i??null,limit:Number.isFinite(r)&&r>0?r:15}}a(Gn,"parseIndexSearchArgs");async function Gs(e){let t=Ne(e);try{let n=await t.indexRepository({full:e.full,embed:e.embed,onProgress:e.json?void 0:r=>{process.stderr.write(`\r ${r.done}/${r.total} ${r.path.slice(0,60)}`.padEnd(84))}});if(e.json)process.stdout.write(JSON.stringify(n)+`
123
130
  `);else{process.stderr.write("\r".padEnd(84)+"\r");let r=e.embed?`, ${(await t.status()).embeddingCount} embeddings`:"";process.stdout.write(` \u2713 ${n.filesParsed} parsed \xB7 ${n.filesSkipped} unchanged \xB7 ${n.filesDeleted} removed \u2192 ${n.nodeCount} symbols, ${n.edgeCount} edges (${n.durationMs}ms${n.incremental?", incremental":""}${r})
124
- `)}return Ni(),0}finally{await t.close()}}a(Ci,"runIndex");async function Mi(e){let t=be(e);try{let n=await t.status();if(e.json)return process.stdout.write(JSON.stringify(n)+`
131
+ `)}return Hs(),0}finally{await t.close()}}a(Gs,"runIndex");async function Vs(e){let t=Ne(e);try{let n=await t.status();if(e.json)return process.stdout.write(JSON.stringify(n)+`
125
132
  `),0;if(!n.indexed)return process.stdout.write(" not indexed \u2014 run `maind index` first.\n"),0;let r=Object.entries(n.languages).map(([s,o])=>`${s}:${o}`).join(" "),i=n.lastIndexedAt?new Date(n.lastIndexedAt).toISOString():"\u2014";return process.stdout.write(` ${n.fileCount} files \xB7 ${n.nodeCount} symbols \xB7 ${n.edgeCount} edges \xB7 ${n.embeddingCount} embeddings
126
133
  languages: ${r||"\u2014"}
127
134
  last indexed: ${i} (commit ${n.lastIndexCommit?.slice(0,8)??"\u2014"}, schema v${n.schemaVersion??"\u2014"})
128
- `),0}finally{await t.close()}}a(Mi,"runIndexStatus");async function Di(e){if(!e.query)return process.stderr.write(`maind: index-search needs a query. Usage: maind index-search <query> [--kind <k>] [--limit <n>]
129
- `),2;let t=be(e);try{let n=await t.searchGraph(e.query,{kind:e.kind??void 0,limit:e.limit});if(e.json)return process.stdout.write(JSON.stringify(n)+`
135
+ `),0}finally{await t.close()}}a(Vs,"runIndexStatus");async function qs(e){if(!e.query)return process.stderr.write(`maind: index-search needs a query. Usage: maind index-search <query> [--kind <k>] [--limit <n>]
136
+ `),2;let t=Ne(e);try{let n=await t.searchGraph(e.query,{kind:e.kind??void 0,limit:e.limit});if(e.json)return process.stdout.write(JSON.stringify(n)+`
130
137
  `),0;if(n.length===0)return process.stdout.write(` no matches.
131
138
  `),0;for(let r of n)process.stdout.write(` ${r.kind.padEnd(10)} ${r.qualifiedName} ${r.filePath}:${r.startLine}
132
- `);return 0}finally{await t.close()}}a(Di,"runIndexSearch");async function Pi(e){if(!e.query)return process.stderr.write(`maind: index-semantic needs a query. Usage: maind index-semantic <query> [--limit <n>]
133
- `),2;let t=be(e);try{let n=await t.semanticQuery(e.query,{limit:e.limit});if(e.json)process.stdout.write(JSON.stringify(n)+`
139
+ `);return 0}finally{await t.close()}}a(qs,"runIndexSearch");async function zs(e){if(!e.query)return process.stderr.write(`maind: index-semantic needs a query. Usage: maind index-semantic <query> [--limit <n>]
140
+ `),2;let t=Ne(e);try{let n=await t.semanticQuery(e.query,{limit:e.limit});if(e.json)process.stdout.write(JSON.stringify(n)+`
134
141
  `);else if(n.length===0)process.stdout.write(` no matches \u2014 did you build embeddings? Run 'maind index --embed' first.
135
142
  `);else for(let r of n)process.stdout.write(` ${(r.score??0).toFixed(3)} ${r.kind.padEnd(10)} ${r.qualifiedName} ${r.filePath}:${r.startLine}
136
- `);return Ni(),0}finally{await t.close()}}a(Pi,"runIndexSemantic");async function Li(e){let t=be(e);try{let n=await t.getArchitecture({topN:10});if(e.json)return process.stdout.write(JSON.stringify(n)+`
143
+ `);return Hs(),0}finally{await t.close()}}a(zs,"runIndexSemantic");async function Ys(e){let t=Ne(e);try{let n=await t.getArchitecture({topN:10});if(e.json)return process.stdout.write(JSON.stringify(n)+`
137
144
  `),0;let r=Object.entries(n.kindDistribution).map(([i,s])=>`${i}:${s}`).join(" ");process.stdout.write(` ${n.fileCount} files \xB7 ${n.nodeCount} symbols \xB7 ${n.edgeCount} edges
138
145
  kinds: ${r}
139
146
  most-imported modules:
140
147
  `);for(let i of n.topModules)process.stdout.write(` ${String(i.importsIn).padStart(4)} \u2190 ${i.filePath} (${i.symbolCount} symbols)
141
- `);return 0}finally{await t.close()}}a(Li,"runIndexArch");import{spawn as Lc,spawnSync as cs,execFileSync as jc}from"node:child_process";import{existsSync as Fc,mkdirSync as Uc,readFileSync as Kc,writeFileSync as Bc}from"node:fs";import{homedir as Hc}from"node:os";import{dirname as Wc,join as fn}from"node:path";function pc(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}a(pc,"getLineColFromPtr");function mc(e,t,n){let r=e.split(/\r\n|\n|\r/g),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let c=r[o-1];c&&(i+=o.toString().padEnd(s," "),i+=": ",i+=c,i+=`
148
+ `);return 0}finally{await t.close()}}a(Ys,"runIndexArch");import{spawn as Su,spawnSync as ko,execFileSync as Ru}from"node:child_process";import{existsSync as Au,mkdirSync as Tu,readFileSync as $u,writeFileSync as Iu}from"node:fs";import{homedir as Nu}from"node:os";import{dirname as Cu,join as ir}from"node:path";function tu(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}a(tu,"getLineColFromPtr");function nu(e,t,n){let r=e.split(/\r\n|\n|\r/g),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let c=r[o-1];c&&(i+=o.toString().padEnd(s," "),i+=": ",i+=c,i+=`
142
149
  `,o===t&&(i+=" ".repeat(s+n+2),i+=`^
143
- `))}return i}a(mc,"makeCodeBlock");var k=class extends Error{static{a(this,"TomlError")}line;column;codeblock;constructor(t,n){let[r,i]=pc(n.toml,n.ptr),s=mc(n.toml,r,i);super(`Invalid TOML document: ${t}
150
+ `))}return i}a(nu,"makeCodeBlock");var k=class extends Error{static{a(this,"TomlError")}line;column;codeblock;constructor(t,n){let[r,i]=tu(n.toml,n.ptr),s=nu(n.toml,r,i);super(`Invalid TOML document: ${t}
144
151
 
145
- ${s}`,n),this.line=r,this.column=i,this.codeblock=s}};function hc(e,t){let n=0;for(;e[t-++n]==="\\";);return--n&&n%2}a(hc,"isEscaped");function tt(e,t=0,n=e.length){let r=e.indexOf(`
146
- `,t);return e[r-1]==="\r"&&r--,r<=n?r:-1}a(tt,"indexOfNewline");function ae(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
152
+ ${s}`,n),this.line=r,this.column=i,this.codeblock=s}};function ru(e,t){let n=0;for(;e[t-++n]==="\\";);return--n&&n%2}a(ru,"isEscaped");function wt(e,t=0,n=e.length){let r=e.indexOf(`
153
+ `,t);return e[r-1]==="\r"&&r--,r<=n?r:-1}a(wt,"indexOfNewline");function pe(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
147
154
  `)return n;if(r==="\r"&&e[n+1]===`
148
- `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new k("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}a(ae,"skipComment");function C(e,t,n,r){let i;for(;;){for(;(i=e[t])===" "||i===" "||!n&&(i===`
155
+ `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new k("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}a(pe,"skipComment");function L(e,t,n,r){let i;for(;;){for(;(i=e[t])===" "||i===" "||!n&&(i===`
149
156
  `||i==="\r"&&e[t+1]===`
150
- `);)t++;if(r||i!=="#")break;t=ae(e,t)}return t}a(C,"skipVoid");function ji(e,t,n,r,i=!1){if(!r)return t=tt(e,t),t<0?e.length:t;for(let s=t;s<e.length;s++){let o=e[s];if(o==="#")s=tt(e,s);else{if(o===n)return s+1;if(o===r||i&&(o===`
157
+ `);)t++;if(r||i!=="#")break;t=pe(e,t)}return t}a(L,"skipVoid");function Xs(e,t,n,r,i=!1){if(!r)return t=wt(e,t),t<0?e.length:t;for(let s=t;s<e.length;s++){let o=e[s];if(o==="#")s=wt(e,s);else{if(o===n)return s+1;if(o===r||i&&(o===`
151
158
  `||o==="\r"&&e[s+1]===`
152
- `))return s}}throw new k("cannot find end of structure",{toml:e,ptr:t})}a(ji,"skipUntil");function nt(e,t){let n=e[t],r=n===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):n;t+=r.length-1;do t=e.indexOf(r,++t);while(t>-1&&n!=="'"&&hc(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}a(nt,"getStringEnd");var gc=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,_e=class e extends Date{static{a(this,"TomlDate")}#t=!1;#n=!1;#e=null;constructor(t){let n=!0,r=!0,i="Z";if(typeof t=="string"){let s=t.match(gc);s?(s[1]||(n=!1,t=`0000-01-01T${t}`),r=!!s[2],r&&t[10]===" "&&(t=t.replace(" ","T")),s[2]&&+s[2]>23?t="":(i=s[3]||null,t=t.toUpperCase(),!i&&r&&(t+="Z"))):t=""}super(t),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=i)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#e===null)return t.slice(0,-1);if(this.#e==="Z")return t;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(t,n="Z"){let r=new e(t);return r.#e=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#e=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#t=!1,n.#e=null,n}};var yc=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,bc=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,_c=/^[+-]?0[0-9_]/,wc=/^[0-9a-f]{2,8}$/i,Fi={b:"\b",t:" ",n:`
153
- `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function rt(e,t=0,n=e.length){let r=e[t]==="'",i=e[t++]===e[t]&&e[t]===e[t+1];i&&(n-=2,e[t+=2]==="\r"&&t++,e[t]===`
159
+ `))return s}}throw new k("cannot find end of structure",{toml:e,ptr:t})}a(Xs,"skipUntil");function kt(e,t){let n=e[t],r=n===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):n;t+=r.length-1;do t=e.indexOf(r,++t);while(t>-1&&n!=="'"&&ru(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}a(kt,"getStringEnd");var iu=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Ce=class e extends Date{static{a(this,"TomlDate")}#t=!1;#n=!1;#e=null;constructor(t){let n=!0,r=!0,i="Z";if(typeof t=="string"){let s=t.match(iu);s?(s[1]||(n=!1,t=`0000-01-01T${t}`),r=!!s[2],r&&t[10]===" "&&(t=t.replace(" ","T")),s[2]&&+s[2]>23?t="":(i=s[3]||null,t=t.toUpperCase(),!i&&r&&(t+="Z"))):t=""}super(t),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=i)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#e===null)return t.slice(0,-1);if(this.#e==="Z")return t;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(t,n="Z"){let r=new e(t);return r.#e=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#e=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#t=!1,n.#e=null,n}};var su=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,ou=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,au=/^[+-]?0[0-9_]/,cu=/^[0-9a-f]{2,8}$/i,Js={b:"\b",t:" ",n:`
160
+ `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function Et(e,t=0,n=e.length){let r=e[t]==="'",i=e[t++]===e[t]&&e[t]===e[t+1];i&&(n-=2,e[t+=2]==="\r"&&t++,e[t]===`
154
161
  `&&t++);let s=0,o,c="",l=t;for(;t<n-1;){let u=e[t++];if(u===`
155
162
  `||u==="\r"&&e[t]===`
156
- `){if(!i)throw new k("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(u<" "&&u!==" "||u==="\x7F")throw new k("control characters are not allowed in strings",{toml:e,ptr:t-1});if(o){if(o=!1,u==="x"||u==="u"||u==="U"){let d=e.slice(t,t+=u==="x"?2:u==="u"?4:8);if(!wc.test(d))throw new k("invalid unicode escape",{toml:e,ptr:s});try{c+=String.fromCodePoint(parseInt(d,16))}catch{throw new k("invalid unicode escape",{toml:e,ptr:s})}}else if(i&&(u===`
157
- `||u===" "||u===" "||u==="\r")){if(t=C(e,t-1,!0),e[t]!==`
158
- `&&e[t]!=="\r")throw new k("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:s});t=C(e,t)}else if(u in Fi)c+=Fi[u];else throw new k("unrecognized escape sequence",{toml:e,ptr:s});l=t}else!r&&u==="\\"&&(s=t-1,o=!0,c+=e.slice(l,s))}return c+e.slice(l,n-1)}a(rt,"parseString");function Ui(e,t,n,r){if(e==="true")return!0;if(e==="false")return!1;if(e==="-inf")return-1/0;if(e==="inf"||e==="+inf")return 1/0;if(e==="nan"||e==="+nan"||e==="-nan")return NaN;if(e==="-0")return r?0n:0;let i=yc.test(e);if(i||bc.test(e)){if(_c.test(e))throw new k("leading zeroes are not allowed",{toml:t,ptr:n});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new k("invalid number",{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(o))&&!r)throw new k("integer value cannot be represented losslessly",{toml:t,ptr:n});(i||r===!0)&&(o=BigInt(e))}return o}let s=new _e(e);if(!s.isValid())throw new k("invalid value",{toml:t,ptr:n});return s}a(Ui,"parseValue");function kc(e,t,n){let r=e.slice(t,n),i=r.indexOf("#");return i>-1&&(ae(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}a(kc,"sliceAndTrimEndOf");function we(e,t,n,r,i){if(r===0)throw new k("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let s=e[t];if(s==="["||s==="{"){let[l,u]=s==="["?Bi(e,t,r,i):Ki(e,t,r,i);if(n){if(u=C(e,u),e[u]===",")u++;else if(e[u]!==n)throw new k("expected comma or end of structure",{toml:e,ptr:u})}return[l,u]}let o;if(s==='"'||s==="'"){o=nt(e,t);let l=rt(e,t,o);if(n){if(o=C(e,o),e[o]&&e[o]!==","&&e[o]!==n&&e[o]!==`
159
- `&&e[o]!=="\r")throw new k("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",")}return[l,o]}o=ji(e,t,",",n);let c=kc(e,t,o-+(e[o-1]===","));if(!c[0])throw new k("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return n&&c[1]>-1&&(o=C(e,t+c[1]),o+=+(e[o]===",")),[Ui(c[0],e,t,i),o]}a(we,"extractValue");var xc=/^[a-zA-Z0-9-_]+[ \t]*$/;function it(e,t,n="="){let r=t-1,i=[],s=e.indexOf(n,t);if(s<0)throw new k("incomplete key-value: cannot find end of key",{toml:e,ptr:t});do{let o=e[t=++r];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===e[t+1]&&o===e[t+2])throw new k("multiline strings are not allowed in keys",{toml:e,ptr:t});let c=nt(e,t);if(c<0)throw new k("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",c);let l=e.slice(c,r<0||r>s?s:r),u=tt(l);if(u>-1)throw new k("newlines are not allowed in keys",{toml:e,ptr:t+r+u});if(l.trimStart())throw new k("found extra tokens after the string part",{toml:e,ptr:c});if(s<c&&(s=e.indexOf(n,c),s<0))throw new k("incomplete key-value: cannot find end of key",{toml:e,ptr:t});i.push(rt(e,t,c))}else{r=e.indexOf(".",t);let c=e.slice(t,r<0||r>s?s:r);if(!xc.test(c))throw new k("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});i.push(c.trimEnd())}}while(r+1&&r<s);return[i,C(e,s+1,!0,!0)]}a(it,"parseKey");function Ki(e,t,n,r){let i={},s=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new k("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=ae(e,t);else if(o!==" "&&o!==" "&&o!==`
160
- `&&o!=="\r"){let c,l=i,u=!1,[d,f]=it(e,t-1);for(let g=0;g<d.length;g++){if(g&&(l=u?l[c]:l[c]={}),c=d[g],(u=Object.hasOwn(l,c))&&(typeof l[c]!="object"||s.has(l[c])))throw new k("trying to redefine an already defined value",{toml:e,ptr:t});!u&&c==="__proto__"&&Object.defineProperty(l,c,{enumerable:!0,configurable:!0,writable:!0})}if(u)throw new k("trying to redefine an already defined value",{toml:e,ptr:t});let[p,h]=we(e,f,"}",n-1,r);s.add(p),l[c]=p,t=h}}if(!o)throw new k("unfinished table encountered",{toml:e,ptr:t});return[i,t]}a(Ki,"parseInlineTable");function Bi(e,t,n,r){let i=[],s;for(t++;(s=e[t++])!=="]"&&s;){if(s===",")throw new k("expected value, found comma",{toml:e,ptr:t-1});if(s==="#")t=ae(e,t);else if(s!==" "&&s!==" "&&s!==`
161
- `&&s!=="\r"){let o=we(e,t-1,"]",n-1,r);i.push(o[0]),t=o[1]}}if(!s)throw new k("unfinished array encountered",{toml:e,ptr:t});return[i,t]}a(Bi,"parseArray");function Hi(e,t,n,r){let i=t,s=n,o,c=!1,l;for(let u=0;u<e.length;u++){if(u){if(i=c?i[o]:i[o]={},s=(l=s[o]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let d=i.length-1;i=i[d],s=s[d].c}}if(o=e[u],(c=Object.hasOwn(i,o))&&s[o]?.t===0&&s[o]?.d)return null;c||(o==="__proto__"&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})),s[o]={t:u<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(l=s[o],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=!0,i[o]=[]),i[o].push(i={}),l.c[l.i++]=l={t:1,d:!1,i:0,c:{}}),l.d))return null;if(l.d=!0,r===1)i=c?i[o]:i[o]={};else if(r===0&&c)return null;return[o,i,l.c]}a(Hi,"peekTable");function st(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,o=i;for(let c=C(e,0);c<e.length;){if(e[c]==="["){let l=e[++c]==="[",u=it(e,c+=+l,"]");if(l){if(e[u[1]-1]!=="]")throw new k("expected end of table declaration",{toml:e,ptr:u[1]-1});u[1]++}let d=Hi(u[0],r,i,l?2:1);if(!d)throw new k("trying to redefine an already defined table or value",{toml:e,ptr:c});o=d[2],s=d[1],c=u[1]}else{let l=it(e,c),u=Hi(l[0],s,o,0);if(!u)throw new k("trying to redefine an already defined table or value",{toml:e,ptr:c});let d=we(e,l[1],void 0,t,n);u[1][u[0]]=d[0],c=d[1]}if(c=C(e,c,!0),e[c]&&e[c]!==`
162
- `&&e[c]!=="\r")throw new k("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:c});c=C(e,c)}return r}a(st,"parse");var Wi=/^[a-z0-9-_]+$/i;function ke(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return"array";if(e instanceof Date)return"date"}return t}a(ke,"extendedTypeOf");function Ec(e){for(let t=0;t<e.length;t++)if(ke(e[t])!=="object")return!1;return e.length!=0}a(Ec,"isArrayOfTables");function Zt(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}a(Zt,"formatString");function en(e,t,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(t==="number")return isNaN(e)?"nan":e===1/0?"inf":e===-1/0?"-inf":r&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t==="bigint"||t==="boolean")return e.toString();if(t==="string")return Zt(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return Sc(e,n,r);if(t==="array")return vc(e,n,r)}a(en,"stringifyValue");function Sc(e,t,n){let r=Object.keys(e);if(r.length===0)return"{}";let i="{ ";for(let s=0;s<r.length;s++){let o=r[s];s&&(i+=", "),i+=Wi.test(o)?o:Zt(o),i+=" = ",i+=en(e[o],ke(e[o]),t-1,n)}return i+" }"}a(Sc,"stringifyInlineTable");function vc(e,t,n){if(e.length===0)return"[]";let r="[ ";for(let i=0;i<e.length;i++){if(i&&(r+=", "),e[i]===null||e[i]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=en(e[i],ke(e[i]),t-1,n)}return r+" ]"}a(vc,"stringifyArray");function Rc(e,t,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="";for(let s=0;s<e.length;s++)i+=`${i&&`
163
+ `){if(!i)throw new k("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(u<" "&&u!==" "||u==="\x7F")throw new k("control characters are not allowed in strings",{toml:e,ptr:t-1});if(o){if(o=!1,u==="x"||u==="u"||u==="U"){let d=e.slice(t,t+=u==="x"?2:u==="u"?4:8);if(!cu.test(d))throw new k("invalid unicode escape",{toml:e,ptr:s});try{c+=String.fromCodePoint(parseInt(d,16))}catch{throw new k("invalid unicode escape",{toml:e,ptr:s})}}else if(i&&(u===`
164
+ `||u===" "||u===" "||u==="\r")){if(t=L(e,t-1,!0),e[t]!==`
165
+ `&&e[t]!=="\r")throw new k("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:s});t=L(e,t)}else if(u in Js)c+=Js[u];else throw new k("unrecognized escape sequence",{toml:e,ptr:s});l=t}else!r&&u==="\\"&&(s=t-1,o=!0,c+=e.slice(l,s))}return c+e.slice(l,n-1)}a(Et,"parseString");function Qs(e,t,n,r){if(e==="true")return!0;if(e==="false")return!1;if(e==="-inf")return-1/0;if(e==="inf"||e==="+inf")return 1/0;if(e==="nan"||e==="+nan"||e==="-nan")return NaN;if(e==="-0")return r?0n:0;let i=su.test(e);if(i||ou.test(e)){if(au.test(e))throw new k("leading zeroes are not allowed",{toml:t,ptr:n});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new k("invalid number",{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(o))&&!r)throw new k("integer value cannot be represented losslessly",{toml:t,ptr:n});(i||r===!0)&&(o=BigInt(e))}return o}let s=new Ce(e);if(!s.isValid())throw new k("invalid value",{toml:t,ptr:n});return s}a(Qs,"parseValue");function lu(e,t,n){let r=e.slice(t,n),i=r.indexOf("#");return i>-1&&(pe(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}a(lu,"sliceAndTrimEndOf");function Oe(e,t,n,r,i){if(r===0)throw new k("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let s=e[t];if(s==="["||s==="{"){let[l,u]=s==="["?eo(e,t,r,i):Zs(e,t,r,i);if(n){if(u=L(e,u),e[u]===",")u++;else if(e[u]!==n)throw new k("expected comma or end of structure",{toml:e,ptr:u})}return[l,u]}let o;if(s==='"'||s==="'"){o=kt(e,t);let l=Et(e,t,o);if(n){if(o=L(e,o),e[o]&&e[o]!==","&&e[o]!==n&&e[o]!==`
166
+ `&&e[o]!=="\r")throw new k("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",")}return[l,o]}o=Xs(e,t,",",n);let c=lu(e,t,o-+(e[o-1]===","));if(!c[0])throw new k("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return n&&c[1]>-1&&(o=L(e,t+c[1]),o+=+(e[o]===",")),[Qs(c[0],e,t,i),o]}a(Oe,"extractValue");var uu=/^[a-zA-Z0-9-_]+[ \t]*$/;function xt(e,t,n="="){let r=t-1,i=[],s=e.indexOf(n,t);if(s<0)throw new k("incomplete key-value: cannot find end of key",{toml:e,ptr:t});do{let o=e[t=++r];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===e[t+1]&&o===e[t+2])throw new k("multiline strings are not allowed in keys",{toml:e,ptr:t});let c=kt(e,t);if(c<0)throw new k("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",c);let l=e.slice(c,r<0||r>s?s:r),u=wt(l);if(u>-1)throw new k("newlines are not allowed in keys",{toml:e,ptr:t+r+u});if(l.trimStart())throw new k("found extra tokens after the string part",{toml:e,ptr:c});if(s<c&&(s=e.indexOf(n,c),s<0))throw new k("incomplete key-value: cannot find end of key",{toml:e,ptr:t});i.push(Et(e,t,c))}else{r=e.indexOf(".",t);let c=e.slice(t,r<0||r>s?s:r);if(!uu.test(c))throw new k("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});i.push(c.trimEnd())}}while(r+1&&r<s);return[i,L(e,s+1,!0,!0)]}a(xt,"parseKey");function Zs(e,t,n,r){let i={},s=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new k("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=pe(e,t);else if(o!==" "&&o!==" "&&o!==`
167
+ `&&o!=="\r"){let c,l=i,u=!1,[d,f]=xt(e,t-1);for(let h=0;h<d.length;h++){if(h&&(l=u?l[c]:l[c]={}),c=d[h],(u=Object.hasOwn(l,c))&&(typeof l[c]!="object"||s.has(l[c])))throw new k("trying to redefine an already defined value",{toml:e,ptr:t});!u&&c==="__proto__"&&Object.defineProperty(l,c,{enumerable:!0,configurable:!0,writable:!0})}if(u)throw new k("trying to redefine an already defined value",{toml:e,ptr:t});let[p,m]=Oe(e,f,"}",n-1,r);s.add(p),l[c]=p,t=m}}if(!o)throw new k("unfinished table encountered",{toml:e,ptr:t});return[i,t]}a(Zs,"parseInlineTable");function eo(e,t,n,r){let i=[],s;for(t++;(s=e[t++])!=="]"&&s;){if(s===",")throw new k("expected value, found comma",{toml:e,ptr:t-1});if(s==="#")t=pe(e,t);else if(s!==" "&&s!==" "&&s!==`
168
+ `&&s!=="\r"){let o=Oe(e,t-1,"]",n-1,r);i.push(o[0]),t=o[1]}}if(!s)throw new k("unfinished array encountered",{toml:e,ptr:t});return[i,t]}a(eo,"parseArray");function to(e,t,n,r){let i=t,s=n,o,c=!1,l;for(let u=0;u<e.length;u++){if(u){if(i=c?i[o]:i[o]={},s=(l=s[o]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let d=i.length-1;i=i[d],s=s[d].c}}if(o=e[u],(c=Object.hasOwn(i,o))&&s[o]?.t===0&&s[o]?.d)return null;c||(o==="__proto__"&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})),s[o]={t:u<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(l=s[o],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=!0,i[o]=[]),i[o].push(i={}),l.c[l.i++]=l={t:1,d:!1,i:0,c:{}}),l.d))return null;if(l.d=!0,r===1)i=c?i[o]:i[o]={};else if(r===0&&c)return null;return[o,i,l.c]}a(to,"peekTable");function vt(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,o=i;for(let c=L(e,0);c<e.length;){if(e[c]==="["){let l=e[++c]==="[",u=xt(e,c+=+l,"]");if(l){if(e[u[1]-1]!=="]")throw new k("expected end of table declaration",{toml:e,ptr:u[1]-1});u[1]++}let d=to(u[0],r,i,l?2:1);if(!d)throw new k("trying to redefine an already defined table or value",{toml:e,ptr:c});o=d[2],s=d[1],c=u[1]}else{let l=xt(e,c),u=to(l[0],s,o,0);if(!u)throw new k("trying to redefine an already defined table or value",{toml:e,ptr:c});let d=Oe(e,l[1],void 0,t,n);u[1][u[0]]=d[0],c=d[1]}if(c=L(e,c,!0),e[c]&&e[c]!==`
169
+ `&&e[c]!=="\r")throw new k("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:c});c=L(e,c)}return r}a(vt,"parse");var no=/^[a-z0-9-_]+$/i;function De(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return"array";if(e instanceof Date)return"date"}return t}a(De,"extendedTypeOf");function du(e){for(let t=0;t<e.length;t++)if(De(e[t])!=="object")return!1;return e.length!=0}a(du,"isArrayOfTables");function Vn(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}a(Vn,"formatString");function qn(e,t,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(t==="number")return isNaN(e)?"nan":e===1/0?"inf":e===-1/0?"-inf":r&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t==="bigint"||t==="boolean")return e.toString();if(t==="string")return Vn(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return fu(e,n,r);if(t==="array")return pu(e,n,r)}a(qn,"stringifyValue");function fu(e,t,n){let r=Object.keys(e);if(r.length===0)return"{}";let i="{ ";for(let s=0;s<r.length;s++){let o=r[s];s&&(i+=", "),i+=no.test(o)?o:Vn(o),i+=" = ",i+=qn(e[o],De(e[o]),t-1,n)}return i+" }"}a(fu,"stringifyInlineTable");function pu(e,t,n){if(e.length===0)return"[]";let r="[ ";for(let i=0;i<e.length;i++){if(i&&(r+=", "),e[i]===null||e[i]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=qn(e[i],De(e[i]),t-1,n)}return r+" ]"}a(pu,"stringifyArray");function mu(e,t,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="";for(let s=0;s<e.length;s++)i+=`${i&&`
163
170
  `}[[${t}]]
164
- `,i+=tn(0,e[s],t,n,r);return i}a(Rc,"stringifyArrayTable");function tn(e,t,n,r,i){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="",o="",c=Object.keys(t);for(let l=0;l<c.length;l++){let u=c[l];if(t[u]!==null&&t[u]!==void 0){let d=ke(t[u]);if(d==="symbol"||d==="function")throw new TypeError(`cannot serialize values of type '${d}'`);let f=Wi.test(u)?u:Zt(u);if(d==="array"&&Ec(t[u]))o+=(o&&`
165
- `)+Rc(t[u],n?`${n}.${f}`:f,r-1,i);else if(d==="object"){let p=n?`${n}.${f}`:f;o+=(o&&`
166
- `)+tn(p,t[u],p,r-1,i)}else s+=f,s+=" = ",s+=en(t[u],d,r,i),s+=`
171
+ `,i+=zn(0,e[s],t,n,r);return i}a(mu,"stringifyArrayTable");function zn(e,t,n,r,i){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="",o="",c=Object.keys(t);for(let l=0;l<c.length;l++){let u=c[l];if(t[u]!==null&&t[u]!==void 0){let d=De(t[u]);if(d==="symbol"||d==="function")throw new TypeError(`cannot serialize values of type '${d}'`);let f=no.test(u)?u:Vn(u);if(d==="array"&&du(t[u]))o+=(o&&`
172
+ `)+mu(t[u],n?`${n}.${f}`:f,r-1,i);else if(d==="object"){let p=n?`${n}.${f}`:f;o+=(o&&`
173
+ `)+zn(p,t[u],p,r-1,i)}else s+=f,s+=" = ",s+=qn(t[u],d,r,i),s+=`
167
174
  `}}return e&&(s||!o)&&(s=s?`[${e}]
168
175
  ${s}`:`[${e}]`),s&&o?`${s}
169
- ${o}`:s||o}a(tn,"stringifyTable");function nn(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(ke(e)!=="object")throw new TypeError("stringify can only be called with an object");let r=tn(0,e,"",t,n);return r[r.length-1]!==`
176
+ ${o}`:s||o}a(zn,"stringifyTable");function Yn(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(De(e)!=="object")throw new TypeError("stringify can only be called with an object");let r=zn(0,e,"",t,n);return r[r.length-1]!==`
170
177
  `?r+`
171
- `:r}a(nn,"stringify");var ot="switchyard",qi=["tool","install","--python","3.12","nemo-switchyard[cli]"],at='uv tool install --python 3.12 "nemo-switchyard[cli]"',Ac="https://docs.astral.sh/uv/getting-started/installation/",zi="switchyard",rn="switchyard-routes.toml",Tc=5e3,Yi="tmpl_switchyard_routes_default",$c="anthropic/claude-opus-5",Ic="anthropic/claude-haiku-4-5-20251001",Gi="openrouter/anthropic/claude-opus-5",Vi="openrouter/anthropic/claude-haiku-4-5",sn=["claude"],Nc=["codex","openclaw"];function Xi(e){return e==="claude"?{kind:"supported",agent:e}:e!==null&&Nc.includes(e)?{kind:"planned",agent:e}:{kind:"unknown",agent:e}}a(Xi,"classifyAgent");function Ji(e){let t=(e.ANTHROPIC_API_KEY??"").trim().length>0,n=(e.OPENROUTER_API_KEY??"").trim().length>0;return t?{kind:"anthropic",capableId:$c,efficientId:Ic,warning:null}:n?{kind:"openrouter",capableId:Gi,efficientId:Vi,warning:null}:{kind:"none",capableId:Gi,efficientId:Vi,warning:"no backend API key found (ANTHROPIC_API_KEY or OPENROUTER_API_KEY) \u2014 the proxy will start but upstream requests will fail until one is exported."}}a(Ji,"chooseBackend");var on="capable",an="efficient";function Oc(e,t){return["# Generated by `maind launch` (Agent Switchyard Phase 1, maind.dev \u2014 ADR-272).","# Regenerated on every launch; do not hand-edit. For a custom policy use","# `maind launch <agent> --config <path>`.","#",`# Routing policy: ${t==="curated"?"curated (MAIND content plane)":"builtin default"}`,"# \u2014 deterministic stage routing (NVIDIA NeMo Switchyard `stage_router`).","# effort low/medium -> efficient_target (fast tier)","# effort high/xhigh/max -> capable_target (strong tier)","# picker `efficient_first` + confidence_threshold 0.5: steady write progress","# keeps the efficient tier; corroborating error/exploration signals escalate","# to the capable tier.","#",`# Backend: ${e.kind==="none"?"openrouter (EXAMPLE \u2014 no API key detected)":e.kind}`,"# \u2014 detected locally from the environment, never from the policy source.","# API keys are read from the environment by the proxy at runtime \u2014 never","# stored in this file.",""].join(`
172
- `)}a(Oc,"policyHeader");function Cc(e){return{[e]:{type:"stage_router",capable_target:on,efficient_target:an,picker:"efficient_first",confidence_threshold:.5}}}a(Cc,"defaultRouteTable");function Qi(e,t,n=null){let r={targets:{[on]:{id:t.capableId},[an]:{id:t.efficientId}},routes:n??Cc(e)};return Oc(t,n?"curated":"builtin")+nn(r)+`
173
- `}a(Qi,"buildRoutesToml");function Zi(e,t){let n;try{n=st(e)}catch{return null}if(typeof n!="object"||n===null)return null;let r=n;if("targets"in r)return null;let i=r.routes;if(typeof i!="object"||i===null)return null;let s=i,o=s[t];if(typeof o!="object"||o===null)return null;for(let c of["capable_target","efficient_target"]){let l=o[c];if(l!==void 0&&l!==on&&l!==an)return null}return s}a(Zi,"acceptPolicyTemplate");function es(e,t){let n;try{n=st(e)}catch{return null}if(typeof n!="object"||n===null)return null;let r=n.routes;return typeof r!="object"||r===null||!(t in r)?null:e}a(es,"acceptRoutesToml");function cn(e,t,n,r){return[e,"launch",t,"--model",n,"--config",r]}a(cn,"buildSwitchyardArgv");function ln(e){return[e]}a(ln,"buildDirectArgv");var Mc={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15};function un(e,t){if(e!==null)return e;if(t!==null){let n=Mc[t];return n!==void 0?128+n:1}return 1}a(un,"exitCodeFromChild");function ts(e,t,n){return t!==null||e===0?"propagate":n<Tc?"fallback-eligible":"propagate"}a(ts,"classifyChildExit");function ns(){return`switchyard not found \u2014 installing via uv: ${at}`}a(ns,"buildInstallAnnouncement");function rs(){return`switchyard is not installed and \`uv\` is missing, so MAIND will not install it for you.
174
- maind: install uv (${Ac}), then run:
175
- maind: ${at}
176
- maind: and re-run \`maind launch claude\`. (Or launch without routing: \`maind launch claude --direct\`.)`}a(rs,"buildUvMissingMessage");function is(){return"switchyard still not reachable after install \u2014 uv's bin dir may be missing from PATH (try `uv tool update-shell`, then open a new terminal)."}a(is,"buildInstallStillMissingMessage");function ss(e){return["\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",` switchyard proxy unavailable: ${e}`," launching claude DIRECTLY \u2014 no model routing for this session."," (disable this fallback with --no-fallback)","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"].join(`
177
- `)}a(ss,"buildFallbackBanner");function os(){return"launching claude directly (--direct) \u2014 no switchyard proxy, no model routing."}a(os,"buildDirectBanner");function as(e,t){if(t){let r={agent:e.agent,config_path:e.configPath,config_source:e.configSource,toml:e.toml,argv:e.argv,backend:e.backendKind,switchyard_detected:e.switchyardDetected};return{stdout:JSON.stringify(r,null,2)+`
178
+ `:r}a(Yn,"stringify");var St="switchyard",so=["tool","install","--python","3.12","nemo-switchyard[cli]"],Rt='uv tool install --python 3.12 "nemo-switchyard[cli]"',hu="https://docs.astral.sh/uv/getting-started/installation/",oo="switchyard",Xn="switchyard-routes.toml",gu=5e3,ao="tmpl_switchyard_routes_default",yu="anthropic/claude-opus-5",bu="anthropic/claude-haiku-4-5-20251001",ro="openrouter/anthropic/claude-opus-5",io="openrouter/anthropic/claude-haiku-4-5",Jn=["claude"],_u=["codex","openclaw"];function co(e){return e==="claude"?{kind:"supported",agent:e}:e!==null&&_u.includes(e)?{kind:"planned",agent:e}:{kind:"unknown",agent:e}}a(co,"classifyAgent");function lo(e){let t=(e.ANTHROPIC_API_KEY??"").trim().length>0,n=(e.OPENROUTER_API_KEY??"").trim().length>0;return t?{kind:"anthropic",capableId:yu,efficientId:bu,warning:null}:n?{kind:"openrouter",capableId:ro,efficientId:io,warning:null}:{kind:"none",capableId:ro,efficientId:io,warning:"no backend API key found (ANTHROPIC_API_KEY or OPENROUTER_API_KEY) \u2014 the proxy will start but upstream requests will fail until one is exported."}}a(lo,"chooseBackend");var Qn="capable",Zn="efficient";function wu(e,t){return["# Generated by `maind launch` (Agent Switchyard Phase 1, maind.dev \u2014 ADR-272).","# Regenerated on every launch; do not hand-edit. For a custom policy use","# `maind launch <agent> --config <path>`.","#",`# Routing policy: ${t==="curated"?"curated (MAIND content plane)":"builtin default"}`,"# \u2014 deterministic stage routing (NVIDIA NeMo Switchyard `stage_router`).","# effort low/medium -> efficient_target (fast tier)","# effort high/xhigh/max -> capable_target (strong tier)","# picker `efficient_first` + confidence_threshold 0.5: steady write progress","# keeps the efficient tier; corroborating error/exploration signals escalate","# to the capable tier.","#",`# Backend: ${e.kind==="none"?"openrouter (EXAMPLE \u2014 no API key detected)":e.kind}`,"# \u2014 detected locally from the environment, never from the policy source.","# API keys are read from the environment by the proxy at runtime \u2014 never","# stored in this file.",""].join(`
179
+ `)}a(wu,"policyHeader");function ku(e){return{[e]:{type:"stage_router",capable_target:Qn,efficient_target:Zn,picker:"efficient_first",confidence_threshold:.5}}}a(ku,"defaultRouteTable");function uo(e,t,n=null){let r={targets:{[Qn]:{id:t.capableId},[Zn]:{id:t.efficientId}},routes:n??ku(e)};return wu(t,n?"curated":"builtin")+Yn(r)+`
180
+ `}a(uo,"buildRoutesToml");function fo(e,t){let n;try{n=vt(e)}catch{return null}if(typeof n!="object"||n===null)return null;let r=n;if("targets"in r)return null;let i=r.routes;if(typeof i!="object"||i===null)return null;let s=i,o=s[t];if(typeof o!="object"||o===null)return null;for(let c of["capable_target","efficient_target"]){let l=o[c];if(l!==void 0&&l!==Qn&&l!==Zn)return null}return s}a(fo,"acceptPolicyTemplate");function po(e,t){let n;try{n=vt(e)}catch{return null}if(typeof n!="object"||n===null)return null;let r=n.routes;return typeof r!="object"||r===null||!(t in r)?null:e}a(po,"acceptRoutesToml");function er(e,t,n,r){return[e,"launch",t,"--model",n,"--config",r]}a(er,"buildSwitchyardArgv");function tr(e){return[e]}a(tr,"buildDirectArgv");var Eu={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15};function nr(e,t){if(e!==null)return e;if(t!==null){let n=Eu[t];return n!==void 0?128+n:1}return 1}a(nr,"exitCodeFromChild");function mo(e,t,n){return t!==null||e===0?"propagate":n<gu?"fallback-eligible":"propagate"}a(mo,"classifyChildExit");function ho(){return`switchyard not found \u2014 installing via uv: ${Rt}`}a(ho,"buildInstallAnnouncement");function go(){return`switchyard is not installed and \`uv\` is missing, so MAIND will not install it for you.
181
+ maind: install uv (${hu}), then run:
182
+ maind: ${Rt}
183
+ maind: and re-run \`maind launch claude\`. (Or launch without routing: \`maind launch claude --direct\`.)`}a(go,"buildUvMissingMessage");function yo(){return"switchyard still not reachable after install \u2014 uv's bin dir may be missing from PATH (try `uv tool update-shell`, then open a new terminal)."}a(yo,"buildInstallStillMissingMessage");function bo(e){return["\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",` switchyard proxy unavailable: ${e}`," launching claude DIRECTLY \u2014 no model routing for this session."," (disable this fallback with --no-fallback)","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"].join(`
184
+ `)}a(bo,"buildFallbackBanner");function _o(){return"launching claude directly (--direct) \u2014 no switchyard proxy, no model routing."}a(_o,"buildDirectBanner");function wo(e,t){if(t){let r={agent:e.agent,config_path:e.configPath,config_source:e.configSource,toml:e.toml,argv:e.argv,backend:e.backendKind,switchyard_detected:e.switchyardDetected};return{stdout:JSON.stringify(r,null,2)+`
178
185
  `,stderr:""}}let n=["maind: dry-run \u2014 nothing installed, written, or spawned.",`maind: config ${e.configPath} (${e.configSource})`,`maind: switchyard detected: ${e.switchyardDetected?"yes":"no"}`,`maind: would run: ${e.argv.join(" ")}`].join(`
179
186
  `);return{stdout:e.toml??`(using existing config: ${e.configPath})
180
187
  `,stderr:n+`
181
- `}}a(as,"renderDryRun");import{createRequire as Dc}from"node:module";function Pc(){return"0.14.0";try{return Dc(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a(Pc,"resolveVersion");var H=Pc();var Gc=5e3;function O(e){process.stderr.write(`maind: ${e}
182
- `)}a(O,"err");function Vc(e){return e instanceof Error?e.message:String(e)}a(Vc,"msg");var qc=new Set(["--config","--route","--mcp-url"]);function ls(e){let t=a(i=>{let s=e.indexOf(i);if(!(s===-1||s+1>=e.length))return e[s+1]},"get"),n=a(i=>e.includes(i),"has"),r=null;for(let i=0;i<e.length;i++){let s=e[i];if(s.startsWith("-")){qc.has(s)&&i++;continue}r=s;break}return{agent:r,dryRun:n("--dry-run"),config:t("--config")??null,route:t("--route")??zi,direct:n("--direct"),noFallback:n("--no-fallback"),noInstall:n("--no-install"),json:n("--json"),mcpUrl:t("--mcp-url")??null}}a(ls,"parseLaunchArgs");var zc={probe(e,t){let n=cs(e,t,{stdio:["ignore","pipe","pipe"],encoding:"utf8",timeout:1e4}),r=n.status===0&&!n.error,i=typeof n.stdout=="string"?n.stdout.trim():"";return{ok:r,stdout:i.length>0?i:null}},install(e){return cs("uv",[...e],{stdio:["ignore","inherit","inherit"]}).status},spawnInteractive(e){let t=Date.now();return new Promise(n=>{let r=!1,i=Lc(e[0],e.slice(1),{stdio:"inherit",env:process.env}),s=a(()=>{},"onSigint"),o=a(d=>()=>{try{i.kill(d)}catch{}},"makeForward"),c=o("SIGTERM"),l=o("SIGHUP");process.on("SIGINT",s),process.on("SIGTERM",c),process.on("SIGHUP",l);let u=a(()=>{process.removeListener("SIGINT",s),process.removeListener("SIGTERM",c),process.removeListener("SIGHUP",l)},"cleanup");i.on("error",d=>{r||(r=!0,u(),n({code:null,signal:null,elapsedMs:Date.now()-t,spawnError:d.message}))}),i.on("exit",(d,f)=>{r||(r=!0,u(),n({code:d,signal:f,elapsedMs:Date.now()-t,spawnError:null}))})})},async fetchTemplate(e,t){let n;try{n=A()}catch(r){if(r instanceof R)return null;throw r}try{let r=new P({apiKey:n.apiKey,deviceId:n.deviceId,clientVersion:H,mcpUrl:e??void 0,projectKey:t}),i=new Promise(o=>{setTimeout(()=>o(null),Gc).unref()}),s=r.callTool("get_template",{template_id:Yi}).then(o=>typeof o.template_body=="string"&&o.template_body.trim().length>0?o.template_body:null).catch(()=>null);return await Promise.race([s,i])}catch{return null}},writeConfig(e,t){let n=Wc(e);n&&n!=="."&&Uc(n,{recursive:!0}),Bc(e,t,"utf8")},readFile(e){try{return Kc(e,"utf8")}catch{return null}},fileExists(e){return Fc(e)},repoRoot(){try{let e=jc("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return e.length>0?e:null}catch{return null}},projectKey(){return L().projectKey},userConfigDir(){return Se()},homeDir(){return Hc()},env:process.env,platform:process.platform};function Yc(e,t){return e!==null?fn(e,".maind",rn):fn(t,rn)}a(Yc,"resolveRoutesPath");async function us(e,t=zc){let n=Xi(e.agent);if(n.kind==="unknown")return O(`usage: maind launch <agent> [--dry-run] [--config <path>] [--route <name>] [--direct] [--no-fallback] [--no-install] \u2014 supported: ${sn.join(", ")}`),2;if(n.kind==="planned")return O(`agent '${n.agent}' is planned but not yet supported \u2014 v1 supports: ${sn.join(", ")}.`),2;if(e.json&&!e.dryRun)return O("--json is only valid together with --dry-run (stdout belongs to the agent session)."),2;let r=n.agent;if(e.direct)return O(os()),ds(t,ln(r));let i=Ji(t.env);i.warning!==null&&O(i.warning);let s,o,c;if(e.config!==null){if(!t.fileExists(e.config))return O(`config not found: ${e.config}`),2;let f=t.readFile(e.config);if(f===null||es(f,e.route)===null)return O(`config ${e.config} is not valid routes TOML with a [routes.${e.route}] entry.`),2;s=e.config,o=null,c="flag"}else{let f=await t.fetchTemplate(e.mcpUrl,t.projectKey()),p=f===null?null:Zi(f,e.route);if(o=Qi(e.route,i,p),p!==null)c="template";else{c="builtin";let h=f===null?"no curated template (offline, unauthenticated, or not published)":`curated template unusable (missing route '${e.route}', or it pins its own targets)`;O(`using builtin routing policy (${h}).`)}s=Yc(t.repoRoot(),t.userConfigDir())}let l=ot,u=t.probe(ot,["--version"]).ok;if(e.dryRun){let f={agent:r,configPath:s,configSource:c,toml:o,argv:cn(l,r,e.route,s),backendKind:i.kind,switchyardDetected:u},p=as(f,e.json);return p.stderr.length>0&&process.stderr.write(p.stderr),process.stdout.write(p.stdout),0}if(!u){if(e.noInstall)return O(`switchyard not found (--no-install). Install it with:
183
- maind: ${at}`),1;if(!t.probe("uv",["--version"]).ok)return O(rs()),1;if(O(ns()),t.install(qi),t.probe(ot,["--version"]).ok)u=!0;else{let f=fn(t.homeDir(),".local","bin",t.platform==="win32"?"switchyard.exe":"switchyard");t.probe(f,["--version"]).ok&&(l=f,u=!0)}if(!u)return dn(t,e,r,is())}if(c!=="flag"&&o!==null)try{t.writeConfig(s,o)}catch(f){return O(`could not write ${s}: ${Vc(f)}`),1}let d=await t.spawnInteractive(cn(l,r,e.route,s));return d.spawnError!==null?dn(t,e,r,`could not start switchyard (${d.spawnError})`):ts(d.code,d.signal,d.elapsedMs)==="fallback-eligible"?dn(t,e,r,`switchyard exited with code ${d.code} after ${(d.elapsedMs/1e3).toFixed(1)}s`):un(d.code,d.signal)}a(us,"runLaunch");async function dn(e,t,n,r){return t.noFallback?(O(`${r} (--no-fallback set \u2014 not degrading to a direct spawn).`),1):(process.stderr.write(ss(r)+`
184
- `),ds(e,ln(n)))}a(dn,"degradeOrFail");async function ds(e,t){let n=await e.spawnInteractive(t);return n.spawnError!==null?(O(`'${t[0]}' not found on PATH \u2014 install the agent CLI first (${n.spawnError}).`),1):un(n.code,n.signal)}a(ds,"spawnAndPropagate");import{execFileSync as fs}from"node:child_process";import{randomUUID as Xc}from"node:crypto";import{existsSync as Jc,readdirSync as Qc,readFileSync as Zc,realpathSync as el}from"node:fs";import{homedir as tl}from"node:os";import{join as ps}from"node:path";function ms(e,t){try{let n=fs("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();if(!n||n==="HEAD"){process.stderr.write(`maind: no branch to bind (detached HEAD) \u2014 skipped.
185
- `);return}fs("git",["config",`branch.${n}.maindObject`,e],{timeout:2e3,stdio:["ignore","ignore","ignore"]}),process.stderr.write(`maind: branch ${n} bound to ${t??e} \u2014 sessions on it announce the link automatically.
188
+ `}}a(wo,"renderDryRun");import{createRequire as xu}from"node:module";function vu(){return"0.16.0";try{return xu(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a(vu,"resolveVersion");var G=vu();var Ou=5e3;function M(e){process.stderr.write(`maind: ${e}
189
+ `)}a(M,"err");function Du(e){return e instanceof Error?e.message:String(e)}a(Du,"msg");var Mu=new Set(["--config","--route","--mcp-url"]);function Eo(e){let t=a(i=>{let s=e.indexOf(i);if(!(s===-1||s+1>=e.length))return e[s+1]},"get"),n=a(i=>e.includes(i),"has"),r=null;for(let i=0;i<e.length;i++){let s=e[i];if(s.startsWith("-")){Mu.has(s)&&i++;continue}r=s;break}return{agent:r,dryRun:n("--dry-run"),config:t("--config")??null,route:t("--route")??oo,direct:n("--direct"),noFallback:n("--no-fallback"),noInstall:n("--no-install"),json:n("--json"),mcpUrl:t("--mcp-url")??null}}a(Eo,"parseLaunchArgs");var Lu={probe(e,t){let n=ko(e,t,{stdio:["ignore","pipe","pipe"],encoding:"utf8",timeout:1e4}),r=n.status===0&&!n.error,i=typeof n.stdout=="string"?n.stdout.trim():"";return{ok:r,stdout:i.length>0?i:null}},install(e){return ko("uv",[...e],{stdio:["ignore","inherit","inherit"]}).status},spawnInteractive(e){let t=Date.now();return new Promise(n=>{let r=!1,i=Su(e[0],e.slice(1),{stdio:"inherit",env:process.env}),s=a(()=>{},"onSigint"),o=a(d=>()=>{try{i.kill(d)}catch{}},"makeForward"),c=o("SIGTERM"),l=o("SIGHUP");process.on("SIGINT",s),process.on("SIGTERM",c),process.on("SIGHUP",l);let u=a(()=>{process.removeListener("SIGINT",s),process.removeListener("SIGTERM",c),process.removeListener("SIGHUP",l)},"cleanup");i.on("error",d=>{r||(r=!0,u(),n({code:null,signal:null,elapsedMs:Date.now()-t,spawnError:d.message}))}),i.on("exit",(d,f)=>{r||(r=!0,u(),n({code:d,signal:f,elapsedMs:Date.now()-t,spawnError:null}))})})},async fetchTemplate(e,t){let n;try{n=I()}catch(r){if(r instanceof T)return null;throw r}try{let r=new P({apiKey:n.apiKey,deviceId:n.deviceId,clientVersion:G,mcpUrl:e??void 0,projectKey:t}),i=new Promise(o=>{setTimeout(()=>o(null),Ou).unref()}),s=r.callTool("get_template",{template_id:ao}).then(o=>typeof o.template_body=="string"&&o.template_body.trim().length>0?o.template_body:null).catch(()=>null);return await Promise.race([s,i])}catch{return null}},writeConfig(e,t){let n=Cu(e);n&&n!=="."&&Tu(n,{recursive:!0}),Iu(e,t,"utf8")},readFile(e){try{return $u(e,"utf8")}catch{return null}},fileExists(e){return Au(e)},repoRoot(){try{let e=Ru("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return e.length>0?e:null}catch{return null}},projectKey(){return j().projectKey},userConfigDir(){return je()},homeDir(){return Nu()},env:process.env,platform:process.platform};function Pu(e,t){return e!==null?ir(e,".maind",Xn):ir(t,Xn)}a(Pu,"resolveRoutesPath");async function xo(e,t=Lu){let n=co(e.agent);if(n.kind==="unknown")return M(`usage: maind launch <agent> [--dry-run] [--config <path>] [--route <name>] [--direct] [--no-fallback] [--no-install] \u2014 supported: ${Jn.join(", ")}`),2;if(n.kind==="planned")return M(`agent '${n.agent}' is planned but not yet supported \u2014 v1 supports: ${Jn.join(", ")}.`),2;if(e.json&&!e.dryRun)return M("--json is only valid together with --dry-run (stdout belongs to the agent session)."),2;let r=n.agent;if(e.direct)return M(_o()),vo(t,tr(r));let i=lo(t.env);i.warning!==null&&M(i.warning);let s,o,c;if(e.config!==null){if(!t.fileExists(e.config))return M(`config not found: ${e.config}`),2;let f=t.readFile(e.config);if(f===null||po(f,e.route)===null)return M(`config ${e.config} is not valid routes TOML with a [routes.${e.route}] entry.`),2;s=e.config,o=null,c="flag"}else{let f=await t.fetchTemplate(e.mcpUrl,t.projectKey()),p=f===null?null:fo(f,e.route);if(o=uo(e.route,i,p),p!==null)c="template";else{c="builtin";let m=f===null?"no curated template (offline, unauthenticated, or not published)":`curated template unusable (missing route '${e.route}', or it pins its own targets)`;M(`using builtin routing policy (${m}).`)}s=Pu(t.repoRoot(),t.userConfigDir())}let l=St,u=t.probe(St,["--version"]).ok;if(e.dryRun){let f={agent:r,configPath:s,configSource:c,toml:o,argv:er(l,r,e.route,s),backendKind:i.kind,switchyardDetected:u},p=wo(f,e.json);return p.stderr.length>0&&process.stderr.write(p.stderr),process.stdout.write(p.stdout),0}if(!u){if(e.noInstall)return M(`switchyard not found (--no-install). Install it with:
190
+ maind: ${Rt}`),1;if(!t.probe("uv",["--version"]).ok)return M(go()),1;if(M(ho()),t.install(so),t.probe(St,["--version"]).ok)u=!0;else{let f=ir(t.homeDir(),".local","bin",t.platform==="win32"?"switchyard.exe":"switchyard");t.probe(f,["--version"]).ok&&(l=f,u=!0)}if(!u)return rr(t,e,r,yo())}if(c!=="flag"&&o!==null)try{t.writeConfig(s,o)}catch(f){return M(`could not write ${s}: ${Du(f)}`),1}let d=await t.spawnInteractive(er(l,r,e.route,s));return d.spawnError!==null?rr(t,e,r,`could not start switchyard (${d.spawnError})`):mo(d.code,d.signal,d.elapsedMs)==="fallback-eligible"?rr(t,e,r,`switchyard exited with code ${d.code} after ${(d.elapsedMs/1e3).toFixed(1)}s`):nr(d.code,d.signal)}a(xo,"runLaunch");async function rr(e,t,n,r){return t.noFallback?(M(`${r} (--no-fallback set \u2014 not degrading to a direct spawn).`),1):(process.stderr.write(bo(r)+`
191
+ `),vo(e,tr(n)))}a(rr,"degradeOrFail");async function vo(e,t){let n=await e.spawnInteractive(t);return n.spawnError!==null?(M(`'${t[0]}' not found on PATH \u2014 install the agent CLI first (${n.spawnError}).`),1):nr(n.code,n.signal)}a(vo,"spawnAndPropagate");import{execFileSync as So}from"node:child_process";import{randomUUID as ju}from"node:crypto";import{existsSync as Fu,readdirSync as Uu,readFileSync as Ku,realpathSync as Bu}from"node:fs";import{homedir as Hu}from"node:os";import{join as Ro}from"node:path";function Ao(e,t){try{let n=So("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();if(!n||n==="HEAD"){process.stderr.write(`maind: no branch to bind (detached HEAD) \u2014 skipped.
192
+ `);return}So("git",["config",`branch.${n}.maindObject`,e],{timeout:2e3,stdio:["ignore","ignore","ignore"]}),process.stderr.write(`maind: branch ${n} bound to ${t??e} \u2014 sessions on it announce the link automatically.
186
193
  `)}catch{process.stderr.write(`maind: could not write the branch binding (git) \u2014 skipped.
187
- `)}}a(ms,"bindCurrentBranch");var pn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,nl=120*6e4,rl=10,il=`maind: usage:
194
+ `)}}a(Ao,"bindCurrentBranch");var sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Wu=120*6e4,Gu=10,Vu=`maind: usage:
188
195
  maind object create --title "<text>" [--parent <uuid>] [--anchor <repo-rel-path>]... [--json] [--session <uuid>]
189
196
  maind object link --object <uuid> --ref <ns:id> [--url <url>] [--session <uuid>]
190
197
  maind object report --event pr_opened|merge --ref <ns:id> [--occurred-on YYYY-MM-DD] [--session <uuid>]
191
198
  maind object anchor --object <uuid> --anchor <repo-rel-path>... [--session <uuid>] [--json]
192
199
  maind object bind --object <uuid> # tie the CURRENT branch to it
193
- `;function gs(e){let t=e[0];if(t!=="create"&&t!=="link"&&t!=="report"&&t!=="anchor"&&t!=="bind")return null;let n={sub:t,anchors:[]};for(let r=1;r<e.length;r++)switch(e[r]){case"--title":n.title=e[++r];break;case"--parent":n.parent=e[++r];break;case"--anchor":n.anchors.push(e[++r]??"");break;case"--object":n.object=e[++r];break;case"--ref":n.ref=e[++r];break;case"--url":n.url=e[++r];break;case"--event":{let s=e[++r];if(s!=="pr_opened"&&s!=="merge")return null;n.event=s;break}case"--occurred-on":n.occurredOn=e[++r];break;case"--session":n.session=e[++r];break;case"--bind-branch":n.bindBranch=!0;break;case"--json":n.json=!0;break;default:return null}return t==="create"&&!n.title||t==="link"&&(!n.object||!n.ref)||t==="report"&&(!n.event||!n.ref)||t==="anchor"&&(!n.object||n.anchors.length===0)||t==="bind"&&!n.object?null:n}a(gs,"parseObjectArgs");function sl(e){try{let t=ps(tl(),".maind","presence",e);if(!Jc(t))return null;let n=hs(process.cwd()),r=null;for(let i of Qc(t))if(i.endsWith(".json"))try{let s=JSON.parse(Zc(ps(t,i),"utf8")),o=Date.parse(s.written_at??"");if(typeof s.own_session_id!="string"||!pn.test(s.own_session_id)||Number.isNaN(o)||Date.now()-o>nl||typeof s.cwd!="string"||hs(s.cwd)!==n)continue;(r===null||o>r.at)&&(r={id:s.own_session_id,at:o})}catch{}return r?.id??null}catch{return null}}a(sl,"snapshotSessionId");function hs(e){try{return el(e)}catch{return e}}a(hs,"safeRealpath");async function ol(e,t,n){if(n&&pn.test(n))return{sessionId:n,source:"flag"};let r=process.env.MAIND_SESSION_ID?.trim().toLowerCase();if(r&&pn.test(r))return{sessionId:r,source:"env"};let i=sl(t);if(i)return{sessionId:i,source:"snapshot"};let s=Xc(),o=await e.callTool("announce_session",{project_key:t,session_id:s,focus:"cli:object",ttl_minutes:rl});return o.ok!==!0?(process.stderr.write(`maind: could not announce a session (${o.error??"unknown"}) \u2014 no live bridge session found for this cwd either.
200
+ `;function $o(e){let t=e[0];if(t!=="create"&&t!=="link"&&t!=="report"&&t!=="anchor"&&t!=="bind")return null;let n={sub:t,anchors:[]};for(let r=1;r<e.length;r++)switch(e[r]){case"--title":n.title=e[++r];break;case"--parent":n.parent=e[++r];break;case"--anchor":n.anchors.push(e[++r]??"");break;case"--object":n.object=e[++r];break;case"--ref":n.ref=e[++r];break;case"--url":n.url=e[++r];break;case"--event":{let s=e[++r];if(s!=="pr_opened"&&s!=="merge")return null;n.event=s;break}case"--occurred-on":n.occurredOn=e[++r];break;case"--session":n.session=e[++r];break;case"--bind-branch":n.bindBranch=!0;break;case"--json":n.json=!0;break;default:return null}return t==="create"&&!n.title||t==="link"&&(!n.object||!n.ref)||t==="report"&&(!n.event||!n.ref)||t==="anchor"&&(!n.object||n.anchors.length===0)||t==="bind"&&!n.object?null:n}a($o,"parseObjectArgs");function qu(e){try{let t=Ro(Hu(),".maind","presence",e);if(!Fu(t))return null;let n=To(process.cwd()),r=null;for(let i of Uu(t))if(i.endsWith(".json"))try{let s=JSON.parse(Ku(Ro(t,i),"utf8")),o=Date.parse(s.written_at??"");if(typeof s.own_session_id!="string"||!sr.test(s.own_session_id)||Number.isNaN(o)||Date.now()-o>Wu||typeof s.cwd!="string"||To(s.cwd)!==n)continue;(r===null||o>r.at)&&(r={id:s.own_session_id,at:o})}catch{}return r?.id??null}catch{return null}}a(qu,"snapshotSessionId");function To(e){try{return Bu(e)}catch{return e}}a(To,"safeRealpath");async function zu(e,t,n){if(n&&sr.test(n))return{sessionId:n,source:"flag"};let r=process.env.MAIND_SESSION_ID?.trim().toLowerCase();if(r&&sr.test(r))return{sessionId:r,source:"env"};let i=qu(t);if(i)return{sessionId:i,source:"snapshot"};let s=ju(),o=await e.callTool("announce_session",{project_key:t,session_id:s,focus:"cli:object",ttl_minutes:Gu});return o.ok!==!0?(process.stderr.write(`maind: could not announce a session (${o.error??"unknown"}) \u2014 no live bridge session found for this cwd either.
194
201
  Fallback: run the MCP calls from an agent session (work_object_create/link_ref/report_event).
195
- `),null):{sessionId:s,source:"announced"}}a(ol,"resolveSession");async function al(e,t,n){try{await e.callTool("announce_session",{project_key:t,session_id:n,status:"ended"})}catch{}}a(al,"endSession");async function ys(e){if(e===null)return process.stderr.write(il),2;let t=e.sub!=="create",n=a(c=>(process.stderr.write(`maind: object ${e.sub}: ${c}
196
- `),t?0:1),"fail");if(e.sub==="bind")return ms(e.object,null),0;let r;try{r=A()}catch(c){return n(c instanceof R?c.message:String(c))}let i=L().projectKey;if(!i)return n("not a git repo with a remote \u2014 no project_key.");let s=new P({apiKey:r.apiKey,deviceId:r.deviceId,clientVersion:H,projectKey:i}),o=null;try{if(o=await ol(s,i,e.session),o===null)return t?0:1;if(e.sub==="create"){let l=await s.callTool("work_object_create",{project_key:i,session_id:o.sessionId,kind:"issue",title:e.title,...e.parent?{parent_id:e.parent}:{},...e.anchors.length>0?{anchors:e.anchors.map(f=>({path_prefix:f}))}:{}}),u=l.object?.id;if(l.ok!==!0||typeof u!="string")return n(`server refused (${l.error??"no object id"})${l.hint?` \u2014 ${l.hint}`:""}`);let d=typeof l.object?.key=="string"?l.object.key:null;return process.stderr.write(`maind: object ${l.created===!1?"already existed":"created"}${d?`: ${d}`:""} (via ${o.source} session).
202
+ `),null):{sessionId:s,source:"announced"}}a(zu,"resolveSession");async function Yu(e,t,n){try{await e.callTool("announce_session",{project_key:t,session_id:n,status:"ended"})}catch{}}a(Yu,"endSession");async function Io(e){if(e===null)return process.stderr.write(Vu),2;let t=e.sub!=="create",n=a(c=>(process.stderr.write(`maind: object ${e.sub}: ${c}
203
+ `),t?0:1),"fail");if(e.sub==="bind")return Ao(e.object,null),0;let r;try{r=I()}catch(c){return n(c instanceof T?c.message:String(c))}let i=j().projectKey;if(!i)return n("not a git repo with a remote \u2014 no project_key.");let s=new P({apiKey:r.apiKey,deviceId:r.deviceId,clientVersion:G,projectKey:i}),o=null;try{if(o=await zu(s,i,e.session),o===null)return t?0:1;if(e.sub==="create"){let l=await s.callTool("work_object_create",{project_key:i,session_id:o.sessionId,kind:"issue",title:e.title,...e.parent?{parent_id:e.parent}:{},...e.anchors.length>0?{anchors:e.anchors.map(f=>({path_prefix:f}))}:{}}),u=l.object?.id;if(l.ok!==!0||typeof u!="string")return n(`server refused (${l.error??"no object id"})${l.hint?` \u2014 ${l.hint}`:""}`);let d=typeof l.object?.key=="string"?l.object.key:null;return process.stderr.write(`maind: object ${l.created===!1?"already existed":"created"}${d?`: ${d}`:""} (via ${o.source} session).
197
204
  `),e.json?process.stdout.write(JSON.stringify({ok:!0,id:u,key:d})+`
198
205
  `):process.stdout.write(u+`
199
- `),e.bindBranch&&ms(u,d),0}if(e.sub==="link"){let l=await s.callTool("work_object_link_ref",{project_key:i,session_id:o.sessionId,object_id:e.object,ref:e.ref,...e.url?{url:e.url}:{}});if(l.ok===!0||l.error==="ref_already_linked"){let u=typeof l.object?.key=="string"?l.object.key:null;return process.stderr.write(`maind: ref ${e.ref} ${l.error==="ref_already_linked"?"already linked":"linked"}${u?` to ${u}`:""}.
206
+ `),e.bindBranch&&Ao(u,d),0}if(e.sub==="link"){let l=await s.callTool("work_object_link_ref",{project_key:i,session_id:o.sessionId,object_id:e.object,ref:e.ref,...e.url?{url:e.url}:{}});if(l.ok===!0||l.error==="ref_already_linked"){let u=typeof l.object?.key=="string"?l.object.key:null;return process.stderr.write(`maind: ref ${e.ref} ${l.error==="ref_already_linked"?"already linked":"linked"}${u?` to ${u}`:""}.
200
207
  `),0}return n(`link failed (${l.error??"unknown"})${l.hint?` \u2014 ${l.hint}`:""}`)}if(e.sub==="anchor"){let l=await s.callTool("work_object_add_anchors",{project_key:i,session_id:o.sessionId,object_id:e.object,anchors:e.anchors.map(p=>({path_prefix:p}))});if(l.ok!==!0)return n(`anchor failed (${l.error??"unknown"})${l.hint?` \u2014 ${l.hint}`:""}`);let u=typeof l.object?.key=="string"?l.object.key:null,d=typeof l.anchors_added=="number"?l.anchors_added:0,f=typeof l.anchor_count=="number"?l.anchor_count:null;return process.stderr.write(d===0?`maind: anchors already present${u?` on ${u}`:""}.
201
208
  `:`maind: ${d} anchor(s) added${u?` to ${u}`:""}${f!==null?` (total ${f})`:""}.
202
209
  `),e.json&&process.stdout.write(JSON.stringify({ok:!0,anchors_added:d,anchor_count:f,id:typeof l.object?.id=="string"?l.object.id:e.object,key:u})+`
203
210
  `),0}let c=await s.callTool("work_object_report_event",{project_key:i,session_id:o.sessionId,event:e.event,ref:e.ref,...e.occurredOn?{occurred_on:e.occurredOn}:{}});return c.ok!==!0?n(`report failed (${c.error??"unknown"})${c.hint?` \u2014 ${c.hint}`:""}`):(process.stderr.write(`maind: ${e.event} reported for ${e.ref}.
204
- `),0)}catch(c){return n(c instanceof Error?c.message:String(c))}finally{o?.source==="announced"&&await al(s,i,o.sessionId)}}a(ys,"runObject");import{execFileSync as ll}from"node:child_process";import{mkdirSync as ul,writeFileSync as dl}from"node:fs";import{dirname as fl}from"node:path";var bs=["bg","text","border","border-x","border-y","border-t","border-r","border-b","border-l","divide","outline","ring","ring-offset","fill","stroke","accent","caret","decoration","placeholder","shadow","from","via","to"];var Um=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+bs.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");var mn="0.1.0";var Es="<!-- maind-review -->";var hn="maind review \xB7 deterministic, provenance-backed";function gn(e,t,n){let r=e.review;return{schema:"maind.review.manifest/v1",generated_at:n.generatedAt,key_prefix:n.keyPrefix,run_ref:n.runRef,base:n.base,diff_stats:n.diffStats,symbol_count:n.symbolCount,risk_flags:r?.risk_flags??[],findings:(r?.convention_findings??[]).map(i=>({convention_id:i.convention_id,version:i.convention_version,severity:i.severity,grade:i.grade,matched_symbol_count:i.matched_symbols.length,matched_changed_symbol_count:i.matched_changed_symbols?.length??0})),served:(r?.lesson_hints??[]).map(i=>({id:i.id,version:typeof i.version=="number"?i.version:null,tier:i.tier??null})),verdict:t?.ok===!0&&typeof t.verdict=="string"?{verdict:t.verdict,counts:{block:t.counts?.block??0,warn:t.counts?.warn??0,note:t.counts?.note??0},fail_on:n.failOn}:null,run:t?.ok===!0?t.run??null:null,...t?.ok===!0&&t.run_note?{run_note:t.run_note}:{},coverage_note:r?.coverage_note??null,regression_context:r?.regression_context??null}}a(gn,"buildReviewManifest");function cl(e){return`**[${e.severity}]**`}a(cl,"severityBadge");function Ss(e){let t=`\`${e.convention_id}@v${e.convention_version}\``,n=e.grade==="verdict"?" \xB7 verdict-grade":"",i=(e.matched_changed_symbols?.length??0)>0?`matched on changed symbols: ${xs(e.matched_changed_symbols??[])}`:`matched (co-located): ${xs(e.matched_symbols)}`,s=e.summary?.trim()?` \u2014 ${e.summary.trim()}`:"";return`- ${cl(e)} ${t}${s}${n}
205
- ${i}`}a(Ss,"findingLine");function xs(e,t=4){let n=e.slice(0,t).map(i=>`\`${i}\``),r=e.length-n.length;return n.join(", ")+(r>0?` (+${r} more)`:"")}a(xs,"formatSymbols");function vs(e){let t=e.counts??{};return`**Verdict: ${(e.verdict??"?").toUpperCase()}** (block: ${t.block??0} \xB7 warn: ${t.warn??0} \xB7 note: ${t.note??0})`}a(vs,"verdictLabel");function Rs(e){let t=e.run;if(t){let n=t.attestation_grade?"attestation-grade":"recorded, not attestation-grade";return`Attestation: run \`${t.id.slice(0,8)}\` (${n}) \xB7 commit \`${t.commit_sha.slice(0,12)}\` \xB7 input \`${t.input_hash.slice(0,12)}\` \xB7 policy \`${t.policy_hash.slice(0,12)}\``}return e.run_note?`Attestation: none \u2014 ${e.run_note}`:null}a(Rs,"attestationLine");function As(e){return e.base?`against \`${e.base}\``:"uncommitted work"}a(As,"baseLabel");function Ts(e,t,n){let r=e.review,i=r?.convention_findings??[],s=r?.lesson_hints??[],o=r?.risk_flags??[],c=[];if(c.push("<!-- Generated by `maind review` \u2014 do not edit by hand. -->"),c.push(`<!-- generated_at: ${n.generatedAt} | key: ${n.keyPrefix}${n.runRef?` | run: ${n.runRef}`:""} -->`),c.push(""),c.push("# maind review"),c.push(""),c.push(`Reviewed ${As(n)}: ${n.symbolCount} changed symbol(s) across ${n.diffStats?.changed_file_count??0} file(s) \xB7 findings: ${i.length} \xB7 risk flags: ${o.length} \xB7 lesson hints: ${s.length}`),c.push(""),t?.ok===!0&&t.verdict){c.push(vs(t));let u=Rs(t);u&&(c.push(""),c.push(u)),t.trust_note&&(c.push(""),c.push(`_${t.trust_note}_`)),c.push("")}if(i.length>0){c.push("## Convention findings"),c.push("");for(let u of i)c.push(Ss(u));c.push("")}else c.push("## Convention findings"),c.push(""),c.push("_No convention findings for this change set._"),c.push("");if(o.length>0){c.push("## Risk flags"),c.push(""),c.push("_Path heuristics from the local diff \u2014 informational, they never block._"),c.push("");for(let u of o)c.push(`- \`${u}\``);c.push("")}if(s.length>0){c.push("## Lesson hints"),c.push(""),c.push("_Semantic suggestions \u2014 advisory, never part of a verdict._"),c.push("");for(let u of s){let d=[`\`${u.id}\``];u.tier&&d.push(u.tier),u.match_reason&&d.push(u.match_reason),c.push(`- **${u.title}** (${d.join(" \xB7 ")})`)}c.push("")}let l=r?.regression_context;return l&&(l.hot_files??0)>0&&(c.push(""),c.push(`_History: ${l.hot_files}/${l.files_scanned??"?"} changed file(s) high-churn (max ${l.max_recent_commits??"?"} commits in the last ${l.window_commits??"?"}-commit window, ${l.distinct_authors??"?"} author(s))._`)),r?.coverage_note&&(c.push("## Coverage"),c.push(""),c.push(`> ${r.coverage_note}`),c.push("")),c.push("---"),c.push(hn),c.push(""),c.join(`
206
- `)}a(Ts,"renderReviewMarkdown");function $s(e,t,n,r){let i=e.review,s=i?.convention_findings??[],o=i?.risk_flags??[],c=i?.lesson_hints??[],l=[];if(l.push(Es),l.push("## maind review"),l.push(""),t?.ok===!0&&t.verdict){l.push(vs(t));let u=Rs(t);u&&l.push(u),l.push("")}if(s.length===0)l.push(`No convention findings for this change set (${n.symbolCount} changed symbol(s) reviewed ${As(n)}).`),l.push("");else{let u=s.slice(0,30);for(let d of u)l.push(Ss(d));s.length>u.length&&(l.push(""),l.push(`\u2026and ${s.length-u.length} more finding(s) \u2014 see the \`${r}\` build artifact.`)),l.push("")}return o.length>0&&(l.push(`**Risk flags:** ${o.map(u=>`\`${u}\``).join(" \xB7 ")} _(heuristics, never blocking)_`),l.push("")),c.length>0&&(l.push("**Related lessons:** "+c.map(u=>`\`${u.id}\``).join(" \xB7 ")),l.push("")),i?.coverage_note&&(l.push(`> ${i.coverage_note}`),l.push("")),l.push("---"),l.push(`_${hn}_`),l.push(""),l.join(`
207
- `)}a($s,"renderReviewComment");function Is(e,t){return["<!-- Generated by `maind review` (fail-open path). -->",`<!-- generated_at: ${e.generatedAt} -->`,"","# maind review","",`_maind review was unavailable for this run: ${t}_`,"","The build can proceed normally \u2014 this file is informational only.",""].join(`
208
- `)}a(Is,"renderFailOpenReview");function Ns(e,t){return[Es,"## maind review","",`_maind review was unavailable for this run: ${t}_`,"","---",`_${hn}_`,""].join(`
209
- `)}a(Ns,"renderFailOpenComment");var pl=/^[a-f0-9]{64}$/,ml=H,hl=".maind/review-comment.md",gl=64;function Ms(e){let t=a(c=>{let l=e.indexOf(c);if(!(l===-1||l+1>=e.length))return e[l+1]},"get"),n=a(c=>e.includes(c),"has"),r=null,i=e.indexOf("--comment");if(i!==-1){let c=e[i+1];r=c&&!c.startsWith("--")?c:hl}let s=t("--fail-on"),o=s==="block"||s==="warn"?s:null;return{base:t("--base")??null,uncommitted:n("--uncommitted"),summary:t("--summary")??null,json:n("--json"),out:t("--out")??".maind/review.md",comment:r,gate:n("--gate"),failOn:o,strict:n("--strict"),noReport:n("--no-report"),projectKey:t("--project-key")??null,mcpUrl:t("--mcp-url")??null,runRef:t("--run-ref")??process.env.GITHUB_RUN_ID??null,clientVersion:ml}}a(Ms,"parseReviewArgs");function yl(){return new Date().toISOString()}a(yl,"nowIso");function ce(e,t){let n=fl(e);n&&n!=="."&&ul(n,{recursive:!0}),dl(e,t,"utf8")}a(ce,"writeArtifact");function Ds(e){return e.endsWith(".md")?e.slice(0,-3)+".json":e+".json"}a(Ds,"manifestPathFor");function bl(e,t){return t==="block"?e==="block":e==="block"||e==="warn"}a(bl,"verdictCrossesFailOn");function _l(e){return{changed_file_count:e.changedFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,stale_file_count:e.staleFiles,truncated:e.truncated,hunk_coverage:e.hunkCoverage,base_kind:e.baseKind,...e.headSha?{head_sha:e.headSha}:{},dirty:e.dirty,...e.baseSha?{base_sha:e.baseSha}:{},code_index_version:mn}}a(_l,"buildDiffStats");function wl(){try{return ll("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}a(wl,"resolveRepoRoot");async function Ps(e){let t={generatedAt:yl(),keyPrefix:"unknown",runRef:e.runRef,base:e.base,mcpUrl:e.mcpUrl??process.env.MAIND_MCP_URL??"https://mcp.maind.dev/mcp",symbolCount:0,diffStats:null,gate:e.gate,failOn:e.gate?e.failOn:null};e.failOn&&!e.gate&&W("--fail-on has no effect without --gate (advisory runs always exit 0).");let n=a((r,i="infra")=>{let s=e.strict&&i==="infra";W(`review unavailable, ${s?"failing (--strict)":"continuing"}: ${r}`);try{ce(e.out,Is(t,r));let o=gn({},null,t);o.error=r,o.error_class=i,ce(Ds(e.out),JSON.stringify(o,null,2)+`
210
- `),e.comment&&ce(e.comment,Ns(t,r)),e.json&&process.stdout.write(JSON.stringify(o,null,2)+`
211
- `)}catch(o){return W(`could not write fail-open artifacts: ${ct(o)}`),e.strict?2:1}return s?2:0},"failOpen");try{let r=wl();if(!r)return n("not a git repository \u2014 review is diff-based.","expected");let i=Je({repoRoot:r}),s;try{let x=await i.status();if(!x.indexed||x.fileCount===0){W("no local index found \u2014 building it now (first run in this checkout)\u2026");let E=await i.indexRepository();W(`indexed ${E.filesParsed} file(s) in ${Math.round(E.durationMs/1e3)}s.`)}s=await i.reviewChanges({since:e.base??void 0,includeUncommitted:e.base?e.uncommitted:!0,limit:gl})}finally{await i.close().catch(()=>{})}let o=_l(s);t.diffStats=o,t.symbolCount=s.symbols.length;let c=e.summary?.trim()||void 0;if(s.symbols.length===0&&!c){let x=s.riskFlags,E={ok:!0,review:{convention_findings:[],lesson_hints:[],risk_flags:x,coverage_note:x.length>0?s.changedFiles===0?"No indexable changed files \u2014 the risk flags below come from non-indexable paths (migrations, workflows, manifests, env files), which the symbol index never sees.":"Changed files found but no indexed symbols \u2014 no symbol-level review. The risk flags below come from the raw path list; pass --summary for an index-less review.":s.changedFiles===0?"No changed files detected.":"Changed files found but no indexed symbols \u2014 nothing reviewable at symbol level."}};return Cs(E,null,t,e),process.stderr.write(`maind review: no reviewable symbols (${s.changedFiles} changed file(s), ${x.length} risk flag(s)) \u2192 ${e.out}
212
- `),0}let l=A();t.keyPrefix=l.keyPrefix;let u=e.projectKey?.trim().toLowerCase(),d=u&&pl.test(u)?u:L().projectKey,f=new P({apiKey:l.apiKey,deviceId:l.deviceId,clientVersion:e.clientVersion,mcpUrl:e.mcpUrl??void 0,projectKey:d}),p;try{p=St(await i.fileHistory({since:e.base??void 0,limit:1}))}catch{p=void 0}let h={changed_symbols:s.symbols.map(x=>({name:x.name,qualified_name:x.qualifiedName,kind:x.kind,language:x.language,change:x.change,changed_line_count:x.changedLineCount})),risk_flags:s.riskFlags,diff_stats:o,...p?{history:p}:{},...c?{change_summary:c}:{},...d?{project_key:d}:{}},g=await f.callTool("review_changes",h);if(g.ok!==!0||!g.review)return n(`review_changes rejected: ${g.error??"unknown_error"}${g.message?` \u2014 ${g.message}`:""}`,Os(g.error));let m=null;if(e.gate){let x=g.review.convention_findings??[],E=!e.noReport&&s.headSha?{commit_sha:s.headSha,...s.baseSha?{base_sha:s.baseSha}:{},dirty:s.dirty,diff_stats:o,code_index_version:mn}:{};try{if(m=await f.callTool("review_verdict",{findings:x.map(v=>({convention_id:v.convention_id,convention_version:v.convention_version,matched_symbols:v.matched_symbols,matched_changed_symbols:v.matched_changed_symbols??[]})),risk_flags:g.review.risk_flags??[],...d?{project_key:d}:{},...E}),m.ok!==!0)if(m.error==="requires_team"||m.error==="requires_enterprise")W("gate skipped: review_verdict is a Team-plan feature \u2014 findings below are advisory. "+(m.message??"Upgrade at https://maind.dev/pricing.")),m=null;else{let v=Os(m.error);if(e.strict&&v==="infra")return n(`review_verdict failed: ${m.error??"unknown_error"}${m.message?` \u2014 ${m.message}`:""}`,v);W(`gate unavailable (continuing advisory): ${m.error??"unknown_error"}`),m=null}}catch(v){if(e.strict)return n(`review_verdict failed: ${ct(v)}`,"infra");W(`gate unavailable (continuing advisory): ${ct(v)}`),m=null}}Cs(g,m,t,e);let b=g.review.convention_findings?.length??0,y=m?.run?` \xB7 run: ${m.run.id.slice(0,8)}${m.run.attestation_grade?" (attestation-grade)":""}`:m?.run_note?` \xB7 run: none (${m.run_note})`:"",w=m?.verdict?` \xB7 verdict: ${m.verdict}${y}`:"";return process.stderr.write(`maind review: ${b} finding(s), ${g.review.risk_flags?.length??0} risk flag(s)${w} \u2192 ${e.out}
213
- `),e.gate&&e.failOn&&m?.verdict&&bl(m.verdict,e.failOn)?(W(`verdict '${m.verdict}' crossed --fail-on ${e.failOn} \u2014 failing the check.`),1):0}catch(r){return r instanceof R?n(r.message,"expected"):n(ct(r),"infra")}}a(Ps,"runReview");var kl=new Set(["unauthorized","invalid_api_key","requires_team","requires_enterprise","scope_not_in_plan","rate_limited"]);function Os(e){return e&&kl.has(e)?"expected":"infra"}a(Os,"classifyServerError");function Cs(e,t,n,r){ce(r.out,Ts(e,t,n));let i=gn(e,t,n);ce(Ds(r.out),JSON.stringify(i,null,2)+`
214
- `),r.comment&&ce(r.comment,$s(e,t,n,r.out)),r.json&&process.stdout.write(JSON.stringify(i,null,2)+`
215
- `)}a(Cs,"writeAll");function ct(e){return e instanceof Error?e.message:String(e)}a(ct,"msg");function W(e){process.stderr.write(`maind review: ${e}
216
- `)}a(W,"warn");import{createReadStream as Sl,existsSync as vl}from"node:fs";import{createInterface as Rl}from"node:readline";var xl=new Set(["low","medium","high","xhigh","max"]),El=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;function lt(e){if(!e)return null;let t=null;for(let n of e.matchAll(El)){let r=n[1].toLowerCase();xl.has(r)&&(t=r)}return t}a(lt,"detectEffortLevel");var Ls="mcp__maind__",js="2026-08-16",Al=/(\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,Tl=/(\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,$l=/(\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,Il="[Request interrupted by user",Nl="The user doesn't want to proceed with this tool use",Ol="<synthetic>",Cl=.7,le={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};function xe(e){return typeof e=="number"&&Number.isFinite(e)?e:0}a(xe,"num");function Ml(e,t,n,r,i){let s=`${n?"s":"m"}:${t}`,o=e.get(s);if(!o){e.set(s,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}o.turns++,o.output_tokens+=r,i>0&&((o.first_ts===0||i<o.first_ts)&&(o.first_ts=i),i>o.last_ts&&(o.last_ts=i))}a(Ml,"bumpModel");function yn(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}a(yn,"asBlocks");function Dl(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
217
- `)}a(Dl,"textOf");function Pl(e,t){let n=a(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[s,o]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of s)o.has(l)&&c++;return c/s.size>=.8}a(Pl,"isRepeat");function Ll(e,t,n){return Al.test(e)?{polarity:-1,magnitude:le.rework,kind:"rework"}:n&&Tl.test(e)?{polarity:-1,magnitude:le.correction,kind:"correction"}:$l.test(e)?{polarity:1,magnitude:le.acceptance,kind:"acceptance"}:t!==null&&Pl(t,e)?{polarity:-1,magnitude:le.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}a(Ll,"classifyGenuine");function jl(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:js}}a(jl,"emptyAnalysis");async function bn(e){let t=jl("");if(!e||!vl(e))return t;let n=[],r=new Map,i=null,s=!1,o=null;await new Promise(f=>{let p=Sl(e,{encoding:"utf-8"}),h=Rl({input:p}),g=a(m=>{let b=m.trim();if(!b)return;let y;try{y=JSON.parse(b)}catch{return}if(t.lines_seen++,!t.session_id){let S=y.sessionId??y.session_id;typeof S=="string"&&S&&(t.session_id=S)}y.type==="ai-title"&&typeof y.aiTitle=="string"&&y.aiTitle&&(t.ai_title=y.aiTitle),typeof y.slug=="string"&&y.slug&&(t.session_slug=y.slug);let w=y.message?.role,x=y.isSidechain===!0,E=y.message?.usage;if(w==="assistant"&&E&&(t.input_tokens+=xe(E.input_tokens),t.output_tokens+=xe(E.output_tokens),t.cache_read_tokens+=xe(E.cache_read_input_tokens),t.cache_creation_tokens+=xe(E.cache_creation_input_tokens)),w==="assistant"&&typeof y.message?.model=="string"&&y.message.model&&y.message.model!==Ol){let S=y.timestamp?Date.parse(y.timestamp):Number.NaN;Ml(r,y.message.model,x,xe(E?.output_tokens),Number.isFinite(S)?S:0)}if(w==="assistant")for(let S of yn(y.message?.content)){if(S.type!=="tool_use"||typeof S.name!="string"||!S.name.startsWith(Ls))continue;let J=S.name.slice(Ls.length);J&&(t.maind_tool_calls[J]=(t.maind_tool_calls[J]??0)+1)}if(x)return;if(w==="assistant"){t.assistant_turns++;let S=yn(y.message?.content),J=!1;for(let kn of S)kn.type==="tool_use"&&(t.tool_calls++,J=!0,kn.name==="AskUserQuestion"&&t.agent_questions++);s=J;return}if(w!=="user")return;let v=yn(y.message?.content),$=Dl(v);if($.includes(Il)){t.interrupts++,n.push({polarity:-1,magnitude:le.interrupt,kind:"interrupt"});return}if(v.some(S=>S.type==="tool_result"&&S.is_error===!0&&typeof S.content=="string"&&S.content.includes(Nl))){t.tool_denials++,n.push({polarity:-1,magnitude:le.denial,kind:"denial"});return}if(v.some(S=>S.type==="tool_result")||!$.trim())return;t.user_turns++,t.user_chars+=$.length;let I=lt($);I&&(i=I);let D=Ll($,o,s);o=$,D.kind==="correction"?t.corrections++:D.kind==="rework"?t.reworks++:D.kind==="repeat"?t.repeated_instructions++:D.kind==="acceptance"&&t.acceptances++,D.polarity!==0&&n.push(D),s=!1},"processLine");h.on("line",m=>{try{g(m)}catch{}}),h.on("close",()=>f()),h.on("error",()=>f()),p.on("error",()=>f())}),t.effort_at_end=i,t.model_mix=[...r.values()].sort((f,p)=>f.first_ts-p.first_ts||f.model.localeCompare(p.model)),t.user_token_estimate=Math.round(t.user_chars/4);let c=t.user_token_estimate+t.output_tokens;t.human_share=c>0?Number((t.user_token_estimate/c).toFixed(4)):0;let l=0,u=0,d=[];return n.forEach((f,p)=>{f.polarity>0?t.reactions_pos++:f.polarity<0&&t.reactions_neg++,l=l*Cl+f.polarity*f.magnitude;let h=Number(l.toFixed(3));d.push({t:p,value:h,...f.kind!=="neutral"?{kind:f.kind}:{}}),u+=h,p>0&&n[p-1].polarity<0&&f.polarity>0&&t.recovery_events++}),t.net_sentiment=t.reactions_pos-t.reactions_neg,t.momentum_series=d,t.momentum_final=d.length?d[d.length-1].value:0,t.momentum_auc=Number(u.toFixed(3)),t.ended_positive=t.momentum_final>0,Object.keys(t.maind_tool_calls).length>0&&(t.maind_connected="connected"),t}a(bn,"analyzeSession");function Fs(e,t,n,r="unknown"){let i={session_analytics:{...e,ingest_source:r}};return t&&t.started_at&&(i.session_span=n?{...t,...n}:t),i}a(Fs,"ingestBody");function Us(e){let t={"content-type":"application/json",authorization:`Bearer ${e.apiKey}`};return e.deviceId&&(t["x-maind-device-id"]=e.deviceId),t}a(Us,"ingestHeaders");async function _n(e,t,n,r,i="unknown"){try{let s=await fetch(e.endpoint,{method:"POST",headers:Us(e),body:JSON.stringify(Fs(t,n,r,i))});if(!s.ok){let c=await s.text().catch(()=>"");return{ok:!1,inserted:0,status:s.status,error:c.slice(0,500)}}let o=await s.json().catch(()=>null);return{ok:!0,inserted:o?.analytics_stored?1:0,spanStored:o?.span_stored===!0,status:s.status}}catch(s){return{ok:!1,inserted:0,error:s instanceof Error?s.message:String(s)}}}a(_n,"postSessionAnalytics");import{readdir as Ks,stat as Fl}from"node:fs/promises";import{homedir as Ul}from"node:os";import{join as ut}from"node:path";var Kl=Ul(),Bs=ut(Kl,".claude","projects");function Hs(e){return e.startsWith("-")?e.replace(/-/g,"/"):e}a(Hs,"cwdFromProjectDir");async function wn(e=Bs){let t;try{t=await Ks(e)}catch{return[]}let n=[];for(let r of t){if(!r.startsWith("-"))continue;let i=ut(e,r),s;try{s=await Ks(i)}catch{continue}let o=s.filter(l=>l.endsWith(".jsonl"));if(o.length===0)continue;let c=0;for(let l of o)try{let u=await Fl(ut(i,l));u.mtimeMs>c&&(c=u.mtimeMs)}catch{}n.push({encodedDir:r,cwd:Hs(r),transcripts:o.map(l=>ut(i,l)),mtimeMs:c})}return n.sort((r,i)=>i.mtimeMs-r.mtimeMs),n.map(({mtimeMs:r,...i})=>i)}a(wn,"listProjects");var Bl="https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest",Hl=120;function dt(e){process.stderr.write(`maind: ${e}
218
- `)}a(dt,"err");function U(e){process.stdout.write(e+`
219
- `)}a(U,"out");function Ws(e){let t={dryRun:!1,since:null,json:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--dry-run")t.dryRun=!0;else if(r==="--json")t.json=!0;else if(r==="--since"){let i=e[++n],s=i?Date.parse(i):Number.NaN;Number.isFinite(s)?t.since=s:dt(`ignoring unparseable --since '${i??""}' (expected YYYY-MM-DD)`)}}return t}a(Ws,"parseSessionsArgs");function Wl(){let e=process.env.MAIND_INGEST_URL?.trim();return e&&e.length>0?e:Bl}a(Wl,"endpoint");var Gl=a(e=>new Promise(t=>setTimeout(t,e)),"sleep");async function Gs(e){let t;try{t=A()}catch(l){if(l instanceof R)return dt(l.message),1;throw l}let r=(await wn()).flatMap(l=>l.transcripts);if(r.length===0)return dt("no Claude Code transcripts found under ~/.claude/projects."),0;let i=Wl(),s=[],o=0,c=0;for(let l of r){let u=await bn(l);if(!u.session_id){o++;continue}if(e.since!==null){let p=u.model_mix.reduce((h,g)=>Math.max(h,g.last_ts),0);if(p>0&&p<e.since){o++;continue}}let d=u.model_mix.filter(p=>!p.sidechain),f={session_id:u.session_id,title:u.ai_title,models:d.map(p=>`${p.model}\xD7${p.turns}`).join(", ")||"\u2014",turns:u.assistant_turns,lines:u.lines_seen,posted:!1};if(!e.dryRun){let p=await _n({endpoint:i,apiKey:t.apiKey,deviceId:t.deviceId},u,null,void 0,"backfill");f.posted=p.ok,p.ok||(c++,f.error=p.error??`status ${p.status??"?"}`),await Gl(Hl)}s.push(f)}if(e.json)return U(JSON.stringify({ok:c===0,dry_run:e.dryRun,skipped:o,failed:c,sessions:s},null,2)),c===0?0:1;U(e.dryRun?`Would upload ${s.length} session(s) to ${i}:`:`Uploaded ${s.length-c}/${s.length} session(s) to ${i}:`),U("");for(let l of s){let u=e.dryRun?" ":l.posted?"\u2713":"\u2717";U(`${u} ${l.session_id.slice(0,8)} ${String(l.turns).padStart(4)} turns ${l.models}`),U(` title: ${l.title??"\u2014"}`),l.error&&U(` error: ${l.error}`)}return U(""),o>0&&U(`${o} transcript(s) skipped (no session id, or older than --since).`),e.dryRun&&(U("Dry run \u2014 nothing was uploaded."),U("Note: a real run uploads the session TITLES listed above (content-derived) for every project on this machine. They are only stored if you enabled 'Session titles' in the consent center; without it the numbers land and the titles are dropped.")),c>0&&dt(`${c} session(s) failed \u2014 re-running is safe, the server upserts.`),c===0?0:1}a(Gs,"runSessionsBackfill");import{execFileSync as Vl}from"node:child_process";var ql="2026-07-05",zl="https://app.maind.dev";function Ee(e){process.stderr.write(`maind: ${e}
220
- `)}a(Ee,"err");function Yl(){try{return Vl("git",["rev-parse","--show-toplevel"],{encoding:"utf8"}).trim()}catch{return process.cwd()}}a(Yl,"repoRoot");function Xl(){let e=process.env.MAIND_DASHBOARD_URL?.trim();return(e&&e.length>0?e:zl).replace(/\/+$/,"")}a(Xl,"dashboardUrl");function Jl(e){let t;try{t=A()}catch(n){if(n instanceof R)return Ee(n.message),null;throw n}try{return xi({repoRoot:Yl(),endpoint:Xl(),apiKey:t.apiKey,deviceId:t.deviceId,onProgress:e?void 0:n=>process.stderr.write(` ${n.phase}: ${n.done}/${n.total}\r`)})}catch(n){return Ee(n instanceof Error?n.message:String(n)),null}}a(Jl,"makeSync");function Ql(e){return e instanceof Error?e.message:String(e)}a(Ql,"msg");function Vs(e){let t=e.find(r=>!r.startsWith("-"));return{sub:t==="status"||t==="enable"||t==="disable"?t:"push",json:e.includes("--json")}}a(Vs,"parseSyncArgs");async function qs(e){let t=Jl(e.json);if(!t)return 1;try{switch(e.sub){case"enable":return await Zl(t);case"disable":return await eu(t);case"status":return await tu(t,e.json);default:return await nu(t,e.json)}}catch(n){return n instanceof X&&n.code==="consent_required"?(Ee("codebase cloud-sync is not enabled \u2014 run `maind sync enable` first."),1):(Ee(`sync failed: ${Ql(n)}`),1)}finally{await t.close().catch(()=>{})}}a(qs,"runSync");async function Zl(e){return await e.setConsent(!0,ql),process.stdout.write("codebase cloud-sync enabled. Structured rows (symbol names, topology, hashes) will be pushed on `maind sync` \u2014 never source, snippets, or plaintext paths.\n"),0}a(Zl,"enable");async function eu(e){return await e.setConsent(!1),process.stdout.write(`codebase cloud-sync disabled.
221
- `),0}a(eu,"disable");async function tu(e,t){let n=await e.localStatus(),r=await e.remoteStatus();return t?(process.stdout.write(JSON.stringify({ok:!0,local:n,remote:r},null,2)+`
211
+ `),0)}catch(c){return n(c instanceof Error?c.message:String(c))}finally{o?.source==="announced"&&await Yu(s,i,o.sessionId)}}a(Io,"runObject");import{execFileSync as td}from"node:child_process";import{mkdirSync as nd,writeFileSync as rd}from"node:fs";import{dirname as id}from"node:path";var or="0.1.0";var Co="<!-- maind-review -->";var ar="maind review \xB7 deterministic, provenance-backed";function cr(e,t,n){let r=e.review;return{schema:"maind.review.manifest/v1",generated_at:n.generatedAt,key_prefix:n.keyPrefix,run_ref:n.runRef,base:n.base,diff_stats:n.diffStats,symbol_count:n.symbolCount,risk_flags:r?.risk_flags??[],findings:(r?.convention_findings??[]).map(i=>({convention_id:i.convention_id,version:i.convention_version,severity:i.severity,grade:i.grade,matched_symbol_count:i.matched_symbols.length,matched_changed_symbol_count:i.matched_changed_symbols?.length??0})),served:(r?.lesson_hints??[]).map(i=>({id:i.id,version:typeof i.version=="number"?i.version:null,tier:i.tier??null})),verdict:t?.ok===!0&&typeof t.verdict=="string"?{verdict:t.verdict,counts:{block:t.counts?.block??0,warn:t.counts?.warn??0,note:t.counts?.note??0},fail_on:n.failOn}:null,run:t?.ok===!0?t.run??null:null,...t?.ok===!0&&t.run_note?{run_note:t.run_note}:{},coverage_note:r?.coverage_note??null,regression_context:r?.regression_context??null,...n.detectors?{detectors:Xu(n.detectors,t,n.detectorsAcknowledged)}:{}}}a(cr,"buildReviewManifest");function At(e){return`${e.detector_id}|${e.rule_id}|${e.evidence_hash}`}a(At,"detectorKey");function lr(e){let t=new Map;for(let n of e?.detector_findings??[])t.set(At(n),n);return t}a(lr,"detectorActions");function Xu(e,t,n){let r=lr(t);return{coverage:e.coverage,server_acknowledged:n,truncated:e.truncated,engines:e.engines.map(i=>({detector_id:i.detector_id,detector_version:i.detector_version,state:i.state,finding_count:i.finding_count})),findings:e.findings.map(i=>{let s=r.get(At(i));return{...i,...s?.status?{status:s.status}:{},...s?.action?{action:s.action}:{},...s?.downgrade_reason?{downgrade_reason:s.downgrade_reason}:{}}})}}a(Xu,"buildManifestDetectors");function Tt(e){let t=0,n=0,r=0;for(let i of e.findings)i.baseline!=="introduced"?r+=i.count:i.level==="open"?t+=i.count:n+=i.count;return{blockEligible:t,advisory:n,preExisting:r}}a(Tt,"detectorCounts");var Ju="Detector section not acknowledged by the server (< 0.48.0) \u2014 this run was recorded as format 1, without detector findings.";function Qu(e,t){let n=e.detectors;if(!n)return[];let r=lr(t),{blockEligible:i,advisory:s,preExisting:o}=Tt(n),c=["## Detectors",""];c.push(`Coverage: **${n.coverage}** \xB7 ${i} block-eligible \xB7 ${s} advisory \xB7 ${o} pre-existing`+(n.truncated>0?` \xB7 ${n.truncated} wire row(s) truncated`:"")),c.push(""),c.push("_Repo-health detectors (ADR-324): only evidence hashes leave the machine; the plain text below is local._"),e.detectorsAcknowledged===!1&&(c.push(""),c.push(`> ${Ju}`)),c.push("");for(let d of n.engines){let f=d.state==="ran"?`${d.finding_count} finding(s)`:d.state.replace("_"," ")+(d.reason?` \u2014 ${d.reason}`:"");c.push(`- \`${d.detector_id}@${d.detector_version}\` \xB7 ${f}`)}let l=n.local.filter(d=>d.baseline==="introduced");if(l.length>0){c.push("");for(let d of l){let f=r.get(At(d)),p=f?.action?` \u2192 **${f.action}**${f.downgrade_reason?` (${f.downgrade_reason})`:""}`:"";c.push(`- \`${d.rule_id}\` [${d.level} \xB7 ${d.baseline}] ${d.title}${p}`)}}let u=new Map;for(let d of n.local)d.baseline==="pre_existing"&&u.set(d.rule_id,(u.get(d.rule_id)??0)+1);if(u.size>0){c.push("");for(let[d,f]of u)c.push(`- \`${d}\` \xB7 ${f} pre-existing (inventory, not introduced by this change)`)}return c.push(""),c}a(Qu,"detectorsSection");function Zu(e,t){let n=e.detectors;if(!n)return[];let r=lr(t),{blockEligible:i,advisory:s,preExisting:o}=Tt(n),c=[`**Detectors:** coverage ${n.coverage} \xB7 ${i} block-eligible \xB7 ${s} advisory \xB7 ${o} pre-existing`+(e.detectorsAcknowledged===!1?" _(not acknowledged by server \u2014 recorded as format 1)_":"")];for(let l of n.findings)r.get(At(l))?.action==="block"&&c.push(`- **[block]** \`${l.rule_id}\` (${l.detector_id}@${l.detector_version}, \xD7${l.count})`);return c.push(""),c}a(Zu,"detectorsCommentLines");function ed(e){return`**[${e.severity}]**`}a(ed,"severityBadge");function Oo(e){let t=`\`${e.convention_id}@v${e.convention_version}\``,n=e.grade==="verdict"?" \xB7 verdict-grade":"",i=(e.matched_changed_symbols?.length??0)>0?`matched on changed symbols: ${No(e.matched_changed_symbols??[])}`:`matched (co-located): ${No(e.matched_symbols)}`,s=e.summary?.trim()?` \u2014 ${e.summary.trim()}`:"";return`- ${ed(e)} ${t}${s}${n}
212
+ ${i}`}a(Oo,"findingLine");function No(e,t=4){let n=e.slice(0,t).map(i=>`\`${i}\``),r=e.length-n.length;return n.join(", ")+(r>0?` (+${r} more)`:"")}a(No,"formatSymbols");function Do(e){let t=e.counts??{};return`**Verdict: ${(e.verdict??"?").toUpperCase()}** (block: ${t.block??0} \xB7 warn: ${t.warn??0} \xB7 note: ${t.note??0})`}a(Do,"verdictLabel");function Mo(e){let t=e.run;if(t){let n=t.attestation_grade?"attestation-grade":"recorded, not attestation-grade",r=typeof t.attestation_format=="number"?` \xB7 format ${t.attestation_format}`:"";return`Attestation: run \`${t.id.slice(0,8)}\` (${n}) \xB7 commit \`${t.commit_sha.slice(0,12)}\` \xB7 input \`${t.input_hash.slice(0,12)}\` \xB7 policy \`${t.policy_hash.slice(0,12)}\`${r}`}return e.run_note?`Attestation: none \u2014 ${e.run_note}`:null}a(Mo,"attestationLine");function Lo(e){return e.base?`against \`${e.base}\``:"uncommitted work"}a(Lo,"baseLabel");function Po(e,t,n){let r=e.review,i=r?.convention_findings??[],s=r?.lesson_hints??[],o=r?.risk_flags??[],c=[];if(c.push("<!-- Generated by `maind review` \u2014 do not edit by hand. -->"),c.push(`<!-- generated_at: ${n.generatedAt} | key: ${n.keyPrefix}${n.runRef?` | run: ${n.runRef}`:""} -->`),c.push(""),c.push("# maind review"),c.push(""),c.push(`Reviewed ${Lo(n)}: ${n.symbolCount} changed symbol(s) across ${n.diffStats?.changed_file_count??0} file(s) \xB7 findings: ${i.length} \xB7 risk flags: ${o.length} \xB7 lesson hints: ${s.length}`),c.push(""),t?.ok===!0&&t.verdict){c.push(Do(t));let u=Mo(t);u&&(c.push(""),c.push(u)),t.trust_note&&(c.push(""),c.push(`_${t.trust_note}_`)),c.push("")}if(i.length>0){c.push("## Convention findings"),c.push("");for(let u of i)c.push(Oo(u));c.push("")}else c.push("## Convention findings"),c.push(""),c.push("_No convention findings for this change set._"),c.push("");if(o.length>0){c.push("## Risk flags"),c.push(""),c.push("_Path heuristics from the local diff \u2014 informational, they never block._"),c.push("");for(let u of o)c.push(`- \`${u}\``);c.push("")}if(c.push(...Qu(n,t)),s.length>0){c.push("## Lesson hints"),c.push(""),c.push("_Semantic suggestions \u2014 advisory, never part of a verdict._"),c.push("");for(let u of s){let d=[`\`${u.id}\``];u.tier&&d.push(u.tier),u.match_reason&&d.push(u.match_reason),c.push(`- **${u.title}** (${d.join(" \xB7 ")})`)}c.push("")}let l=r?.regression_context;return l&&(l.hot_files??0)>0&&(c.push(""),c.push(`_History: ${l.hot_files}/${l.files_scanned??"?"} changed file(s) high-churn (max ${l.max_recent_commits??"?"} commits in the last ${l.window_commits??"?"}-commit window, ${l.distinct_authors??"?"} author(s))._`)),r?.coverage_note&&(c.push("## Coverage"),c.push(""),c.push(`> ${r.coverage_note}`),c.push("")),c.push("---"),c.push(ar),c.push(""),c.join(`
213
+ `)}a(Po,"renderReviewMarkdown");function jo(e,t,n,r){let i=e.review,s=i?.convention_findings??[],o=i?.risk_flags??[],c=i?.lesson_hints??[],l=[];if(l.push(Co),l.push("## maind review"),l.push(""),t?.ok===!0&&t.verdict){l.push(Do(t));let u=Mo(t);u&&l.push(u),l.push("")}if(s.length===0)l.push(`No convention findings for this change set (${n.symbolCount} changed symbol(s) reviewed ${Lo(n)}).`),l.push("");else{let u=s.slice(0,30);for(let d of u)l.push(Oo(d));s.length>u.length&&(l.push(""),l.push(`\u2026and ${s.length-u.length} more finding(s) \u2014 see the \`${r}\` build artifact.`)),l.push("")}return o.length>0&&(l.push(`**Risk flags:** ${o.map(u=>`\`${u}\``).join(" \xB7 ")} _(heuristics, never blocking)_`),l.push("")),l.push(...Zu(n,t)),c.length>0&&(l.push("**Related lessons:** "+c.map(u=>`\`${u.id}\``).join(" \xB7 ")),l.push("")),i?.coverage_note&&(l.push(`> ${i.coverage_note}`),l.push("")),l.push("---"),l.push(`_${ar}_`),l.push(""),l.join(`
214
+ `)}a(jo,"renderReviewComment");function Fo(e,t){return["<!-- Generated by `maind review` (fail-open path). -->",`<!-- generated_at: ${e.generatedAt} -->`,"","# maind review","",`_maind review was unavailable for this run: ${t}_`,"","The build can proceed normally \u2014 this file is informational only.",""].join(`
215
+ `)}a(Fo,"renderFailOpenReview");function Uo(e,t){return[Co,"## maind review","",`_maind review was unavailable for this run: ${t}_`,"","---",`_${ar}_`,""].join(`
216
+ `)}a(Uo,"renderFailOpenComment");var sd=/^[a-f0-9]{64}$/,od=G,ad=".maind/review-comment.md",cd=64;function Ho(e){let t=a(c=>{let l=e.indexOf(c);if(!(l===-1||l+1>=e.length))return e[l+1]},"get"),n=a(c=>e.includes(c),"has"),r=null,i=e.indexOf("--comment");if(i!==-1){let c=e[i+1];r=c&&!c.startsWith("--")?c:ad}let s=t("--fail-on"),o=s==="block"||s==="warn"?s:null;return{base:t("--base")??null,uncommitted:n("--uncommitted"),summary:t("--summary")??null,json:n("--json"),out:t("--out")??".maind/review.md",comment:r,gate:n("--gate"),failOn:o,strict:n("--strict"),noReport:n("--no-report"),projectKey:t("--project-key")??null,mcpUrl:t("--mcp-url")??null,runRef:t("--run-ref")??process.env.GITHUB_RUN_ID??null,clientVersion:od}}a(Ho,"parseReviewArgs");function ld(){return new Date().toISOString()}a(ld,"nowIso");function me(e,t){let n=id(e);n&&n!=="."&&nd(n,{recursive:!0}),rd(e,t,"utf8")}a(me,"writeArtifact");function Wo(e){return e.endsWith(".md")?e.slice(0,-3)+".json":e+".json"}a(Wo,"manifestPathFor");function ud(e,t){return t==="block"?e==="block":e==="block"||e==="warn"}a(ud,"verdictCrossesFailOn");function dd(e,t,n){return e===0&&!t&&!n}a(dd,"shouldShortCircuit");function fd(e,t){return{changed_file_count:e.changedFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,stale_file_count:e.staleFiles,truncated:e.truncated,hunk_coverage:e.hunkCoverage,base_kind:e.baseKind,...e.headSha?{head_sha:e.headSha}:{},dirty:e.dirty,...e.baseSha?{base_sha:e.baseSha}:{},code_index_version:or,...t?{detector_coverage:t}:{}}}a(fd,"buildDiffStats");function pd(){try{return td("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}a(pd,"resolveRepoRoot");async function Go(e){let t={generatedAt:ld(),keyPrefix:"unknown",runRef:e.runRef,base:e.base,mcpUrl:e.mcpUrl??process.env.MAIND_MCP_URL??"https://mcp.maind.dev/mcp",symbolCount:0,diffStats:null,gate:e.gate,failOn:e.gate?e.failOn:null,detectors:null,detectorsAcknowledged:null};e.failOn&&!e.gate&&K("--fail-on has no effect without --gate (advisory runs always exit 0).");let n=a((r,i="infra")=>{let s=e.strict&&i==="infra";K(`review unavailable, ${s?"failing (--strict)":"continuing"}: ${r}`);try{me(e.out,Fo(t,r));let o=cr({},null,t);o.error=r,o.error_class=i,me(Wo(e.out),JSON.stringify(o,null,2)+`
217
+ `),e.comment&&me(e.comment,Uo(t,r)),e.json&&process.stdout.write(JSON.stringify(o,null,2)+`
218
+ `)}catch(o){return K(`could not write fail-open artifacts: ${Me(o)}`),e.strict?2:1}return s?2:0},"failOpen");try{let r=pd();if(!r)return n("not a git repository \u2014 review is diff-based.","expected");let i=gt({repoRoot:r}),s,o=null;try{let x=await i.status();if(!x.indexed||x.fileCount===0){K("no local index found \u2014 building it now (first run in this checkout)\u2026");let C=await i.indexRepository();K(`indexed ${C.filesParsed} file(s) in ${Math.round(C.durationMs/1e3)}s.`)}if(s=await i.reviewChanges({since:e.base??void 0,includeUncommitted:e.base?e.uncommitted:!0,limit:cd}),e.gate)try{o=await i.reviewDetectors({baseRef:e.base??void 0})}catch(C){o=ce(Se(`reviewDetectors failed: ${Me(C)}`))}}finally{await i.close().catch(()=>{})}let c=fd(s,o?.coverage);t.diffStats=c,t.symbolCount=s.symbols.length,t.detectors=o;let l=e.summary?.trim()||void 0,u=null;if(s.symbols.length===0&&!l){let x=s.riskFlags,C={ok:!0,review:{convention_findings:[],lesson_hints:[],risk_flags:x,coverage_note:x.length>0?s.changedFiles===0?"No indexable changed files \u2014 the risk flags below come from non-indexable paths (migrations, workflows, manifests, env files), which the symbol index never sees.":"Changed files found but no indexed symbols \u2014 no symbol-level review. The risk flags below come from the raw path list; pass --summary for an index-less review.":s.changedFiles===0?"No changed files detected.":"Changed files found but no indexed symbols \u2014 nothing reviewable at symbol level."}};if(dd(s.symbols.length,l,e.gate))return Bo(C,null,t,e),process.stderr.write(`maind review: no reviewable symbols (${s.changedFiles} changed file(s), ${x.length} risk flag(s)) \u2192 ${e.out}
219
+ `),0;u=C}let d=I();t.keyPrefix=d.keyPrefix;let f=e.projectKey?.trim().toLowerCase(),p=f&&sd.test(f)?f:j().projectKey,m=new P({apiKey:d.apiKey,deviceId:d.deviceId,clientVersion:e.clientVersion,mcpUrl:e.mcpUrl??void 0,projectKey:p}),h;try{h=Wt(await i.fileHistory({since:e.base??void 0,limit:1}))}catch{h=void 0}let y={changed_symbols:s.symbols.map(x=>({name:x.name,qualified_name:x.qualifiedName,kind:x.kind,language:x.language,change:x.change,changed_line_count:x.changedLineCount})),risk_flags:s.riskFlags,diff_stats:c,...h?{history:h}:{},...l?{change_summary:l}:{},...p?{project_key:p}:{}},b=u??await m.callTool("review_changes",y);if(b.ok!==!0||!b.review)return n(`review_changes rejected: ${b.error??"unknown_error"}${b.message?` \u2014 ${b.message}`:""}`,Ko(b.error));let g=null;if(e.gate){let x=b.review.convention_findings??[],C=!e.noReport&&s.headSha?{commit_sha:s.headSha,...s.baseSha?{base_sha:s.baseSha}:{},dirty:s.dirty,diff_stats:c,code_index_version:or}:{};try{if(g=await m.callTool("review_verdict",{findings:x.map(R=>({convention_id:R.convention_id,convention_version:R.convention_version,matched_symbols:R.matched_symbols,matched_changed_symbols:R.matched_changed_symbols??[]})),risk_flags:b.review.risk_flags??[],...o?{detector_findings:o.findings}:{},...p?{project_key:p}:{},...C}),g.ok===!0&&o&&(t.detectorsAcknowledged=Array.isArray(g.detector_findings),t.detectorsAcknowledged||K("detector section not acknowledged by server (< 0.48.0) \u2014 this run was recorded as format 1 without detector findings.")),g.ok!==!0)if(g.error==="requires_team"||g.error==="requires_enterprise")K("gate skipped: review_verdict is a Team-plan feature \u2014 findings below are advisory. "+(g.message??"Upgrade at https://maind.dev/pricing.")),g=null;else{let R=Ko(g.error);if(e.strict&&R==="infra")return n(`review_verdict failed: ${g.error??"unknown_error"}${g.message?` \u2014 ${g.message}`:""}`,R);K(`gate unavailable (continuing advisory): ${g.error??"unknown_error"}`),g=null}}catch(R){if(e.strict)return n(`review_verdict failed: ${Me(R)}`,"infra");K(`gate unavailable (continuing advisory): ${Me(R)}`),g=null}}Bo(b,g,t,e);let w=b.review.convention_findings?.length??0,S=g?.run?` \xB7 run: ${g.run.id.slice(0,8)}${g.run.attestation_grade?" (attestation-grade)":""}`:g?.run_note?` \xB7 run: none (${g.run_note})`:"",A=g?.verdict?` \xB7 verdict: ${g.verdict}${S}`:"",O=t.detectors?` \xB7 detectors: ${t.detectors.coverage} (${Tt(t.detectors).blockEligible} block-eligible)`+(t.detectorsAcknowledged===!1?", not acknowledged by server":""):"";return process.stderr.write(`maind review: ${w} finding(s), ${b.review.risk_flags?.length??0} risk flag(s)${A}${O} \u2192 ${e.out}
220
+ `),e.gate&&e.failOn&&g?.verdict&&ud(g.verdict,e.failOn)?(K(`verdict '${g.verdict}' crossed --fail-on ${e.failOn} \u2014 failing the check.`),1):0}catch(r){return r instanceof T?n(r.message,"expected"):n(Me(r),"infra")}}a(Go,"runReview");var md=new Set(["unauthorized","invalid_api_key","requires_team","requires_enterprise","scope_not_in_plan","rate_limited"]);function Ko(e){return e&&md.has(e)?"expected":"infra"}a(Ko,"classifyServerError");function Bo(e,t,n,r){me(r.out,Po(e,t,n));let i=cr(e,t,n);me(Wo(r.out),JSON.stringify(i,null,2)+`
221
+ `),r.comment&&me(r.comment,jo(e,t,n,r.out)),r.json&&process.stdout.write(JSON.stringify(i,null,2)+`
222
+ `)}a(Bo,"writeAll");function Me(e){return e instanceof Error?e.message:String(e)}a(Me,"msg");function K(e){process.stderr.write(`maind review: ${e}
223
+ `)}a(K,"warn");import{createReadStream as yd,existsSync as bd}from"node:fs";import{createInterface as _d}from"node:readline";var hd=new Set(["low","medium","high","xhigh","max"]),gd=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;function $t(e){if(!e)return null;let t=null;for(let n of e.matchAll(gd)){let r=n[1].toLowerCase();hd.has(r)&&(t=r)}return t}a($t,"detectEffortLevel");var Vo="mcp__maind__",qo="2026-08-16",wd=/(\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,kd=/(\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,Ed=/(\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,xd="[Request interrupted by user",vd="The user doesn't want to proceed with this tool use",Sd="<synthetic>",Rd=.7,he={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};function Le(e){return typeof e=="number"&&Number.isFinite(e)?e:0}a(Le,"num");function Ad(e,t,n,r,i){let s=`${n?"s":"m"}:${t}`,o=e.get(s);if(!o){e.set(s,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}o.turns++,o.output_tokens+=r,i>0&&((o.first_ts===0||i<o.first_ts)&&(o.first_ts=i),i>o.last_ts&&(o.last_ts=i))}a(Ad,"bumpModel");function ur(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}a(ur,"asBlocks");function Td(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
224
+ `)}a(Td,"textOf");function $d(e,t){let n=a(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[s,o]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of s)o.has(l)&&c++;return c/s.size>=.8}a($d,"isRepeat");function Id(e,t,n){return wd.test(e)?{polarity:-1,magnitude:he.rework,kind:"rework"}:n&&kd.test(e)?{polarity:-1,magnitude:he.correction,kind:"correction"}:Ed.test(e)?{polarity:1,magnitude:he.acceptance,kind:"acceptance"}:t!==null&&$d(t,e)?{polarity:-1,magnitude:he.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}a(Id,"classifyGenuine");function Nd(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:qo}}a(Nd,"emptyAnalysis");async function dr(e){let t=Nd("");if(!e||!bd(e))return t;let n=[],r=new Map,i=null,s=!1,o=null;await new Promise(f=>{let p=yd(e,{encoding:"utf-8"}),m=_d({input:p}),h=a(y=>{let b=y.trim();if(!b)return;let g;try{g=JSON.parse(b)}catch{return}if(t.lines_seen++,!t.session_id){let v=g.sessionId??g.session_id;typeof v=="string"&&v&&(t.session_id=v)}g.type==="ai-title"&&typeof g.aiTitle=="string"&&g.aiTitle&&(t.ai_title=g.aiTitle),typeof g.slug=="string"&&g.slug&&(t.session_slug=g.slug);let w=g.message?.role,S=g.isSidechain===!0,A=g.message?.usage;if(w==="assistant"&&A&&(t.input_tokens+=Le(A.input_tokens),t.output_tokens+=Le(A.output_tokens),t.cache_read_tokens+=Le(A.cache_read_input_tokens),t.cache_creation_tokens+=Le(A.cache_creation_input_tokens)),w==="assistant"&&typeof g.message?.model=="string"&&g.message.model&&g.message.model!==Sd){let v=g.timestamp?Date.parse(g.timestamp):Number.NaN;Ad(r,g.message.model,S,Le(A?.output_tokens),Number.isFinite(v)?v:0)}if(w==="assistant")for(let v of ur(g.message?.content)){if(v.type!=="tool_use"||typeof v.name!="string"||!v.name.startsWith(Vo))continue;let V=v.name.slice(Vo.length);V&&(t.maind_tool_calls[V]=(t.maind_tool_calls[V]??0)+1)}if(S)return;if(w==="assistant"){t.assistant_turns++;let v=ur(g.message?.content),V=!1;for(let mr of v)mr.type==="tool_use"&&(t.tool_calls++,V=!0,mr.name==="AskUserQuestion"&&t.agent_questions++);s=V;return}if(w!=="user")return;let O=ur(g.message?.content),x=Td(O);if(x.includes(xd)){t.interrupts++,n.push({polarity:-1,magnitude:he.interrupt,kind:"interrupt"});return}if(O.some(v=>v.type==="tool_result"&&v.is_error===!0&&typeof v.content=="string"&&v.content.includes(vd))){t.tool_denials++,n.push({polarity:-1,magnitude:he.denial,kind:"denial"});return}if(O.some(v=>v.type==="tool_result")||!x.trim())return;t.user_turns++,t.user_chars+=x.length;let R=$t(x);R&&(i=R);let $=Id(x,o,s);o=x,$.kind==="correction"?t.corrections++:$.kind==="rework"?t.reworks++:$.kind==="repeat"?t.repeated_instructions++:$.kind==="acceptance"&&t.acceptances++,$.polarity!==0&&n.push($),s=!1},"processLine");m.on("line",y=>{try{h(y)}catch{}}),m.on("close",()=>f()),m.on("error",()=>f()),p.on("error",()=>f())}),t.effort_at_end=i,t.model_mix=[...r.values()].sort((f,p)=>f.first_ts-p.first_ts||f.model.localeCompare(p.model)),t.user_token_estimate=Math.round(t.user_chars/4);let c=t.user_token_estimate+t.output_tokens;t.human_share=c>0?Number((t.user_token_estimate/c).toFixed(4)):0;let l=0,u=0,d=[];return n.forEach((f,p)=>{f.polarity>0?t.reactions_pos++:f.polarity<0&&t.reactions_neg++,l=l*Rd+f.polarity*f.magnitude;let m=Number(l.toFixed(3));d.push({t:p,value:m,...f.kind!=="neutral"?{kind:f.kind}:{}}),u+=m,p>0&&n[p-1].polarity<0&&f.polarity>0&&t.recovery_events++}),t.net_sentiment=t.reactions_pos-t.reactions_neg,t.momentum_series=d,t.momentum_final=d.length?d[d.length-1].value:0,t.momentum_auc=Number(u.toFixed(3)),t.ended_positive=t.momentum_final>0,Object.keys(t.maind_tool_calls).length>0&&(t.maind_connected="connected"),t}a(dr,"analyzeSession");function zo(e,t,n,r="unknown"){let i={session_analytics:{...e,ingest_source:r}};return t&&t.started_at&&(i.session_span=n?{...t,...n}:t),i}a(zo,"ingestBody");function Yo(e){let t={"content-type":"application/json",authorization:`Bearer ${e.apiKey}`};return e.deviceId&&(t["x-maind-device-id"]=e.deviceId),t}a(Yo,"ingestHeaders");async function fr(e,t,n,r,i="unknown"){try{let s=await fetch(e.endpoint,{method:"POST",headers:Yo(e),body:JSON.stringify(zo(t,n,r,i))});if(!s.ok){let c=await s.text().catch(()=>"");return{ok:!1,inserted:0,status:s.status,error:c.slice(0,500)}}let o=await s.json().catch(()=>null);return{ok:!0,inserted:o?.analytics_stored?1:0,spanStored:o?.span_stored===!0,status:s.status}}catch(s){return{ok:!1,inserted:0,error:s instanceof Error?s.message:String(s)}}}a(fr,"postSessionAnalytics");import{readdir as Xo,stat as Cd}from"node:fs/promises";import{homedir as Od}from"node:os";import{join as It}from"node:path";var Dd=Od(),Jo=It(Dd,".claude","projects");function Qo(e){return e.startsWith("-")?e.replace(/-/g,"/"):e}a(Qo,"cwdFromProjectDir");async function pr(e=Jo){let t;try{t=await Xo(e)}catch{return[]}let n=[];for(let r of t){if(!r.startsWith("-"))continue;let i=It(e,r),s;try{s=await Xo(i)}catch{continue}let o=s.filter(l=>l.endsWith(".jsonl"));if(o.length===0)continue;let c=0;for(let l of o)try{let u=await Cd(It(i,l));u.mtimeMs>c&&(c=u.mtimeMs)}catch{}n.push({encodedDir:r,cwd:Qo(r),transcripts:o.map(l=>It(i,l)),mtimeMs:c})}return n.sort((r,i)=>i.mtimeMs-r.mtimeMs),n.map(({mtimeMs:r,...i})=>i)}a(pr,"listProjects");var Md="https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest",Ld=120;function Nt(e){process.stderr.write(`maind: ${e}
225
+ `)}a(Nt,"err");function B(e){process.stdout.write(e+`
226
+ `)}a(B,"out");function Zo(e){let t={dryRun:!1,since:null,json:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--dry-run")t.dryRun=!0;else if(r==="--json")t.json=!0;else if(r==="--since"){let i=e[++n],s=i?Date.parse(i):Number.NaN;Number.isFinite(s)?t.since=s:Nt(`ignoring unparseable --since '${i??""}' (expected YYYY-MM-DD)`)}}return t}a(Zo,"parseSessionsArgs");function Pd(){let e=process.env.MAIND_INGEST_URL?.trim();return e&&e.length>0?e:Md}a(Pd,"endpoint");var jd=a(e=>new Promise(t=>setTimeout(t,e)),"sleep");async function ea(e){let t;try{t=I()}catch(l){if(l instanceof T)return Nt(l.message),1;throw l}let r=(await pr()).flatMap(l=>l.transcripts);if(r.length===0)return Nt("no Claude Code transcripts found under ~/.claude/projects."),0;let i=Pd(),s=[],o=0,c=0;for(let l of r){let u=await dr(l);if(!u.session_id){o++;continue}if(e.since!==null){let p=u.model_mix.reduce((m,h)=>Math.max(m,h.last_ts),0);if(p>0&&p<e.since){o++;continue}}let d=u.model_mix.filter(p=>!p.sidechain),f={session_id:u.session_id,title:u.ai_title,models:d.map(p=>`${p.model}\xD7${p.turns}`).join(", ")||"\u2014",turns:u.assistant_turns,lines:u.lines_seen,posted:!1};if(!e.dryRun){let p=await fr({endpoint:i,apiKey:t.apiKey,deviceId:t.deviceId},u,null,void 0,"backfill");f.posted=p.ok,p.ok||(c++,f.error=p.error??`status ${p.status??"?"}`),await jd(Ld)}s.push(f)}if(e.json)return B(JSON.stringify({ok:c===0,dry_run:e.dryRun,skipped:o,failed:c,sessions:s},null,2)),c===0?0:1;B(e.dryRun?`Would upload ${s.length} session(s) to ${i}:`:`Uploaded ${s.length-c}/${s.length} session(s) to ${i}:`),B("");for(let l of s){let u=e.dryRun?" ":l.posted?"\u2713":"\u2717";B(`${u} ${l.session_id.slice(0,8)} ${String(l.turns).padStart(4)} turns ${l.models}`),B(` title: ${l.title??"\u2014"}`),l.error&&B(` error: ${l.error}`)}return B(""),o>0&&B(`${o} transcript(s) skipped (no session id, or older than --since).`),e.dryRun&&(B("Dry run \u2014 nothing was uploaded."),B("Note: a real run uploads the session TITLES listed above (content-derived) for every project on this machine. They are only stored if you enabled 'Session titles' in the consent center; without it the numbers land and the titles are dropped.")),c>0&&Nt(`${c} session(s) failed \u2014 re-running is safe, the server upserts.`),c===0?0:1}a(ea,"runSessionsBackfill");import{execFileSync as Fd}from"node:child_process";var Ud="2026-07-05",Kd="https://app.maind.dev";function Pe(e){process.stderr.write(`maind: ${e}
227
+ `)}a(Pe,"err");function Bd(){try{return Fd("git",["rev-parse","--show-toplevel"],{encoding:"utf8"}).trim()}catch{return process.cwd()}}a(Bd,"repoRoot");function Hd(){let e=process.env.MAIND_DASHBOARD_URL?.trim();return(e&&e.length>0?e:Kd).replace(/\/+$/,"")}a(Hd,"dashboardUrl");function Wd(e){let t;try{t=I()}catch(n){if(n instanceof T)return Pe(n.message),null;throw n}try{return Ds({repoRoot:Bd(),endpoint:Hd(),apiKey:t.apiKey,deviceId:t.deviceId,onProgress:e?void 0:n=>process.stderr.write(` ${n.phase}: ${n.done}/${n.total}\r`)})}catch(n){return Pe(n instanceof Error?n.message:String(n)),null}}a(Wd,"makeSync");function Gd(e){return e instanceof Error?e.message:String(e)}a(Gd,"msg");function ta(e){let t=e.find(r=>!r.startsWith("-"));return{sub:t==="status"||t==="enable"||t==="disable"?t:"push",json:e.includes("--json")}}a(ta,"parseSyncArgs");async function na(e){let t=Wd(e.json);if(!t)return 1;try{switch(e.sub){case"enable":return await Vd(t);case"disable":return await qd(t);case"status":return await zd(t,e.json);default:return await Yd(t,e.json)}}catch(n){return n instanceof ee&&n.code==="consent_required"?(Pe("codebase cloud-sync is not enabled \u2014 run `maind sync enable` first."),1):(Pe(`sync failed: ${Gd(n)}`),1)}finally{await t.close().catch(()=>{})}}a(na,"runSync");async function Vd(e){return await e.setConsent(!0,Ud),process.stdout.write("codebase cloud-sync enabled. Structured rows (symbol names, topology, hashes) will be pushed on `maind sync` \u2014 never source, snippets, or plaintext paths.\n"),0}a(Vd,"enable");async function qd(e){return await e.setConsent(!1),process.stdout.write(`codebase cloud-sync disabled.
228
+ `),0}a(qd,"disable");async function zd(e,t){let n=await e.localStatus(),r=await e.remoteStatus();return t?(process.stdout.write(JSON.stringify({ok:!0,local:n,remote:r},null,2)+`
222
229
  `),0):(process.stdout.write(`local: ${n.indexed?`${n.nodeCount} symbols \xB7 ${n.edgeCount} edges \xB7 ${n.fileCount} files`:"not indexed"}${n.lastSyncedAt?` \xB7 last synced ${new Date(n.lastSyncedAt).toISOString()}`:""}
223
230
  cloud: ${r.indexed?`${r.node_count??"?"} symbols \xB7 ${r.edge_count??"?"} edges`:"not synced"}
224
- `),0)}a(tu,"status");async function nu(e,t){let n=await e.localStatus();if(!n.indexed||n.nodeCount===0)return Ee("no local index found \u2014 run `maind index` first."),1;let r=await e.push();return process.stderr.write(`
231
+ `),0)}a(zd,"status");async function Yd(e,t){let n=await e.localStatus();if(!n.indexed||n.nodeCount===0)return Pe("no local index found \u2014 run `maind index` first."),1;let r=await e.push();return process.stderr.write(`
225
232
  `),t?(process.stdout.write(JSON.stringify({ok:!0,...r},null,2)+`
226
233
  `),0):(process.stdout.write(`synced ${r.nodes} symbols + ${r.edges} edges to the cloud${r.embeddings?` + ${r.embeddings} vectors`:""}${r.pruned?` (pruned ${r.pruned} stale)`:""}${r.headCommit?` @ ${r.headCommit.slice(0,8)}`:""}.
227
- `),0)}a(nu,"push");var ru=`maind ${H} \u2014 headless MAIND CLI for CI + git context
234
+ `),0)}a(Yd,"push");var Xd=`maind ${G} \u2014 headless MAIND CLI for CI + git context
228
235
 
229
236
  Usage:
230
237
  maind context [options] Pull stack-relevant lessons + conventions into the runner
@@ -264,6 +271,8 @@ review options (advisory by default \u2014 exits 0 unless --gate + --fail-on):
264
271
  line 1 carries the idempotency marker for the workflow to post via gh
265
272
  --json Print the review manifest JSON to stdout (pipeable)
266
273
  --gate Aggregate findings into a server-side pass|warn|block verdict (Team plan)
274
+ Also runs the four repo-health detectors (number collisions, spec drift,
275
+ dead theme classes, table ACL); only evidence hashes + coverage are sent (ADR-324)
267
276
  --fail-on block|warn With --gate: exit 1 when the verdict crosses this threshold
268
277
  --strict Infra errors (native module / transport / unexpected server
269
278
  error) exit 2 instead of failing open with exit 0. Expected
@@ -344,12 +353,12 @@ Auth:
344
353
  Reads MAIND_API_KEY (a read-scoped CI key from https://maind.dev/keys), or falls
345
354
  back to a paired bridge key on this machine. The context pull is fail-open: on any
346
355
  error it still writes explanatory artifacts and exits 0 so the build proceeds.
347
- `;async function iu(){let e=process.argv.slice(2),t=e[0];if(!t||t==="--help"||t==="-h"||t==="help")return process.stdout.write(ru),0;if(t==="--version"||t==="-v")return process.stdout.write(H+`
348
- `),0;if(t==="context")return An(Rn(e.slice(1)));if(t==="git-context")return Gn(Hn(e.slice(1)));if(t==="project-key"){let r=L().projectKey;return r?(process.stdout.write(r+`
356
+ `;async function Jd(){let e=process.argv.slice(2),t=e[0];if(!t||t==="--help"||t==="-h"||t==="help")return process.stdout.write(Xd),0;if(t==="--version"||t==="-v")return process.stdout.write(G+`
357
+ `),0;if(t==="context")return wr(_r(e.slice(1)));if(t==="git-context")return Pr(Mr(e.slice(1)));if(t==="project-key"){let r=j().projectKey;return r?(process.stdout.write(r+`
349
358
  `),0):(process.stderr.write(`maind: not a git repo with a remote \u2014 no project_key.
350
- `),1)}return t==="launch"?us(ls(e.slice(1))):(t==="index"&&e.includes("--embed")||t==="index-semantic")&&!$i(e)?Ii(e):t==="index"?Ci(et(e.slice(1))):t==="index-status"?Mi(et(e.slice(1))):t==="index-search"?Di(Qt(e.slice(1))):t==="index-semantic"?Pi(Qt(e.slice(1))):t==="index-arch"?Li(et(e.slice(1))):t==="sync"?qs(Vs(e.slice(1))):t==="sessions"?e[1]!=="backfill"?(process.stderr.write(`maind: usage: maind sessions backfill [--dry-run] [--since YYYY-MM-DD] [--json]
351
- `),2):Gs(Ws(e.slice(2))):t==="review"?Ps(Ms(e.slice(1))):t==="object"?ys(gs(e.slice(1))):t==="ci-report"?jn(Ln(e.slice(1))):t==="ci-result"?Kn(Un(e.slice(1))):(process.stderr.write(`maind: unknown command '${t}'. Run 'maind --help'.
352
- `),2)}a(iu,"main");iu().then(e=>process.exit(e)).catch(e=>{process.stderr.write(`maind: fatal: ${e instanceof Error?e.stack??e.message:String(e)}
359
+ `),1)}return t==="launch"?xo(Eo(e.slice(1))):(t==="index"&&e.includes("--embed")||t==="index-semantic")&&!Ks(e)?Bs(e):t==="index"?Gs(_t(e.slice(1))):t==="index-status"?Vs(_t(e.slice(1))):t==="index-search"?qs(Gn(e.slice(1))):t==="index-semantic"?zs(Gn(e.slice(1))):t==="index-arch"?Ys(_t(e.slice(1))):t==="sync"?na(ta(e.slice(1))):t==="sessions"?e[1]!=="backfill"?(process.stderr.write(`maind: usage: maind sessions backfill [--dry-run] [--since YYYY-MM-DD] [--json]
360
+ `),2):ea(Zo(e.slice(2))):t==="review"?Go(Ho(e.slice(1))):t==="object"?Io($o(e.slice(1))):t==="ci-report"?Ir($r(e.slice(1))):t==="ci-result"?Or(Cr(e.slice(1))):(process.stderr.write(`maind: unknown command '${t}'. Run 'maind --help'.
361
+ `),2)}a(Jd,"main");Jd().then(e=>process.exit(e)).catch(e=>{process.stderr.write(`maind: fatal: ${e instanceof Error?e.stack??e.message:String(e)}
353
362
  `),process.exit(1)});
354
363
  /*! Bundled license information:
355
364