@maind-dev/cli 0.100.0 → 0.100.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -184,9 +184,12 @@ Since `0.70.0`, `--gate` sends `review_verdict` what findings are made of — th
184
184
  changed symbols (up to 1000), the raw risk flags, the detector findings with one
185
185
  run entry per catalogued detector, diff statistics and the commit anchors —
186
186
  instead of findings the client assembled. The server matches the symbols against
187
- its full visible code-review convention set itself, so a client cannot leave a
188
- finding out, and records a **format-3** run that anyone with repo access can
189
- recompute (`maind verify`, below).
187
+ the repository's code-review conventions itself — the global ones, your org's
188
+ org-wide ones and team conventions bound to this repository — so a client cannot
189
+ leave a finding out. The set is the same whoever runs the gate (locally, in CI,
190
+ or on replay); a team convention that is not bound to the repository stays a
191
+ session rule and does not gate. The server records a **format-3** run that
192
+ anyone with repo access can recompute (`maind verify`, below).
190
193
 
191
194
  A record is written only where it can be worth something: `--no-report`, a
192
195
  checkout without an `origin` remote, or a shallow clone without a merge base
package/build/index.js CHANGED
@@ -133,7 +133,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
133
133
  vec BLOB NOT NULL,
134
134
  content_hash TEXT NOT NULL
135
135
  );
136
- `,wn="schema_version",rr="last_index_commit",Mi="last_indexed_at",to="edges_dirty",kc="resolve_config_fp",Li="embed_recipe_version",Pi="embed_model",Fi="embed_dim",wc="last_synced_at",ry="last_synced_commit";function vc(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(vc,"splitIdentifier");function oy(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let o of vc(e.name))t.add(o);for(let o of vc(e.qualifiedName))t.add(o);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}a(oy,"buildSearchText");function iy(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let o of vc(r))t.add(o)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}a(iy,"toFtsMatchQuery");var no=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(wn),o=await this.store.countFiles()>0;(t.full||o&&r!==kn)&&await this.wipe();let i=await this.store.getAllFiles(),s;if(t.onlyChangedSince!==void 0){if(i.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let y=cl(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(y===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");s=y}else s=ih(this.repoRoot);let l=new Set(s.map(y=>y.path)),c=new Map(i.map(y=>[y.path,y])),u=i.length>0&&!t.full,d={filesScanned:s.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u},f=!1,p=a(async()=>{f||(f=!0,await this.store.setMeta(to,"1"))},"markEdgesDirty");for(let y of i)l.has(y.path)||(await p(),await this.store.deleteFile(y.path),d.filesDeleted++);let h=0;for(let y of s){h++;let k=ah(this.repoRoot,y.path);if(!k){d.filesSkipped++;continue}let R=c.get(y.path);if(R&&R.mtimeMs===k.mtimeMs&&R.size===k.size){d.filesSkipped++;continue}let x=this.readRepoFile(y.path);if(x===null){d.filesSkipped++;continue}let v=Si(x);if(R&&R.contentHash===v){await this.store.upsertFile({...R,mtimeMs:k.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let w=await this.parser.parse(y.path,x,y.language),A=new Map;for(let S of w.nodes)A.set(S.nodeKey,oy(S));let C={path:y.path,language:y.language,contentHash:v,mtimeMs:k.mtimeMs,size:k.size,indexedAt:n};await p(),await this.store.replaceFileNodes(C,w.nodes,A,{contains:w.edges,refs:w.refs,imports:w.imports,exports:w.exports}),d.filesParsed++,t.onProgress?.({path:y.path,done:h,total:s.length})}let _=Wm(this.repoRoot),b=await this.store.getMeta(kc)!==_.fingerprint;if(f||b||await this.store.getMeta(to)==="1"){let y=Qm(await this.store.getNameIndex()),k=new Jn(_.config,y.files),R=eh(await this.store.getAllFacts(),y,k);await this.store.replaceCrossFileEdges(R),await this.store.setMeta(kc,_.fingerprint),await this.store.setMeta(to,"0")}if(this.embedder&&t.embed){let y=await this.store.getNodesByKinds([...tl]),k=await this.store.getEmbeddingContentHashes(),R=[];for(let v of y){let w=Hm(v),A=Si(`${this.embedder.recipeVersion}\0${w}`);k.get(v.nodeKey)!==A&&R.push({nodeKey:v.nodeKey,text:w,hash:A})}let x=64;for(let v=0;v<R.length;v+=x){let w=R.slice(v,v+x),A=await this.embedder.embedDocuments(w.map(S=>S.text));await this.store.upsertEmbeddings(w.map((S,O)=>({nodeKey:S.nodeKey,dim:this.embedder.dim,vec:A[O],contentHash:S.hash})));let C=Math.min(v+x,R.length);t.onProgress?.({path:"embedding symbols",done:C,total:R.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Li,this.embedder.recipeVersion),await this.store.setMeta(Pi,this.embedder.model),await this.store.setMeta(Fi,String(this.embedder.dim))}await this.store.setMeta(wn,kn),await this.store.setMeta(Mi,String(n));let g=Br(this.repoRoot);return g&&await this.store.setMeta(rr,g),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let i of n)r[i.language]=i.count;let o=await this.store.getMeta(Mi);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:o?Number(o):null,lastIndexCommit:await this.store.getMeta(rr),schemaVersion:await this.store.getMeta(wn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=vn(n.limit,20,100),o=await this.store.searchFts(t,n.kind??null,r),i=[];for(let s of o){let l=await this.store.getNode(s.nodeKey);l&&i.push({...ly(l),score:s.score})}return i}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=vn(n.limit,20,100),o=await this.embedder.embedQuery(t),s=(await this.store.allEmbeddings()).map(c=>({nodeKey:c.nodeKey,score:Vm(o,c.vec)})).sort((c,u)=>u.score-c.score).slice(0,r),l=[];for(let c of s){let u=await this.store.getNode(c.nodeKey);u&&l.push({...ly(u),score:c.score})}return l}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",o=vn(n.maxDepth,3,5),i=vn(n.limit,100,1e3),s=n.kinds??null,l=[],c=new Set,u=new Set([t]),d=[t];for(let f=0;f<o&&d.length>0;f++){let p=[];for(let h of d){let _=await this.store.neighbors(h,r,s,i);for(let b of _){let g=`${b.srcKey} ${b.dstKey} ${b.kind}`;if(c.has(g))continue;if(c.add(g),l.push({srcKey:b.srcKey,dstKey:b.dstKey,kind:b.kind}),l.length>=i)return l;let y=r==="out"?b.dstKey:b.srcKey;u.has(y)||(u.add(y),p.push(y))}}d=p}return l}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=sy(ay.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),o={};for(let s of n)o[s.kind]=s.count;let i={};for(let s of r)i[s.language]=s.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:o,languageDistribution:i,topModules:await this.store.topModulesByFanIn(vn(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=cl(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=vn(t.limit,64,200),o=[],i=0;for(let s of n){let l=await this.store.getNodesByFile(s.path);l.length>0&&i++,o.push(...l)}return o.sort((s,l)=>s.filePath.localeCompare(l.filePath)||s.startLine-l.startLine),{changedFiles:n.length,indexedFiles:i,symbols:o.slice(0,r),truncated:o.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=xi(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(Br(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return gh(this.repoRoot,n,t)}async checkDivergence(t={}){return wl(this.repoRoot,t)}async checkNumberCollisions(t={}){return qr(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Cl(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Jr(this.repoRoot,t)}async reviewDetectors(t={}){return yc(this.repoRoot,t)}async reviewDetectorScopes(t={}){return _c(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=xi(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=uh(this.repoRoot,t),o=r?.files??new Map,i=r?.coverage??"none",s=ny({paths:n,hunks:o,readUntracked:a(p=>this.readRepoFileHead(p,ch),"readUntracked")}),l=oh(n.keys()),c=vn(t.limit,64,t.attest?Pt:200),u=[],d=0,f=0;for(let p of l){let h=await this.store.getNodesByFile(p.path);if(h.length===0)continue;d++;let _=await this.store.getFile(p.path),b=this.readRepoFile(p.path),g=_!==null&&b!==null&&Si(b)!==_.contentHash;g&&(f++,i==="full"&&(i="partial"));let y=n.get(p.path)??"modified",k=o.get(p.path);for(let R of h)u.push(yC(R,y,k,g))}return u.sort((p,h)=>cy(p.change)-cy(h.change)||(p.filePath<h.filePath?-1:p.filePath>h.filePath?1:0)||p.startLine-h.startLine),{changedFiles:l.length,indexedFiles:d,staleFiles:f,symbols:u.slice(0,c),truncated:u.length>c,riskFlags:s,hunkCoverage:i,baseKind:t.since?"ref":"uncommitted",headSha:Br(this.repoRoot),dirty:Kr(this.repoRoot),baseSha:t.since?Ri(this.repoRoot,t.since):null,mergeBaseSha:t.since?ll(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 sy(ay.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 ly(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(ly,"toHit");function vn(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}a(vn,"clampLimit");function cy(e){return e==="added"?0:e==="modified"?1:2}a(cy,"changeRank");function yC(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let o=0;for(let s of n.addedRanges){let l=Math.max(s.start,e.startLine),c=Math.min(s.end,e.endLine);c>=l&&(o+=c-l+1)}let i=n.deletionPoints.some(s=>s>=e.startLine-1&&s<=e.endLine);return o>0||i?{...e,change:"modified",changedLineCount:o,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}a(yC,"classifyReviewSymbol");var _C=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"];var MH=new RegExp(_C.join("|"),"g");var uy="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",bC={meta:"SELECT key, value FROM meta WHERE key = ?",file:"SELECT path, language, content_hash, mtime_ms, size, indexed_at FROM files WHERE path = ?",symbolsInFile:`SELECT ${uy} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${uy} FROM nodes WHERE name = ? AND kind <> 'module' ORDER BY file_path, start_line LIMIT ?`,callersOfFile:"SELECT e.dst_key AS callee_key, e.kind AS edge_kind, c.node_key, c.kind, c.name, c.qualified_name, c.file_path, c.start_line, c.end_line, c.signature FROM nodes n JOIN edges e ON e.dst_key = n.node_key AND e.kind IN ('calls', 'extends', 'implements') JOIN nodes c ON c.node_key = e.src_key WHERE n.file_path = ? AND c.file_path <> ? LIMIT ?",importersOf:"SELECT src_key FROM edges WHERE dst_key = ? AND kind = 'imports' LIMIT ?"};var or="0.2.0";var Ui=200,Bi=512,fy=64,py=32,my=1e4;function ro(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:Pt,attest:!0}}a(ro,"attestReviewOptions");function oo(e,t){let n=0,r=[];for(let i of e.symbols){let s=i.qualifiedName?i.qualifiedName:void 0;if(i.name.length===0||i.name.length>Ui||s!==void 0&&s.length>Bi){n+=1;continue}r.push({name:i.name,...s!==void 0?{qualified_name:s}:{},...i.kind&&i.kind.length<=fy?{kind:i.kind}:{},...i.language&&i.language.length<=py?{language:i.language}:{},change:i.change,changed_line_count:Math.min(Math.max(0,i.changedLineCount),my)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(i=>({detector_id:i.detector_id,detector_version:i.detector_version,state:i.state})),diff_stats:{base_kind:e.baseKind,changed_file_count:e.changedFiles,stale_file_count:e.staleFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,truncated:e.truncated||n>0,hunk_coverage:e.hunkCoverage,detector_coverage:t.coverage},...e.headSha?{commit_sha:e.headSha}:{},...e.baseSha?{base_sha:e.baseSha}:{},...typeof e.mergeBaseSha=="string"?{merge_base_sha:e.mergeBaseSha}:{},dirty:e.dirty,code_index_version:or},dropped:n}}a(oo,"buildAttestPayload");function xc(e,t,n){return e?{persist:!1,skipped:"no_report"}:n.headSha?t?n.baseKind==="ref"&&typeof n.mergeBaseSha!="string"?{persist:!1,skipped:"no_merge_base"}:{persist:!0,skipped:null}:{persist:!1,skipped:"no_project_key"}:{persist:!1,skipped:"no_head"}}a(xc,"attestPersistDecision");function Sc(e,t,n){let r=t,o=[];r===0?o.push("No code_review conventions are visible to you \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):o.push(`Matched by the server (attest mode) against its full visible code_review set${typeof r=="number"?` (${r} convention(s))`:""} \u2014 ${e.symbols.length-n} changed symbol(s), no session filter, no cap.`),e.hunkCoverage!=="full"&&o.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&o.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let i=e.changedFiles-e.indexedFiles;return i>0&&o.push(`${i} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&o.push(`Symbol list truncated at ${Pt} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&o.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),o.join(" ")}a(Sc,"attestCoverageNote");var dy=-32602;function Rc(e){let t=/^MCP error (-?\d+):\s*([\s\S]*)$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=t[2]??"";return n===dy&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===dy?{kind:"invalid_params",code:n,detail:r,issues:kC(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}a(Rc,"classifyMcpErrorText");function kC(e){let t=e.indexOf("[");if(t===-1)return[];try{let n=JSON.parse(e.slice(t));return Array.isArray(n)?n.filter(r=>typeof r=="object"&&r!==null):[]}catch{return[]}}a(kC,"parseIssues");function Ec(e){if(e.kind!=="invalid_params"||e.issues.length!==1)return!1;let t=e.issues[0],n=t.path??[];return n.length===1&&n[0]==="findings"&&t.code==="invalid_type"&&(t.received===void 0||t.received==="undefined")}a(Ec,"isLegacyAttestRejection");var wC=`MCP error -32602: Input validation error: Invalid arguments for tool review_verdict: ${JSON.stringify([{code:"invalid_type",expected:"array",received:"undefined",path:["findings"],message:"Required"}],null,2)}`;var xC="https://mcp.maind.dev/mcp",hy="maind-cli",Me=class extends Error{constructor(n,r){super(n);this.code=r;this.name="McpError"}static{a(this,"McpError")}},Qe=class extends Me{constructor(n,r,o,i=[],s){super(n,s);this.tool=r;this.kind=o;this.issues=i;this.name="McpToolError"}static{a(this,"McpToolError")}},SC=-32602;function gy(e,t){let n=Rc(t);if(!n)return null;let r=`tool ${e} failed: ${n.kind==="unknown_tool"?n.detail:RC(n.detail)}`;return new Qe(r,e,n.kind,n.issues,n.code)}a(gy,"classifyToolErrorText");function RC(e){let t=e.split(`
136
+ `,wn="schema_version",rr="last_index_commit",Mi="last_indexed_at",to="edges_dirty",kc="resolve_config_fp",Li="embed_recipe_version",Pi="embed_model",Fi="embed_dim",wc="last_synced_at",ry="last_synced_commit";function vc(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(vc,"splitIdentifier");function oy(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let o of vc(e.name))t.add(o);for(let o of vc(e.qualifiedName))t.add(o);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}a(oy,"buildSearchText");function iy(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let o of vc(r))t.add(o)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}a(iy,"toFtsMatchQuery");var no=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(wn),o=await this.store.countFiles()>0;(t.full||o&&r!==kn)&&await this.wipe();let i=await this.store.getAllFiles(),s;if(t.onlyChangedSince!==void 0){if(i.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let y=cl(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(y===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");s=y}else s=ih(this.repoRoot);let l=new Set(s.map(y=>y.path)),c=new Map(i.map(y=>[y.path,y])),u=i.length>0&&!t.full,d={filesScanned:s.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u},f=!1,p=a(async()=>{f||(f=!0,await this.store.setMeta(to,"1"))},"markEdgesDirty");for(let y of i)l.has(y.path)||(await p(),await this.store.deleteFile(y.path),d.filesDeleted++);let h=0;for(let y of s){h++;let k=ah(this.repoRoot,y.path);if(!k){d.filesSkipped++;continue}let R=c.get(y.path);if(R&&R.mtimeMs===k.mtimeMs&&R.size===k.size){d.filesSkipped++;continue}let x=this.readRepoFile(y.path);if(x===null){d.filesSkipped++;continue}let v=Si(x);if(R&&R.contentHash===v){await this.store.upsertFile({...R,mtimeMs:k.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let w=await this.parser.parse(y.path,x,y.language),A=new Map;for(let S of w.nodes)A.set(S.nodeKey,oy(S));let C={path:y.path,language:y.language,contentHash:v,mtimeMs:k.mtimeMs,size:k.size,indexedAt:n};await p(),await this.store.replaceFileNodes(C,w.nodes,A,{contains:w.edges,refs:w.refs,imports:w.imports,exports:w.exports}),d.filesParsed++,t.onProgress?.({path:y.path,done:h,total:s.length})}let _=Wm(this.repoRoot),b=await this.store.getMeta(kc)!==_.fingerprint;if(f||b||await this.store.getMeta(to)==="1"){let y=Qm(await this.store.getNameIndex()),k=new Jn(_.config,y.files),R=eh(await this.store.getAllFacts(),y,k);await this.store.replaceCrossFileEdges(R),await this.store.setMeta(kc,_.fingerprint),await this.store.setMeta(to,"0")}if(this.embedder&&t.embed){let y=await this.store.getNodesByKinds([...tl]),k=await this.store.getEmbeddingContentHashes(),R=[];for(let v of y){let w=Hm(v),A=Si(`${this.embedder.recipeVersion}\0${w}`);k.get(v.nodeKey)!==A&&R.push({nodeKey:v.nodeKey,text:w,hash:A})}let x=64;for(let v=0;v<R.length;v+=x){let w=R.slice(v,v+x),A=await this.embedder.embedDocuments(w.map(S=>S.text));await this.store.upsertEmbeddings(w.map((S,O)=>({nodeKey:S.nodeKey,dim:this.embedder.dim,vec:A[O],contentHash:S.hash})));let C=Math.min(v+x,R.length);t.onProgress?.({path:"embedding symbols",done:C,total:R.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Li,this.embedder.recipeVersion),await this.store.setMeta(Pi,this.embedder.model),await this.store.setMeta(Fi,String(this.embedder.dim))}await this.store.setMeta(wn,kn),await this.store.setMeta(Mi,String(n));let g=Br(this.repoRoot);return g&&await this.store.setMeta(rr,g),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let i of n)r[i.language]=i.count;let o=await this.store.getMeta(Mi);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:o?Number(o):null,lastIndexCommit:await this.store.getMeta(rr),schemaVersion:await this.store.getMeta(wn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=vn(n.limit,20,100),o=await this.store.searchFts(t,n.kind??null,r),i=[];for(let s of o){let l=await this.store.getNode(s.nodeKey);l&&i.push({...ly(l),score:s.score})}return i}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=vn(n.limit,20,100),o=await this.embedder.embedQuery(t),s=(await this.store.allEmbeddings()).map(c=>({nodeKey:c.nodeKey,score:Vm(o,c.vec)})).sort((c,u)=>u.score-c.score).slice(0,r),l=[];for(let c of s){let u=await this.store.getNode(c.nodeKey);u&&l.push({...ly(u),score:c.score})}return l}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",o=vn(n.maxDepth,3,5),i=vn(n.limit,100,1e3),s=n.kinds??null,l=[],c=new Set,u=new Set([t]),d=[t];for(let f=0;f<o&&d.length>0;f++){let p=[];for(let h of d){let _=await this.store.neighbors(h,r,s,i);for(let b of _){let g=`${b.srcKey} ${b.dstKey} ${b.kind}`;if(c.has(g))continue;if(c.add(g),l.push({srcKey:b.srcKey,dstKey:b.dstKey,kind:b.kind}),l.length>=i)return l;let y=r==="out"?b.dstKey:b.srcKey;u.has(y)||(u.add(y),p.push(y))}}d=p}return l}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=sy(ay.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),o={};for(let s of n)o[s.kind]=s.count;let i={};for(let s of r)i[s.language]=s.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:o,languageDistribution:i,topModules:await this.store.topModulesByFanIn(vn(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=cl(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=vn(t.limit,64,200),o=[],i=0;for(let s of n){let l=await this.store.getNodesByFile(s.path);l.length>0&&i++,o.push(...l)}return o.sort((s,l)=>s.filePath.localeCompare(l.filePath)||s.startLine-l.startLine),{changedFiles:n.length,indexedFiles:i,symbols:o.slice(0,r),truncated:o.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=xi(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(Br(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return gh(this.repoRoot,n,t)}async checkDivergence(t={}){return wl(this.repoRoot,t)}async checkNumberCollisions(t={}){return qr(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Cl(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Jr(this.repoRoot,t)}async reviewDetectors(t={}){return yc(this.repoRoot,t)}async reviewDetectorScopes(t={}){return _c(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=xi(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=uh(this.repoRoot,t),o=r?.files??new Map,i=r?.coverage??"none",s=ny({paths:n,hunks:o,readUntracked:a(p=>this.readRepoFileHead(p,ch),"readUntracked")}),l=oh(n.keys()),c=vn(t.limit,64,t.attest?Pt:200),u=[],d=0,f=0;for(let p of l){let h=await this.store.getNodesByFile(p.path);if(h.length===0)continue;d++;let _=await this.store.getFile(p.path),b=this.readRepoFile(p.path),g=_!==null&&b!==null&&Si(b)!==_.contentHash;g&&(f++,i==="full"&&(i="partial"));let y=n.get(p.path)??"modified",k=o.get(p.path);for(let R of h)u.push(yC(R,y,k,g))}return u.sort((p,h)=>cy(p.change)-cy(h.change)||(p.filePath<h.filePath?-1:p.filePath>h.filePath?1:0)||p.startLine-h.startLine),{changedFiles:l.length,indexedFiles:d,staleFiles:f,symbols:u.slice(0,c),truncated:u.length>c,riskFlags:s,hunkCoverage:i,baseKind:t.since?"ref":"uncommitted",headSha:Br(this.repoRoot),dirty:Kr(this.repoRoot),baseSha:t.since?Ri(this.repoRoot,t.since):null,mergeBaseSha:t.since?ll(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 sy(ay.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 ly(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(ly,"toHit");function vn(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}a(vn,"clampLimit");function cy(e){return e==="added"?0:e==="modified"?1:2}a(cy,"changeRank");function yC(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let o=0;for(let s of n.addedRanges){let l=Math.max(s.start,e.startLine),c=Math.min(s.end,e.endLine);c>=l&&(o+=c-l+1)}let i=n.deletionPoints.some(s=>s>=e.startLine-1&&s<=e.endLine);return o>0||i?{...e,change:"modified",changedLineCount:o,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}a(yC,"classifyReviewSymbol");var _C=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"];var FH=new RegExp(_C.join("|"),"g");var uy="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",bC={meta:"SELECT key, value FROM meta WHERE key = ?",file:"SELECT path, language, content_hash, mtime_ms, size, indexed_at FROM files WHERE path = ?",symbolsInFile:`SELECT ${uy} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${uy} FROM nodes WHERE name = ? AND kind <> 'module' ORDER BY file_path, start_line LIMIT ?`,callersOfFile:"SELECT e.dst_key AS callee_key, e.kind AS edge_kind, c.node_key, c.kind, c.name, c.qualified_name, c.file_path, c.start_line, c.end_line, c.signature FROM nodes n JOIN edges e ON e.dst_key = n.node_key AND e.kind IN ('calls', 'extends', 'implements') JOIN nodes c ON c.node_key = e.src_key WHERE n.file_path = ? AND c.file_path <> ? LIMIT ?",importersOf:"SELECT src_key FROM edges WHERE dst_key = ? AND kind = 'imports' LIMIT ?"};var or="0.2.0";var Ui=200,Bi=512,fy=64,py=32,my=1e4;function ro(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:Pt,attest:!0}}a(ro,"attestReviewOptions");function oo(e,t){let n=0,r=[];for(let i of e.symbols){let s=i.qualifiedName?i.qualifiedName:void 0;if(i.name.length===0||i.name.length>Ui||s!==void 0&&s.length>Bi){n+=1;continue}r.push({name:i.name,...s!==void 0?{qualified_name:s}:{},...i.kind&&i.kind.length<=fy?{kind:i.kind}:{},...i.language&&i.language.length<=py?{language:i.language}:{},change:i.change,changed_line_count:Math.min(Math.max(0,i.changedLineCount),my)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(i=>({detector_id:i.detector_id,detector_version:i.detector_version,state:i.state})),diff_stats:{base_kind:e.baseKind,changed_file_count:e.changedFiles,stale_file_count:e.staleFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,truncated:e.truncated||n>0,hunk_coverage:e.hunkCoverage,detector_coverage:t.coverage},...e.headSha?{commit_sha:e.headSha}:{},...e.baseSha?{base_sha:e.baseSha}:{},...typeof e.mergeBaseSha=="string"?{merge_base_sha:e.mergeBaseSha}:{},dirty:e.dirty,code_index_version:or},dropped:n}}a(oo,"buildAttestPayload");function xc(e,t,n){return e?{persist:!1,skipped:"no_report"}:n.headSha?t?n.baseKind==="ref"&&typeof n.mergeBaseSha!="string"?{persist:!1,skipped:"no_merge_base"}:{persist:!0,skipped:null}:{persist:!1,skipped:"no_project_key"}:{persist:!1,skipped:"no_head"}}a(xc,"attestPersistDecision");function Sc(e,t,n){let r=t,o=[];r===0?o.push("No code_review conventions apply to this repository \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):o.push(`Matched by the server (attest mode) against the repository's code_review set${typeof r=="number"?` (${r} convention(s))`:""} \u2014 ${e.symbols.length-n} changed symbol(s), no session filter, no cap.`),e.hunkCoverage!=="full"&&o.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&o.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let i=e.changedFiles-e.indexedFiles;return i>0&&o.push(`${i} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&o.push(`Symbol list truncated at ${Pt} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&o.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),o.join(" ")}a(Sc,"attestCoverageNote");var dy=-32602;function Rc(e){let t=/^MCP error (-?\d+):\s*([\s\S]*)$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=t[2]??"";return n===dy&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===dy?{kind:"invalid_params",code:n,detail:r,issues:kC(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}a(Rc,"classifyMcpErrorText");function kC(e){let t=e.indexOf("[");if(t===-1)return[];try{let n=JSON.parse(e.slice(t));return Array.isArray(n)?n.filter(r=>typeof r=="object"&&r!==null):[]}catch{return[]}}a(kC,"parseIssues");function Ec(e){if(e.kind!=="invalid_params"||e.issues.length!==1)return!1;let t=e.issues[0],n=t.path??[];return n.length===1&&n[0]==="findings"&&t.code==="invalid_type"&&(t.received===void 0||t.received==="undefined")}a(Ec,"isLegacyAttestRejection");var wC=`MCP error -32602: Input validation error: Invalid arguments for tool review_verdict: ${JSON.stringify([{code:"invalid_type",expected:"array",received:"undefined",path:["findings"],message:"Required"}],null,2)}`;var xC="https://mcp.maind.dev/mcp",hy="maind-cli",Me=class extends Error{constructor(n,r){super(n);this.code=r;this.name="McpError"}static{a(this,"McpError")}},Qe=class extends Me{constructor(n,r,o,i=[],s){super(n,s);this.tool=r;this.kind=o;this.issues=i;this.name="McpToolError"}static{a(this,"McpToolError")}},SC=-32602;function gy(e,t){let n=Rc(t);if(!n)return null;let r=`tool ${e} failed: ${n.kind==="unknown_tool"?n.detail:RC(n.detail)}`;return new Qe(r,e,n.kind,n.issues,n.code)}a(gy,"classifyToolErrorText");function RC(e){let t=e.split(`
137
137
  `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}a(RC,"firstLine");var ye=class{static{a(this,"McpClient")}mcpUrl;apiKey;deviceId;clientVersion;projectKey;sessionId=null;nextId=1;initialized=!1;server=null;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??xC}headers(){let t={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.apiKey}`,"x-maind-client-family":hy,"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:hy,version:this.clientVersion}}});if(t.message.error)throw new Me(`initialize failed: ${t.message.error.message}`,t.message.error.code);t.sessionId&&(this.sessionId=t.sessionId);let n=t.message.result?.serverInfo;this.server=typeof n?.version=="string"?n.version:null,await this.post({jsonrpc:"2.0",method:"notifications/initialized"}),this.initialized=!0}serverVersion(){return this.server}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){let{code:l,message:c}=r.message.error,u=gy(t,`MCP error ${l}: ${c}`);throw u&&l===SC?u:new Me(`tool ${t} failed: ${c}`,l)}let o=r.message.result,i=o?.content?.find(l=>l.type==="text"&&typeof l.text=="string")?.text;if(typeof i!="string")throw new Me(`tool ${t} returned no text content`);if(o?.isError===!0){let l=gy(t,i);if(l)throw l}let s=TC(i);if(s===void 0)throw new Me(`tool ${t} returned non-JSON text`);return s}async post(t){let n;try{n=await fetch(this.mcpUrl,{method:"POST",headers:this.headers(),body:JSON.stringify(t)})}catch(l){throw new Me(`network error contacting ${this.mcpUrl}: ${AC(l)}`)}let r=n.headers.get("mcp-session-id");if(n.status===401){let l=await n.text().catch(()=>"");throw new Me(`auth rejected (401): ${l.slice(0,200)}`,401)}if(n.status===202)return{message:{jsonrpc:"2.0",result:null},sessionId:r};if(!n.ok){let l=await n.text().catch(()=>"");throw new Me(`upstream HTTP ${n.status}: ${l.slice(0,300)}`,n.status)}let i=(n.headers.get("content-type")??"").startsWith("text/event-stream")?await EC(n):await n.text();if(i.trim().length===0)return{message:{jsonrpc:"2.0",result:null},sessionId:r};let s;try{s=JSON.parse(i)}catch{throw new Me(`could not parse JSON-RPC response: ${i.slice(0,200)}`)}return{message:s,sessionId:r}}};async function EC(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",o=[],i="",s=a(()=>{if(o.length===0)return;let l=o.join(`
138
138
  `).trim();o=[],l.length>0&&(i=l)},"flush");for(;;){let{value:l,done:c}=await t.read();if(c)break;r+=n.decode(l,{stream:!0});let u;for(;(u=r.indexOf(`
139
139
  `))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let f=d.endsWith("\r")?d.slice(0,-1):d;if(f===""){s();continue}f.startsWith(":")||f.startsWith("data:")&&o.push(f.slice(5).replace(/^\s/,""))}}return s(),i}a(EC,"readSseMessage");function AC(e){return e instanceof Error?e.message:String(e)}a(AC,"stringifyErr");function TC(e){let t=e.trim();try{return JSON.parse(t)}catch{}let n=t.indexOf("{"),r=t.indexOf("["),o=[n,r].filter(u=>u>=0);if(o.length===0)return;let i=Math.min(...o),l=t[i]==="{"?"}":"]",c=t.lastIndexOf(l);if(!(c<=i))try{return JSON.parse(t.slice(i,c+1))}catch{return}}a(TC,"parseJsonLoose");function Ac(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(Ac,"buildManifest");function yy(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 o=n.stack.length>0?n.stack.join(", "):"(none)";if(r.push(`**Stack:** ${o} \xB7 **Lessons:** ${e.length} \xB7 **Conventions:** ${t.length}`),r.push(""),t.length>0){r.push("## Always-on conventions"),r.push("");for(let i of t)r.push(`- **${i.title}** \`${i.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(`
@@ -236,7 +236,7 @@ maind: and re-run \`maind launch claude\`. (Or launch without routing: \`maind l
236
236
  `,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(`
237
237
  `);return{stdout:e.toml??`(using existing config: ${e.configPath})
238
238
  `,stderr:n+`
239
- `}}a(W_,"renderDryRun");import{createRequire as c$}from"node:module";function u$(){return"0.100.0";try{return c$(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a(u$,"resolveVersion");var ce=u$();var b$=5e3;function Ne(e){process.stderr.write(`maind: ${e}
239
+ `}}a(W_,"renderDryRun");import{createRequire as c$}from"node:module";function u$(){return"0.100.1";try{return c$(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a(u$,"resolveVersion");var ce=u$();var b$=5e3;function Ne(e){process.stderr.write(`maind: ${e}
240
240
  `)}a(Ne,"err");function k$(e){return e instanceof Error?e.message:String(e)}a(k$,"msg");var w$=new Set(["--config","--route","--mcp-url"]);function z_(e){let t=a(o=>{let i=e.indexOf(o);if(!(i===-1||i+1>=e.length))return e[i+1]},"get"),n=a(o=>e.includes(o),"has"),r=null;for(let o=0;o<e.length;o++){let i=e[o];if(i.startsWith("-")){w$.has(i)&&o++;continue}r=i;break}return{agent:r,dryRun:n("--dry-run"),config:t("--config")??null,route:t("--route")??N_,direct:n("--direct"),noFallback:n("--no-fallback"),noInstall:n("--no-install"),json:n("--json"),mcpUrl:t("--mcp-url")??null}}a(z_,"parseLaunchArgs");var v$={probe(e,t){let n=q_(e,t,{stdio:["ignore","pipe","pipe"],encoding:"utf8",timeout:1e4}),r=n.status===0&&!n.error,o=typeof n.stdout=="string"?n.stdout.trim():"";return{ok:r,stdout:o.length>0?o:null}},install(e){return q_("uv",[...e],{stdio:["ignore","inherit","inherit"]}).status},spawnInteractive(e){let t=Date.now();return new Promise(n=>{let r=!1,o=d$(e[0],e.slice(1),{stdio:"inherit",env:process.env}),i=a(()=>{},"onSigint"),s=a(d=>()=>{try{o.kill(d)}catch{}},"makeForward"),l=s("SIGTERM"),c=s("SIGHUP");process.on("SIGINT",i),process.on("SIGTERM",l),process.on("SIGHUP",c);let u=a(()=>{process.removeListener("SIGINT",i),process.removeListener("SIGTERM",l),process.removeListener("SIGHUP",c)},"cleanup");o.on("error",d=>{r||(r=!0,u(),n({code:null,signal:null,elapsedMs:Date.now()-t,spawnError:d.message}))}),o.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=le()}catch(r){if(r instanceof pe)return null;throw r}try{let r=new ye({apiKey:n.apiKey,deviceId:n.deviceId,clientVersion:ce,mcpUrl:e??void 0,projectKey:t}),o=new Promise(s=>{setTimeout(()=>s(null),b$).unref()}),i=r.callTool("get_template",{template_id:D_}).then(s=>typeof s.template_body=="string"&&s.template_body.trim().length>0?s.template_body:null).catch(()=>null);return await Promise.race([i,o])}catch{return null}},writeConfig(e,t){let n=_$(e);n&&n!=="."&&m$(n,{recursive:!0}),g$(e,t,"utf8")},readFile(e){try{return h$(e,"utf8")}catch{return null}},fileExists(e){return p$(e)},repoRoot(){try{let e=f$("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 Ve().projectKey},userConfigDir(){return Xo()},homeDir(){return y$()},env:process.env,platform:process.platform};function x$(e,t){return e!==null?ru(e,".maind",Yc):ru(t,Yc)}a(x$,"resolveRoutesPath");async function Y_(e,t=v$){let n=j_(e.agent);if(n.kind==="unknown")return Ne(`usage: maind launch <agent> [--dry-run] [--config <path>] [--route <name>] [--direct] [--no-fallback] [--no-install] \u2014 supported: ${Xc.join(", ")}`),2;if(n.kind==="planned")return Ne(`agent '${n.agent}' is planned but not yet supported \u2014 v1 supports: ${Xc.join(", ")}.`),2;if(e.json&&!e.dryRun)return Ne("--json is only valid together with --dry-run (stdout belongs to the agent session)."),2;let r=n.agent;if(e.direct)return Ne(V_()),X_(t,eu(r));let o=M_(t.env);o.warning!==null&&Ne(o.warning);let i,s,l;if(e.config!==null){if(!t.fileExists(e.config))return Ne(`config not found: ${e.config}`),2;let f=t.readFile(e.config);if(f===null||F_(f,e.route)===null)return Ne(`config ${e.config} is not valid routes TOML with a [routes.${e.route}] entry.`),2;i=e.config,s=null,l="flag"}else{let f=await t.fetchTemplate(e.mcpUrl,t.projectKey()),p=f===null?null:P_(f,e.route);if(s=L_(e.route,o,p),p!==null)l="template";else{l="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)`;Ne(`using builtin routing policy (${h}).`)}i=x$(t.repoRoot(),t.userConfigDir())}let c=is,u=t.probe(is,["--version"]).ok;if(e.dryRun){let f={agent:r,configPath:i,configSource:l,toml:s,argv:Qc(c,r,e.route,i),backendKind:o.kind,switchyardDetected:u},p=W_(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 Ne(`switchyard not found (--no-install). Install it with:
241
241
  maind: ${ss}`),1;if(!t.probe("uv",["--version"]).ok)return Ne(K_()),1;if(Ne(B_()),t.install(O_),t.probe(is,["--version"]).ok)u=!0;else{let f=ru(t.homeDir(),".local","bin",t.platform==="win32"?"switchyard.exe":"switchyard");t.probe(f,["--version"]).ok&&(c=f,u=!0)}if(!u)return nu(t,e,r,G_())}if(l!=="flag"&&s!==null)try{t.writeConfig(i,s)}catch(f){return Ne(`could not write ${i}: ${k$(f)}`),1}let d=await t.spawnInteractive(Qc(c,r,e.route,i));return d.spawnError!==null?nu(t,e,r,`could not start switchyard (${d.spawnError})`):U_(d.code,d.signal,d.elapsedMs)==="fallback-eligible"?nu(t,e,r,`switchyard exited with code ${d.code} after ${(d.elapsedMs/1e3).toFixed(1)}s`):tu(d.code,d.signal)}a(Y_,"runLaunch");async function nu(e,t,n,r){return t.noFallback?(Ne(`${r} (--no-fallback set \u2014 not degrading to a direct spawn).`),1):(process.stderr.write(H_(r)+`
242
242
  `),X_(e,eu(n)))}a(nu,"degradeOrFail");async function X_(e,t){let n=await e.spawnInteractive(t);return n.spawnError!==null?(Ne(`'${t[0]}' not found on PATH \u2014 install the agent CLI first (${n.spawnError}).`),1):tu(n.code,n.signal)}a(X_,"spawnAndPropagate");import{execFileSync as gr}from"node:child_process";import{cpSync as _N,existsSync as Uu,mkdirSync as bN,mkdtempSync as kw,readFileSync as kN,realpathSync as wN,rmSync as ww,writeFileSync as As}from"node:fs";import{tmpdir as vw}from"node:os";import{dirname as xw,join as qt,resolve as Gu}from"node:path";function J_(e,t,n=()=>null){if(e!==null)return e.trim()==="0"?{kind:"none",reason:"no required checks"}:{kind:"watch"};let r=t();if(r===null)return{kind:"unknown",reason:"neither query could be answered"};if(r.trim()==="0")return{kind:"none",reason:"no checks at all"};let o=n();return o!==null&&o.trim()==="0"?{kind:"none",reason:"checks exist, none required",checks:Number.parseInt(r.trim(),10)}:{kind:"unknown",reason:`${r.trim()} check(s) exist, but the required-query failed`}}a(J_,"classifyCheckCount");function Z_(e){switch(e.kind){case"watch":return"";case"none":return e.reason==="no checks at all"?"this repository reports NO checks at all \u2014 the merge rests on the local gate alone.":e.reason==="checks exist, none required"?`${e.checks??"some"} check(s) run on this PR, but none is required (no branch protection) \u2014 they are not waited for; the merge rests on the local gate.`:"no required checks are configured \u2014 nothing to wait for.";case"unknown":return`could not establish the required checks: ${e.reason}.`}}a(Z_,"checkCountLine");function Q_(e,t){let n=new Set(t);return e.filter(r=>!n.has(r))}a(Q_,"missingRequiredChecks");function eb(e){if(e===null)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let o=r;if(o?.type!=="required_status_checks")continue;let i=o.parameters?.required_status_checks;if(Array.isArray(i))for(let s of i){let l=s?.context;typeof l=="string"&&!n.includes(l)&&n.push(l)}}return n}catch{return null}}a(eb,"requiredContextsFromRules");import{execFileSync as S$}from"node:child_process";function R$(e,t){if(e===0)return{kind:"clean"};if(e!==1)return{kind:"unknown",reason:e===129?"this git does not know `merge-tree --write-tree` (needs git 2.38+)":`git merge-tree failed (exit ${e??"signal"})`};let n=t.split(`
@@ -469,7 +469,7 @@ ${s}`,2e3)??s}:n.push({type:"thought",body:s});continue}if(r.type==="action"){le
469
469
  `)||e.warn(`could not write the run evidence to ${i}.`)}a(Nj,"writeEvidence");function rx(e){return e==="pass"||e==="warn"||e==="block"}a(rx,"verdictReached");async function Dj(e,t){if(e.repo.commitsAhead(t.wt,`origin/${t.baseBranch}`)===0)return e.warn(`${t.branch} carries no commits over origin/${t.baseBranch} \u2014 no pull request opened.`),null;let r=e.repo.readFile(On(t.wt,js)),o=ke(e.env)?.runId??null,i=ke(e.env)?.adapter==="github",s=e.repo.headSubject(t.wt)??`${t.key}: agent run`,l=null,c=null;if(e.appPr){let p;try{p=await e.appPr({sessionId:t.sessionId,objectId:t.objectId,repo:t.slug,head:t.branch,base:t.baseBranch,title:s,body:hd({agentBody:r,key:t.key,runRef:o,setup:t.setup,viaApp:!0})})}catch{p={ok:!1,error:"unreachable"}}if(p.ok)return e.warn(`opened pull request #${p.number} for ${t.branch} (with the MAIND GitHub app)`),{number:p.number,url:p.url,openedWith:"app",appRefusal:null,appRefusalDetail:null,serverRecorded:p.recorded};if(p.error==="pr_exists"){let h=p.number!==void 0?{number:p.number,url:p.url??null}:e.repo.openPr(t.wt,t.branch);if(h)return{...h,openedWith:null,appRefusal:null,appRefusalDetail:null,serverRecorded:!1}}l=p.error,c=p.detail??null,e.warn(`the MAIND GitHub app did not open the pull request (${p.error}${p.detail?`, ${p.detail}`:""}: ${Ds(p.error,"en",p.detail)})`+(p.acceptUrl?` \u2014 accept it at ${p.acceptUrl}`:"")+` \u2014 falling back to ${t.prToken?.source??"no token"}.`)}if(!t.prToken)return e.warn("no GITHUB_TOKEN in this run's environment \u2014 cannot open the pull request."),null;let u=a(p=>e.repo.createPr({token:p.token,slug:t.slug,head:t.branch,base:t.baseBranch,title:s,body:hd({agentBody:r,key:t.key,runRef:o,setup:t.setup,ciNotice:dd(p.source,i)===!1,appRefusal:l,appRefusalDetail:c})}),"attempt"),d=t.prToken,f=await u(d);if("error"in f&&d.source==="MAIND_PR_TOKEN"&&/^HTTP (401|403|404)\b/.test(f.error)){let p=dv(e.env);e.warn(`MAIND_PR_TOKEN was rejected (${f.error.split(" ").slice(0,2).join(" ")}) \u2014 `+(p?`opening with ${p.source} instead.`:"and there is no job token to fall back to.")),p&&(d=p,f=await u(d))}if("error"in f){let p=e.repo.openPr(t.wt,t.branch);if(p)return{...p,openedWith:null,appRefusal:null,appRefusalDetail:null,serverRecorded:!1};let h=/not permitted to create or approve pull requests/i.test(f.error)?" \u2014 enable it under Settings > Actions > General > Workflow permissions: 'Allow GitHub Actions to create and approve pull requests'. The branch is pushed; the work is not lost.":"";return e.warn(`could not open the pull request: ${f.error}${h}`),null}return e.warn(`opened pull request #${f.number} for ${t.branch} (with ${d.source})`),{...f,openedWith:d.source,appRefusal:l,appRefusalDetail:c,serverRecorded:!1}}a(Dj,"openPullRequest");function cx(e){return e==="subscription"||e==="api"?e:"auto"}a(cx,"parseAuthChoice");function ux(e,t){let n=a(i=>(e[i]??"").trim().length>0,"has"),r=n("CLAUDE_CODE_OAUTH_TOKEN"),o=n("ANTHROPIC_API_KEY");return t==="subscription"?r?null:"auth=subscription, but CLAUDE_CODE_OAUTH_TOKEN is empty \u2014 set the repo secret (run `claude setup-token` on your machine).":t==="api"?o?null:"auth=api, but ANTHROPIC_API_KEY is empty \u2014 set the repo secret.":r||o?null:"neither CLAUDE_CODE_OAUTH_TOKEN nor ANTHROPIC_API_KEY is set \u2014 the run has no model credential."}a(ux,"modelCredentialGap");var dx={ready:0,unchecked:0,reported:3,unreported:4};function fx(e,t,n){switch(t){case"ready":return`preflight: ${e} is ready \u2014 the run may start.`;case"unchecked":return`preflight: ${e} \u2014 the maind server does not offer the readiness check yet; the run's take decides (before any model call).`;case"reported":return`preflight: ${e} is NOT ready \u2014 ${n??"not takeable"}. Recorded on the object as dispatch_failed; nothing was started.`;case"unreported":return`preflight: ${e} is NOT ready \u2014 ${n??"unknown reason"}. Not recorded on the object; nothing was started.`}}a(fx,"preflightLine");function jj(e){if(e instanceof Qe)return{ok:!1,error:e.kind,retryAfterSeconds:null,transient:!1};if(e instanceof Me&&typeof e.code=="number"){if(e.code===401)return{ok:!1,error:"auth_rejected",retryAfterSeconds:null,transient:!1};if(e.code>=400&&e.code<500&&e.code!==408&&e.code!==429)return{ok:!1,error:`http_${e.code}`,retryAfterSeconds:null,transient:!1}}return{ok:!1,error:"unreachable",retryAfterSeconds:null,transient:!0}}a(jj,"activityAnswerFromError");function px(e){return Od(async t=>{try{return $d(await e.callTool(Id,t))}catch(n){return jj(n)}})}a(px,"mcpActivityTransport");async function mx(e,t){let n=e.target.kind==="key"?e.target.key:e.target.kind==="uuid"?e.target.objectId:null;if(!n)return t.warn("preflight needs an object: `maind run preflight <MAI-n|uuid>`."),2;let r=n,o=a((d,f,p={})=>{let h=fx(r,d,f);return d==="ready"||d==="unchecked"?t.out(`${h}
470
470
  `):t.warn(h),e.json&&t.out(`${JSON.stringify({preflight:d,object:r,ready:d==="ready",...f?{why:f}:{},...p.fact?{fact:p.fact}:{},reported:p.reported===!0})}
471
471
  `),dx[d]},"finish"),i=t.resolveRepoRoot(t.cwd());if(!i)return o("unreported","not a git repository");let s=e.projectKey??t.projectKeyOf(i);if(!s)return o("unreported","no project_key \u2014 the repository has no remote to derive it from (pass --project-key)");let l=ux(t.env,e.auth),c=t.newSessionId(),u=await t.plan.announce({projectKey:s,sessionId:c,focus:`kernel: preflight ${n}`,ttlMinutes:10});if(!u.ok)return o("unreported",`could not announce a session: ${u.error??"unknown"}`);try{let d=await t.plan.resolveObject(s,c,n);if(!d.ok)return o("unreported",`${d.error}${d.hint?` \u2014 ${d.hint}`:""}`);r=d.object.key;let f=await t.plan.preflight({projectKey:s,sessionId:c,objectId:d.object.object_id,...l?{clientFailure:"model_credentials_missing"}:{},report:e.report});if(!f.ok)return f.error==="unknown_tool"?l?o("unreported",l):o("unchecked",null):o("unreported",`${f.error}${f.hint?` \u2014 ${f.hint}`:""}`);if(f.ready)return o("ready",null);let p=f.reason==="model_credentials_missing"?l??"the run has no model credential":`${f.fact??f.reason}${f.detail?` (${f.detail})`:""}`;return o(f.reported?"reported":"unreported",p,{fact:f.fact,reported:f.reported})}catch(d){return o("unreported",`maind server: ${d instanceof Error?d.message:String(d)}`)}finally{await t.plan.end(s,c)}}a(mx,"runPreflight");import{execFileSync as HM}from"node:child_process";import{statSync as VM}from"node:fs";import{homedir as WM}from"node:os";import{join as qM}from"node:path";import{createReadStream as wx,existsSync as Jj}from"node:fs";import{createInterface as vx}from"node:readline";var Mj=new Set(["low","medium","high","xhigh","max"]),Lj=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;function ea(e){if(!e)return null;let t=null;for(let n of e.matchAll(Lj)){let r=n[1].toLowerCase();Mj.has(r)&&(t=r)}return t}a(ea,"detectEffortLevel");var hx=["mcp__maind__","mcp__plugin_maind_maind__"];function wr(e){for(let t of hx)if(e.startsWith(t)){let n=e.slice(t.length);return n.length>0?n:null}return null}a(wr,"maindToolName");import{createReadStream as Pj,existsSync as Fj,readdirSync as Uj}from"node:fs";import{basename as _x,dirname as Bj,join as gx}from"node:path";import{createInterface as Kj}from"node:readline";var Nn="main",Gj="<synthetic>",Hj=new Set(["get_session_analysis","get_session_cost_context"]),Vj=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,bx=32;function kx(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!Vj.test(n)||e.ids.includes(n)||e.ids.length>=bx||e.ids.push(n)}a(kx,"addCoordinationId");function Wj(e,t){if(Array.isArray(t))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let o=wr(r.name);if(o===null||Hj.has(o))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?kx(e,i.session_id):o==="announce_session"&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}a(Wj,"noteCoordinationUse");function qj(e){if(typeof e=="string")return e;if(!Array.isArray(e))return"";let t="";for(let n of e)n&&typeof n=="object"&&typeof n.text=="string"&&(t+=n.text);return t}a(qj,"resultText");function zj(e,t){if(!(e.pendingAnnounce.size===0||!Array.isArray(t)))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_result"||typeof r.tool_use_id!="string"||!e.pendingAnnounce.delete(r.tool_use_id))continue;let o=qj(r.content),i=null;try{let s=JSON.parse(o);s&&s.ok===!0&&(i=s.session_id)}catch{let s=/"session_id"\s*:\s*"([0-9a-f-]{36})"/i.exec(o);i=s?s[1]:null}kx(e,i)}}a(zj,"noteAnnounceResult");var Yj={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};function vr(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}a(vr,"num");function Xj(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let o=Yj[r.name];if(!o||!r.input||typeof r.input!="object")continue;let i=r.input[o];typeof i=="string"&&i.length>0&&t.push(i)}return t}a(Xj,"editedPathsOf");function ta(e){let t=_x(e).replace(/\.jsonl$/,""),n=gx(Bj(e),t,"subagents"),r;try{r=Uj(n)}catch{return[]}return r.filter(o=>o.endsWith(".jsonl")).sort().map(o=>gx(n,o))}a(ta,"subagentFilesOf");async function yx(e,t,n,r,o,i){Fj(e)&&await new Promise(s=>{let l=Pj(e,{encoding:"utf-8"}),c=Kj({input:l}),u=0;c.on("line",d=>{u++;let f=d.trim();if(!f)return;let p;try{p=JSON.parse(f)}catch{return}if(p.message?.role==="user"){zj(i,p.message.content);return}if(p.message?.role!=="assistant")return;Wj(i,p.message.content);let h=typeof p.message.id=="string"&&p.message.id?p.message.id:null,_=typeof p.requestId=="string"&&p.requestId?p.requestId:null,b=h??_??`${e}#${u}`,g=Xj(p.message.content),y=r.get(b);if(y){for(let w of g)y.edited_paths.includes(w)||y.edited_paths.push(w);return}if(n.has(b))return;n.add(b);let k=p.message.usage??{},R=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,x=typeof p.message.model=="string"&&p.message.model?p.message.model:"",v={ts:Number.isFinite(R)?R:0,model:x||"<unknown>",synthetic:x===Gj,input_tokens:vr(k.input_tokens),output_tokens:vr(k.output_tokens),cache_read_tokens:vr(k.cache_read_input_tokens),cache_creation_tokens:vr(k.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(vr(k.cache_creation?.ephemeral_1h_input_tokens),vr(k.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:g,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(b,v),o.push(v)}),c.on("close",()=>s()),c.on("error",()=>s()),l.on("error",()=>s())})}a(yx,"readStream");function jd(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let o=e[r];o.ts>0?n=o.ts:n>0&&(o.ts=n)}}a(jd,"fillTimestamps");async function Lo(e){let t=new Set,n=new Map,r=[],o=e?ta(e):[],i={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:o,coordination_ids:[]};let s=[];await yx(e,Nn,t,n,s,i),jd(s),r.push(...s);for(let l of o){let c=[],u=_x(l).replace(/\.jsonl$/,"");i.pendingAnnounce.clear(),await yx(l,u,t,n,c,i),jd(c);for(let d of c)d.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:o,coordination_ids:i.ids}}a(Lo,"collectTurns");var xx="2026-10-01",Zj=/(\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,Qj=/(\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,eM=/(\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,tM="[Request interrupted by user",nM="The user doesn't want to proceed with this tool use",rM=.7,xr={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};function oM(e,t,n,r,o){let i=`${n?"s":"m"}:${t}`,s=e.get(i);if(!s){e.set(i,{model:t,turns:1,output_tokens:r,first_ts:o,last_ts:o,sidechain:n});return}s.turns++,s.output_tokens+=r,o>0&&((s.first_ts===0||o<s.first_ts)&&(s.first_ts=o),o>s.last_ts&&(s.last_ts=o))}a(oM,"bumpModel");function na(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}a(na,"asBlocks");function iM(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
472
- `)}a(iM,"textOf");function sM(e,t){let n=a(c=>new Set(c.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),o=n(t);if(r.size<3||o.size<3)return!1;let[i,s]=r.size<=o.size?[r,o]:[o,r],l=0;for(let c of i)s.has(c)&&l++;return l/i.size>=.8}a(sM,"isRepeat");function aM(e,t,n){return Zj.test(e)?{polarity:-1,magnitude:xr.rework,kind:"rework"}:n&&Qj.test(e)?{polarity:-1,magnitude:xr.correction,kind:"correction"}:eM.test(e)?{polarity:1,magnitude:xr.acceptance,kind:"acceptance"}:t!==null&&sM(t,e)?{polarity:-1,magnitude:xr.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}a(aM,"classifyGenuine");function lM(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:xx,behaviour_measured:!0}}a(lM,"emptyAnalysis");async function cM(e,t){for(let n of ta(e))await new Promise(r=>{let o=vx({input:wx(n,{encoding:"utf-8"})});o.on("line",i=>{let s=i.trim();if(!s)return;let l;try{l=JSON.parse(s)}catch{return}if(l.message?.role==="assistant")for(let c of na(l.message?.content)){if(c.type!=="tool_use"||typeof c.name!="string")continue;let u=wr(c.name);u!==null&&(t.maind_tool_calls??={},t.maind_tool_calls[u]=(t.maind_tool_calls[u]??0)+1)}}),o.on("error",()=>r()),o.on("close",()=>r())})}a(cM,"tallySubagentMaindCalls");async function Md(e,t={}){let n=lM("");if(!e||!Jj(e))return n;let r=t.turns??(await Lo(e)).turns;for(let h of r)n.input_tokens+=h.input_tokens,n.output_tokens+=h.output_tokens,n.cache_read_tokens+=h.cache_read_tokens,n.cache_creation_tokens+=h.cache_creation_tokens,h.sidechain||n.assistant_turns++;let o=[],i=new Map,s=null,l=!1,c=null;await new Promise(h=>{let _=wx(e,{encoding:"utf-8"}),b=vx({input:_}),g=a(y=>{let k=y.trim();if(!k)return;let R;try{R=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let U=R.sessionId??R.session_id;typeof U=="string"&&U&&(n.session_id=U)}R.type==="ai-title"&&typeof R.aiTitle=="string"&&R.aiTitle&&(n.ai_title=R.aiTitle),typeof R.slug=="string"&&R.slug&&(n.session_slug=R.slug);let x=R.message?.role,v=R.isSidechain===!0;if(x==="assistant")for(let U of na(R.message?.content)){if(U.type!=="tool_use"||typeof U.name!="string")continue;let F=wr(U.name);F!==null&&(n.maind_tool_calls??={},n.maind_tool_calls[F]=(n.maind_tool_calls[F]??0)+1)}if(v)return;if(x==="assistant"){let U=na(R.message?.content),F=!1;for(let W of U)W.type==="tool_use"&&(n.tool_calls++,F=!0,W.name==="AskUserQuestion"&&n.agent_questions++);l=F;return}if(x!=="user")return;let w=na(R.message?.content),A=iM(w);if(A.includes(tM)){n.interrupts++,o.push({polarity:-1,magnitude:xr.interrupt,kind:"interrupt"});return}if(w.some(U=>U.type==="tool_result"&&U.is_error===!0&&typeof U.content=="string"&&U.content.includes(nM))){n.tool_denials++,o.push({polarity:-1,magnitude:xr.denial,kind:"denial"});return}if(w.some(U=>U.type==="tool_result")||!A.trim())return;n.user_turns++,n.user_chars+=A.length;let S=ea(A);S&&(s=S);let O=aM(A,c,l);c=A,O.kind==="correction"?n.corrections++:O.kind==="rework"?n.reworks++:O.kind==="repeat"?n.repeated_instructions++:O.kind==="acceptance"&&n.acceptances++,O.polarity!==0&&o.push(O),l=!1},"processLine");b.on("line",y=>{try{g(y)}catch{}}),b.on("close",()=>h()),b.on("error",()=>h()),_.on("error",()=>h())}),await cM(e,n),n.effort_at_end=s;for(let h of r)h.synthetic||h.model==="<unknown>"||oM(i,h.model,h.sidechain,h.output_tokens,h.ts);n.model_mix=[...i.values()].sort((h,_)=>h.first_ts-_.first_ts||h.model.localeCompare(_.model)),n.user_token_estimate=Math.round(n.user_chars/4);let u=n.user_token_estimate+n.output_tokens;n.human_share=u>0?Number((n.user_token_estimate/u).toFixed(4)):0;let d=0,f=0,p=[];return o.forEach((h,_)=>{h.polarity>0?n.reactions_pos++:h.polarity<0&&n.reactions_neg++,d=d*rM+h.polarity*h.magnitude;let b=Number(d.toFixed(3));p.push({t:_,value:b,...h.kind!=="neutral"?{kind:h.kind}:{}}),f+=b,_>0&&o[_-1].polarity<0&&h.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=p,n.momentum_final=p.length?p[p.length-1].value:0,n.momentum_auc=Number(f.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}a(Md,"analyzeSession");function Sx(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}a(Sx,"parseIngestResponse");function Rx(e,t,n,r="unknown",o){let i={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...n?.coordination_session_ids&&n.coordination_session_ids.length>0?{coordination_session_ids:[...n.coordination_session_ids]}:{},...o?{cost_slices:o.slices,cost_context_ok:o.context_ok}:{}}};if(t&&t.started_at)if(n){let{coordination_session_ids:s,...l}=n;i.session_span={...t,...l}}else i.session_span=t;return i}a(Rx,"ingestBody");function Ex(e){let t={"content-type":"application/json",authorization:`Bearer ${e.apiKey}`};return e.deviceId&&(t["x-maind-device-id"]=e.deviceId),t}a(Ex,"ingestHeaders");async function Sr(e,t,n,r,o="unknown",i){try{let s=await fetch(e.endpoint,{method:"POST",headers:Ex(e),body:JSON.stringify(Rx(t,n,r,o,i))});if(!s.ok){let c=await s.text().catch(()=>"");return{ok:!1,inserted:0,status:s.status,error:c.slice(0,500)}}let l=Sx(await s.json().catch(()=>null));return{ok:!0,inserted:l.analyticsStored?1:0,spanStored:l.spanStored,...l.slicesStored!==null?{slicesStored:l.slicesStored,slicesReason:l.slicesReason,slicesCount:l.slicesCount}:{},status:s.status}}catch(s){return{ok:!1,inserted:0,error:s instanceof Error?s.message:String(s)}}}a(Sr,"postSessionAnalytics");import{mkdirSync as O3,readFileSync as mM,renameSync as N3,writeFileSync as D3}from"node:fs";import{dirname as M3,isAbsolute as Kd,sep as Gd}from"node:path";import{isAbsolute as Ax,relative as uM,resolve as Tx,sep as Cx}from"node:path";var oa=[2e5,272e3];function Ix(e){return e>oa[1]?"above_272k":e>oa[0]?"band_200k_272k":"standard"}a(Ix,"contextTierOf");function $x(e){return e.trim().replace(/\[[^\]]*\]$/,"")}a($x,"normalizeModelId");var dM=oa[0],Ld=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ra(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}a(ra,"msOf");function Fd(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=a(s=>{if(!Array.isArray(s))return[];let l=[];for(let c of s){if(!c||typeof c!="object")continue;let u=c,d=ra(u.from);typeof u.object_id!="string"||!Ld.test(u.object_id)||d===null||l.push({object_id:u.object_id.toLowerCase(),from:d,to:ra(u.to)})}return l},"windows"),o=[];if(Array.isArray(n.claims))for(let s of n.claims){if(!s||typeof s!="object")continue;let l=s,c=ra(l.from);typeof l.path_prefix!="string"||c===null||o.push({path_prefix:l.path_prefix,from:c,to:ra(l.to)})}let i=[];if(Array.isArray(n.anchors))for(let s of n.anchors){if(!s||typeof s!="object")continue;let l=s;typeof l.object_id!="string"||!Ld.test(l.object_id)||typeof l.path_prefix=="string"&&i.push({object_id:l.object_id.toLowerCase(),path_prefix:l.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Ld.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:o,anchors:i}}a(Fd,"parseCostContext");function ia(e,t){if(!Ax(e))return null;let n=uM(Tx(t),Tx(e));return!n||n==="."||n.startsWith("..")||Ax(n)?null:Cx==="/"?n:n.split(Cx).join("/")}a(ia,"toRepoRelative");function fM(e,t){return t===""||e===t||e.startsWith(t+"/")}a(fM,"underPrefix");function Ud(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}a(Ud,"prefixesOverlap");function Ox(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}a(Ox,"sortedAnchors");function Bd(e,t){for(let n of Ox(t))if(fM(e,n.path_prefix))return n.object_id;return null}a(Bd,"anchorFor");function pM(e,t){for(let n of Ox(t))if(Ud(e,n.path_prefix))return n.object_id;return null}a(pM,"bestAnchorOverlapping");function Pd(e,t){return e>=t.from&&(t.to===null||e<t.to)}a(Pd,"inWindow");function Nx(e,t,n,r){let o=e.ts,i=r?.anchors??[],s=t.map(l=>Bd(l,i)).filter(l=>l!==null);if(r&&o>0){let l=r.leases.filter(d=>Pd(o,d));if(l.length)return l.sort((d,f)=>f.from-d.from||d.object_id.localeCompare(f.object_id)),{object_id:l[0].object_id,source:"lease"};let c=r.bindings.filter(d=>Pd(o,d));if(c.length)return{object_id:(c.find(f=>s.includes(f.object_id))??c.find(f=>n!==null&&f.object_id===n.object_id)??[...c].sort((f,p)=>f.object_id.localeCompare(p.object_id))[0]).object_id,source:"binding"};let u=r.claims.filter(d=>Pd(o,d));if(u.length){let d=t[0]??n?.rel??null,f=(d===null?u:u.filter(p=>Ud(p.path_prefix,d))).sort((p,h)=>h.path_prefix.length-p.path_prefix.length);for(let p of f){let h=pM(p.path_prefix,i);if(h)return{object_id:h,source:"claim"}}}}return s.length?{object_id:s[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}a(Nx,"assignTurn");function sa(e,t,n){let r=t?.anchors??[],o=n.repoRoot,i=n.relativize??(o?g=>ia(g,o):null),s=a(g=>{if(!i)return[];let y=[];for(let k of g.edited_paths){let R=i(k);R!==null&&!y.includes(R)&&y.push(R)}return y},"relOf"),l=a(g=>{for(let y of g){let k=Bd(y,r);if(k)return{object_id:k,rel:y}}return null},"firstAnchoredEdit"),c=new Map;for(let g of e){let y=c.get(g.stream)??[];y.push(g),c.set(g.stream,y)}let u=[...c.entries()].sort(([g],[y])=>g===Nn?-1:y===Nn?1:0),d=[],f=a(g=>{let y=null;for(let k of d){if(k.ts>g&&g>0)break;y=k.seg}return y},"mainSegmentAt"),p=new Map;for(let[g,y]of u){let k=y.map((x,v)=>({t:x,i:v,rels:s(x)})).sort((x,v)=>x.t.ts-v.t.ts||x.i-v.i),R=null;for(let x of k){let v=l(x.rels);if(v){R=v;break}}!R&&g!==Nn&&k.length&&(R=f(k[0].t.ts));for(let x of k){let v=l(x.rels);v&&(R=v),g===Nn&&d.push({ts:x.t.ts,seg:R});let w=x.t;if(w.input_tokens+w.output_tokens+w.cache_read_tokens+w.cache_creation_tokens===0)continue;let C=Nx(w,x.rels,R,t),S=Ix(w.input_tokens+w.cache_read_tokens+w.cache_creation_tokens),O=$x(w.model),U=`${C.object_id??""}|${C.source}|${O}|${S}`,F=p.get(U);F||(F={object_id:C.object_id,attribution_source:C.source,model:O,context_tier:S,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},p.set(U,F)),F.input_tokens+=w.input_tokens,F.output_tokens+=w.output_tokens,F.cache_read_tokens+=w.cache_read_tokens,F.cache_creation_tokens+=w.cache_creation_tokens,F.cache_creation_1h_tokens+=w.cache_creation_1h_tokens,F.turns+=1,w.ts>0&&((F.firstMs===0||w.ts<F.firstMs)&&(F.firstMs=w.ts),w.ts>F.lastMs&&(F.lastMs=w.ts))}}let h=n.nowMs??Date.now(),_=[];for(let g of p.values()){let{firstMs:y,lastMs:k,...R}=g;R.first_ts=new Date(y>0?y:h).toISOString(),R.last_ts=new Date(k>0?k:h).toISOString(),_.push(R)}let b={lease:0,binding:1,claim:2,path:3,none:4};return _.sort((g,y)=>b[g.attribution_source]-b[y.attribution_source]||(g.object_id??"").localeCompare(y.object_id??"")||g.model.localeCompare(y.model)||g.context_tier.localeCompare(y.context_tier)),_}a(sa,"sliceSession");function hM(e){let t=e.split(Gd).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}a(hM,"dirOf");function gM(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}a(gM,"within");function aa(e){let t=new Map,n=a(d=>{let f=t.get(d);if(f!==void 0)return f;let p=e.keyOfRoot(d);return t.set(d,p),p},"keyOf"),r=new Map,o=a(d=>{let f=r.get(d);if(f!==void 0)return f;let p=e.gitRoot(d);return r.set(d,p),p},"gitRoot"),i=new Map,s=[...(e.known??new Map).entries()].filter(([d])=>Kd(d)).sort((d,f)=>f[0].length-d[0].length),l=new Map,c=a(d=>{if(!e.isDir)return null;let f=l.get(d);if(f!==void 0)return f;let p=u(d);return l.set(d,p),p},"byConvention"),u=a(d=>{if(!e.isDir)return null;let f=d.split("/");for(let p=2;p<f.length+1;p++){let h=f.slice(0,p).join("/");if(!h||e.isDir(h))continue;let _=f.slice(0,p-1).join("/")||"/",b=f[p-1];for(let g=b.lastIndexOf("-");g>0;g=b.lastIndexOf("-",g-1)){let y=`${_==="/"?"":_}/${b.slice(0,g)}`;if(e.isDir(y)&&o(y)===y)return{root:h,key:n(y)}}return null}return null},"conventionRoot");return{of(d){if(!Kd(d))return null;let f=d.split(Gd).join("/"),p=hM(f),h=o(p);if(h){let _=n(h);return i.set(h,_),{root:h,key:_}}for(let[_,b]of s)if(!(!gM(f,_)||f===_)&&!(e.isDir&&e.isDir(_)))return{root:_,key:b};return c(p)},seenLive(){return[...i.entries()].map(([d,f])=>({root:d,key:f}))}}}a(aa,"createCheckoutResolver");function la(e,t){let n=new Map;for(let s of e){let l=new Map;for(let c of s.edited_paths){let u=t.of(c);!u||!u.key||l.set(u.key,Math.max(l.get(u.key)??0,u.root.length))}for(let[c,u]of l){let d=n.get(c)??{turns:0,depth:0};d.turns+=1,d.depth=Math.max(d.depth,u),n.set(c,d)}}let r=null,o=0,i=0;for(let[s,l]of n)(l.turns>o||l.turns===o&&(l.depth>i||l.depth===i&&r!==null&&s<r))&&(r=s,o=l.turns,i=l.depth);return r}a(la,"dominantProjectKey");function ca(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:ia(n.split(Gd).join("/"),r.root)}}a(ca,"relativizerFor");var yM=90*24*60*60*1e3,P3=60*60*1e3,_M=/^[a-f0-9]{64}$/;function bM(e){try{let t=JSON.parse(mM(e,"utf8"));if(t&&t.v===1&&t.checkouts&&typeof t.checkouts=="object")return{v:1,checkouts:t.checkouts}}catch{}return{v:1,checkouts:{}}}a(bM,"readMemory");function Hd(e){let t=new Map,n=bM(e);for(let[r,o]of Object.entries(n.checkouts)){if(!Kd(r)||!o||typeof o!="object")continue;let i=typeof o.project_key=="string"&&_M.test(o.project_key)?o.project_key:null;t.set(r,i)}return t}a(Hd,"loadCheckoutMemory");import{createReadStream as kM,existsSync as wM}from"node:fs";import{createInterface as vM}from"node:readline";import{homedir as Dx}from"node:os";import{isAbsolute as xM,join as ua}from"node:path";var jx=ua(Dx(),".codex","sessions");function Po(e=process.env,t=Dx()){let n=e.CODEX_HOME?.trim();return n&&xM(n)?ua(n,"sessions"):ua(t,".codex","sessions")}a(Po,"codexSessionsDir");async function Fo(e=jx){let{readdir:t}=await import("node:fs/promises"),n=[],r=a(async o=>{let i;try{i=await t(o,{withFileTypes:!0})}catch{return}for(let s of i){let l=ua(o,s.name);s.isDirectory()?await r(l):s.isFile()&&s.name.endsWith(".jsonl")&&n.push(l)}},"walk");return await r(e),n.sort()}a(Fo,"listCodexSessions");var Vd=a(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,"num");function Mx(e){let t=Vd(e.cached_input_tokens),n=Vd(e.input_tokens);return{input_tokens:Math.max(0,n-t),cache_read_tokens:t,output_tokens:Vd(e.output_tokens),cache_creation_tokens:0,cache_creation_1h_tokens:0}}a(Mx,"mapCodexUsage");var Wd=/^\*\*\* (?:Update|Add|Delete) File: (.+)$/gm;function SM(e){if(typeof e!="string"||e.length===0)return[];let t=[];Wd.lastIndex=0;for(let n=Wd.exec(e);n!==null;n=Wd.exec(e)){let r=n[1]?.trim();r&&!t.includes(r)&&t.push(r)}return t}a(SM,"codexEditedPaths");async function Uo(e){if(!e||!wM(e))return{turns:[],skipped:0};let t=[],n=0,r=null,o=null,i=[];return await new Promise(s=>{let l=vM({input:kM(e,{encoding:"utf-8"})});l.on("line",u=>{let d=u.trim();if(!d)return;let f;try{f=JSON.parse(d)}catch{return}let p=f.payload??{};if(f.type==="session_meta"||f.type==="turn_context"){typeof p.cwd=="string"&&p.cwd&&(o=p.cwd),typeof p.model=="string"&&p.model&&(r=p.model);return}if(p.name==="apply_patch"){for(let g of SM(p.input))i.includes(g)||i.push(g);return}if(p.type!=="token_count")return;let h=p.info?.last_token_usage;if(!h){n++;return}let _=Mx(h);if(_.input_tokens+_.output_tokens+_.cache_read_tokens===0){n++;return}let b=f.timestamp?Date.parse(f.timestamp):Number.NaN;t.push({ts:Number.isFinite(b)?b:0,model:r??"<unknown>",synthetic:!1,..._,sidechain:!1,stream:"main",edited_paths:i,cwd:o}),i=[]});let c=a(()=>s({turns:t,skipped:n}),"done");l.on("close",c),l.on("error",c)})}a(Uo,"collectCodexTurns");var Lx="2026-10-11",RM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,EM="maind",AM=new Set(["function_call","custom_tool_call","web_search_call"]);function Px(e){let t={user_turns:0,assistant_turns:0,tool_calls:0,session_id:null,lines_seen:e.length,maind_tool_calls:{},coordination_ids:[]};for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=r.payload??{},i=typeof o.type=="string"?o.type:"";if(r.type==="session_meta"&&!t.session_id){let s=typeof o.session_id=="string"&&o.session_id?o.session_id:o.id;typeof s=="string"&&s&&(t.session_id=s)}r.type==="event_msg"&&(i==="user_message"?t.user_turns++:i==="agent_message"?t.assistant_turns++:i==="mcp_tool_call_end"&&TM(t,o.invocation)),r.type==="response_item"&&AM.has(i)&&t.tool_calls++}return t}a(Px,"countCodexRecords");function TM(e,t){if(!t||typeof t!="object")return;let n=t;if(n.server!==EM||typeof n.tool!="string"||!n.tool)return;e.maind_tool_calls[n.tool]=(e.maind_tool_calls[n.tool]??0)+1;let r=n.arguments;if(!r||typeof r!="object")return;let o=r.session_id;if(typeof o!="string"||!RM.test(o.trim()))return;let i=o.trim().toLowerCase();e.coordination_ids.includes(i)||e.coordination_ids.push(i)}a(TM,"countMaindCall");async function qd(e,t={}){let n=t.turns??(await Uo(e)).turns,r=[],{readFile:o}=await import("node:fs/promises"),i;try{i=await o(e,"utf-8")}catch{return null}for(let u of i.split(`
472
+ `)}a(iM,"textOf");function sM(e,t){let n=a(c=>new Set(c.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),o=n(t);if(r.size<3||o.size<3)return!1;let[i,s]=r.size<=o.size?[r,o]:[o,r],l=0;for(let c of i)s.has(c)&&l++;return l/i.size>=.8}a(sM,"isRepeat");function aM(e,t,n){return Zj.test(e)?{polarity:-1,magnitude:xr.rework,kind:"rework"}:n&&Qj.test(e)?{polarity:-1,magnitude:xr.correction,kind:"correction"}:eM.test(e)?{polarity:1,magnitude:xr.acceptance,kind:"acceptance"}:t!==null&&sM(t,e)?{polarity:-1,magnitude:xr.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}a(aM,"classifyGenuine");function lM(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:xx,behaviour_measured:!0}}a(lM,"emptyAnalysis");async function cM(e,t){for(let n of ta(e))await new Promise(r=>{let o=vx({input:wx(n,{encoding:"utf-8"})});o.on("line",i=>{let s=i.trim();if(!s)return;let l;try{l=JSON.parse(s)}catch{return}if(l.message?.role==="assistant")for(let c of na(l.message?.content)){if(c.type!=="tool_use"||typeof c.name!="string")continue;let u=wr(c.name);u!==null&&(t.maind_tool_calls??={},t.maind_tool_calls[u]=(t.maind_tool_calls[u]??0)+1)}}),o.on("error",()=>r()),o.on("close",()=>r())})}a(cM,"tallySubagentMaindCalls");async function Md(e,t={}){let n=lM("");if(!e||!Jj(e))return n;let r=t.turns??(await Lo(e)).turns;for(let h of r)n.input_tokens+=h.input_tokens,n.output_tokens+=h.output_tokens,n.cache_read_tokens+=h.cache_read_tokens,n.cache_creation_tokens+=h.cache_creation_tokens,h.sidechain||n.assistant_turns++;let o=[],i=new Map,s=null,l=!1,c=null;await new Promise(h=>{let _=wx(e,{encoding:"utf-8"}),b=vx({input:_}),g=a(y=>{let k=y.trim();if(!k)return;let R;try{R=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let U=R.sessionId??R.session_id;typeof U=="string"&&U&&(n.session_id=U)}R.type==="ai-title"&&typeof R.aiTitle=="string"&&R.aiTitle&&(n.ai_title=R.aiTitle),typeof R.slug=="string"&&R.slug&&(n.session_slug=R.slug);let x=R.message?.role,v=R.isSidechain===!0;if(x==="assistant")for(let U of na(R.message?.content)){if(U.type!=="tool_use"||typeof U.name!="string")continue;let F=wr(U.name);F!==null&&(n.maind_tool_calls??={},n.maind_tool_calls[F]=(n.maind_tool_calls[F]??0)+1)}if(v)return;if(x==="assistant"){let U=na(R.message?.content),F=!1;for(let W of U)W.type==="tool_use"&&(n.tool_calls++,F=!0,W.name==="AskUserQuestion"&&n.agent_questions++);l=F;return}if(x!=="user")return;let w=na(R.message?.content),A=iM(w);if(A.includes(tM)){n.interrupts++,o.push({polarity:-1,magnitude:xr.interrupt,kind:"interrupt"});return}if(w.some(U=>U.type==="tool_result"&&U.is_error===!0&&typeof U.content=="string"&&U.content.includes(nM))){n.tool_denials++,o.push({polarity:-1,magnitude:xr.denial,kind:"denial"});return}if(w.some(U=>U.type==="tool_result")||!A.trim())return;n.user_turns++,n.user_chars+=A.length;let S=ea(A);S&&(s=S);let O=aM(A,c,l);c=A,O.kind==="correction"?n.corrections++:O.kind==="rework"?n.reworks++:O.kind==="repeat"?n.repeated_instructions++:O.kind==="acceptance"&&n.acceptances++,O.polarity!==0&&o.push(O),l=!1},"processLine");b.on("line",y=>{try{g(y)}catch{}}),b.on("close",()=>h()),b.on("error",()=>h()),_.on("error",()=>h())}),await cM(e,n),n.effort_at_end=s;for(let h of r)h.synthetic||h.model==="<unknown>"||oM(i,h.model,h.sidechain,h.output_tokens,h.ts);n.model_mix=[...i.values()].sort((h,_)=>h.first_ts-_.first_ts||h.model.localeCompare(_.model)),n.user_token_estimate=Math.round(n.user_chars/4);let u=n.user_token_estimate+n.output_tokens;n.human_share=u>0?Number((n.user_token_estimate/u).toFixed(4)):0;let d=0,f=0,p=[];return o.forEach((h,_)=>{h.polarity>0?n.reactions_pos++:h.polarity<0&&n.reactions_neg++,d=d*rM+h.polarity*h.magnitude;let b=Number(d.toFixed(3));p.push({t:_,value:b,...h.kind!=="neutral"?{kind:h.kind}:{}}),f+=b,_>0&&o[_-1].polarity<0&&h.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=p,n.momentum_final=p.length?p[p.length-1].value:0,n.momentum_auc=Number(f.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}a(Md,"analyzeSession");function Sx(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}a(Sx,"parseIngestResponse");function Rx(e,t,n,r="unknown",o){let i={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...n?.coordination_session_ids&&n.coordination_session_ids.length>0?{coordination_session_ids:[...n.coordination_session_ids]}:{},...o?{cost_slices:o.slices,cost_context_ok:o.context_ok}:{}}};if(t&&t.started_at)if(n){let{coordination_session_ids:s,...l}=n;i.session_span={...t,...l}}else i.session_span=t;return i}a(Rx,"ingestBody");function Ex(e){let t={"content-type":"application/json",authorization:`Bearer ${e.apiKey}`};return e.deviceId&&(t["x-maind-device-id"]=e.deviceId),t}a(Ex,"ingestHeaders");async function Sr(e,t,n,r,o="unknown",i){try{let s=await fetch(e.endpoint,{method:"POST",headers:Ex(e),body:JSON.stringify(Rx(t,n,r,o,i))});if(!s.ok){let c=await s.text().catch(()=>"");return{ok:!1,inserted:0,status:s.status,error:c.slice(0,500)}}let l=Sx(await s.json().catch(()=>null));return{ok:!0,inserted:l.analyticsStored?1:0,spanStored:l.spanStored,...l.slicesStored!==null?{slicesStored:l.slicesStored,slicesReason:l.slicesReason,slicesCount:l.slicesCount}:{},status:s.status}}catch(s){return{ok:!1,inserted:0,error:s instanceof Error?s.message:String(s)}}}a(Sr,"postSessionAnalytics");import{mkdirSync as K3,readFileSync as mM,renameSync as G3,writeFileSync as H3}from"node:fs";import{dirname as W3,isAbsolute as Kd,sep as Gd}from"node:path";import{isAbsolute as Ax,relative as uM,resolve as Tx,sep as Cx}from"node:path";var oa=[2e5,272e3];function Ix(e){return e>oa[1]?"above_272k":e>oa[0]?"band_200k_272k":"standard"}a(Ix,"contextTierOf");function $x(e){return e.trim().replace(/\[[^\]]*\]$/,"")}a($x,"normalizeModelId");var dM=oa[0],Ld=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ra(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}a(ra,"msOf");function Fd(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=a(s=>{if(!Array.isArray(s))return[];let l=[];for(let c of s){if(!c||typeof c!="object")continue;let u=c,d=ra(u.from);typeof u.object_id!="string"||!Ld.test(u.object_id)||d===null||l.push({object_id:u.object_id.toLowerCase(),from:d,to:ra(u.to)})}return l},"windows"),o=[];if(Array.isArray(n.claims))for(let s of n.claims){if(!s||typeof s!="object")continue;let l=s,c=ra(l.from);typeof l.path_prefix!="string"||c===null||o.push({path_prefix:l.path_prefix,from:c,to:ra(l.to)})}let i=[];if(Array.isArray(n.anchors))for(let s of n.anchors){if(!s||typeof s!="object")continue;let l=s;typeof l.object_id!="string"||!Ld.test(l.object_id)||typeof l.path_prefix=="string"&&i.push({object_id:l.object_id.toLowerCase(),path_prefix:l.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Ld.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:o,anchors:i}}a(Fd,"parseCostContext");function ia(e,t){if(!Ax(e))return null;let n=uM(Tx(t),Tx(e));return!n||n==="."||n.startsWith("..")||Ax(n)?null:Cx==="/"?n:n.split(Cx).join("/")}a(ia,"toRepoRelative");function fM(e,t){return t===""||e===t||e.startsWith(t+"/")}a(fM,"underPrefix");function Ud(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}a(Ud,"prefixesOverlap");function Ox(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}a(Ox,"sortedAnchors");function Bd(e,t){for(let n of Ox(t))if(fM(e,n.path_prefix))return n.object_id;return null}a(Bd,"anchorFor");function pM(e,t){for(let n of Ox(t))if(Ud(e,n.path_prefix))return n.object_id;return null}a(pM,"bestAnchorOverlapping");function Pd(e,t){return e>=t.from&&(t.to===null||e<t.to)}a(Pd,"inWindow");function Nx(e,t,n,r){let o=e.ts,i=r?.anchors??[],s=t.map(l=>Bd(l,i)).filter(l=>l!==null);if(r&&o>0){let l=r.leases.filter(d=>Pd(o,d));if(l.length)return l.sort((d,f)=>f.from-d.from||d.object_id.localeCompare(f.object_id)),{object_id:l[0].object_id,source:"lease"};let c=r.bindings.filter(d=>Pd(o,d));if(c.length)return{object_id:(c.find(f=>s.includes(f.object_id))??c.find(f=>n!==null&&f.object_id===n.object_id)??[...c].sort((f,p)=>f.object_id.localeCompare(p.object_id))[0]).object_id,source:"binding"};let u=r.claims.filter(d=>Pd(o,d));if(u.length){let d=t[0]??n?.rel??null,f=(d===null?u:u.filter(p=>Ud(p.path_prefix,d))).sort((p,h)=>h.path_prefix.length-p.path_prefix.length);for(let p of f){let h=pM(p.path_prefix,i);if(h)return{object_id:h,source:"claim"}}}}return s.length?{object_id:s[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}a(Nx,"assignTurn");function sa(e,t,n){let r=t?.anchors??[],o=n.repoRoot,i=n.relativize??(o?g=>ia(g,o):null),s=a(g=>{if(!i)return[];let y=[];for(let k of g.edited_paths){let R=i(k);R!==null&&!y.includes(R)&&y.push(R)}return y},"relOf"),l=a(g=>{for(let y of g){let k=Bd(y,r);if(k)return{object_id:k,rel:y}}return null},"firstAnchoredEdit"),c=new Map;for(let g of e){let y=c.get(g.stream)??[];y.push(g),c.set(g.stream,y)}let u=[...c.entries()].sort(([g],[y])=>g===Nn?-1:y===Nn?1:0),d=[],f=a(g=>{let y=null;for(let k of d){if(k.ts>g&&g>0)break;y=k.seg}return y},"mainSegmentAt"),p=new Map;for(let[g,y]of u){let k=y.map((x,v)=>({t:x,i:v,rels:s(x)})).sort((x,v)=>x.t.ts-v.t.ts||x.i-v.i),R=null;for(let x of k){let v=l(x.rels);if(v){R=v;break}}!R&&g!==Nn&&k.length&&(R=f(k[0].t.ts));for(let x of k){let v=l(x.rels);v&&(R=v),g===Nn&&d.push({ts:x.t.ts,seg:R});let w=x.t;if(w.input_tokens+w.output_tokens+w.cache_read_tokens+w.cache_creation_tokens===0)continue;let C=Nx(w,x.rels,R,t),S=Ix(w.input_tokens+w.cache_read_tokens+w.cache_creation_tokens),O=$x(w.model),U=`${C.object_id??""}|${C.source}|${O}|${S}`,F=p.get(U);F||(F={object_id:C.object_id,attribution_source:C.source,model:O,context_tier:S,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},p.set(U,F)),F.input_tokens+=w.input_tokens,F.output_tokens+=w.output_tokens,F.cache_read_tokens+=w.cache_read_tokens,F.cache_creation_tokens+=w.cache_creation_tokens,F.cache_creation_1h_tokens+=w.cache_creation_1h_tokens,F.turns+=1,w.ts>0&&((F.firstMs===0||w.ts<F.firstMs)&&(F.firstMs=w.ts),w.ts>F.lastMs&&(F.lastMs=w.ts))}}let h=n.nowMs??Date.now(),_=[];for(let g of p.values()){let{firstMs:y,lastMs:k,...R}=g;R.first_ts=new Date(y>0?y:h).toISOString(),R.last_ts=new Date(k>0?k:h).toISOString(),_.push(R)}let b={lease:0,binding:1,claim:2,path:3,none:4};return _.sort((g,y)=>b[g.attribution_source]-b[y.attribution_source]||(g.object_id??"").localeCompare(y.object_id??"")||g.model.localeCompare(y.model)||g.context_tier.localeCompare(y.context_tier)),_}a(sa,"sliceSession");function hM(e){let t=e.split(Gd).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}a(hM,"dirOf");function gM(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}a(gM,"within");function aa(e){let t=new Map,n=a(d=>{let f=t.get(d);if(f!==void 0)return f;let p=e.keyOfRoot(d);return t.set(d,p),p},"keyOf"),r=new Map,o=a(d=>{let f=r.get(d);if(f!==void 0)return f;let p=e.gitRoot(d);return r.set(d,p),p},"gitRoot"),i=new Map,s=[...(e.known??new Map).entries()].filter(([d])=>Kd(d)).sort((d,f)=>f[0].length-d[0].length),l=new Map,c=a(d=>{if(!e.isDir)return null;let f=l.get(d);if(f!==void 0)return f;let p=u(d);return l.set(d,p),p},"byConvention"),u=a(d=>{if(!e.isDir)return null;let f=d.split("/");for(let p=2;p<f.length+1;p++){let h=f.slice(0,p).join("/");if(!h||e.isDir(h))continue;let _=f.slice(0,p-1).join("/")||"/",b=f[p-1];for(let g=b.lastIndexOf("-");g>0;g=b.lastIndexOf("-",g-1)){let y=`${_==="/"?"":_}/${b.slice(0,g)}`;if(e.isDir(y)&&o(y)===y)return{root:h,key:n(y)}}return null}return null},"conventionRoot");return{of(d){if(!Kd(d))return null;let f=d.split(Gd).join("/"),p=hM(f),h=o(p);if(h){let _=n(h);return i.set(h,_),{root:h,key:_}}for(let[_,b]of s)if(!(!gM(f,_)||f===_)&&!(e.isDir&&e.isDir(_)))return{root:_,key:b};return c(p)},seenLive(){return[...i.entries()].map(([d,f])=>({root:d,key:f}))}}}a(aa,"createCheckoutResolver");function la(e,t){let n=new Map;for(let s of e){let l=new Map;for(let c of s.edited_paths){let u=t.of(c);!u||!u.key||l.set(u.key,Math.max(l.get(u.key)??0,u.root.length))}for(let[c,u]of l){let d=n.get(c)??{turns:0,depth:0};d.turns+=1,d.depth=Math.max(d.depth,u),n.set(c,d)}}let r=null,o=0,i=0;for(let[s,l]of n)(l.turns>o||l.turns===o&&(l.depth>i||l.depth===i&&r!==null&&s<r))&&(r=s,o=l.turns,i=l.depth);return r}a(la,"dominantProjectKey");function ca(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:ia(n.split(Gd).join("/"),r.root)}}a(ca,"relativizerFor");var yM=90*24*60*60*1e3,z3=60*60*1e3,_M=/^[a-f0-9]{64}$/;function bM(e){try{let t=JSON.parse(mM(e,"utf8"));if(t&&t.v===1&&t.checkouts&&typeof t.checkouts=="object")return{v:1,checkouts:t.checkouts}}catch{}return{v:1,checkouts:{}}}a(bM,"readMemory");function Hd(e){let t=new Map,n=bM(e);for(let[r,o]of Object.entries(n.checkouts)){if(!Kd(r)||!o||typeof o!="object")continue;let i=typeof o.project_key=="string"&&_M.test(o.project_key)?o.project_key:null;t.set(r,i)}return t}a(Hd,"loadCheckoutMemory");import{createReadStream as kM,existsSync as wM}from"node:fs";import{createInterface as vM}from"node:readline";import{homedir as Dx}from"node:os";import{isAbsolute as xM,join as ua}from"node:path";var jx=ua(Dx(),".codex","sessions");function Po(e=process.env,t=Dx()){let n=e.CODEX_HOME?.trim();return n&&xM(n)?ua(n,"sessions"):ua(t,".codex","sessions")}a(Po,"codexSessionsDir");async function Fo(e=jx){let{readdir:t}=await import("node:fs/promises"),n=[],r=a(async o=>{let i;try{i=await t(o,{withFileTypes:!0})}catch{return}for(let s of i){let l=ua(o,s.name);s.isDirectory()?await r(l):s.isFile()&&s.name.endsWith(".jsonl")&&n.push(l)}},"walk");return await r(e),n.sort()}a(Fo,"listCodexSessions");var Vd=a(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,"num");function Mx(e){let t=Vd(e.cached_input_tokens),n=Vd(e.input_tokens);return{input_tokens:Math.max(0,n-t),cache_read_tokens:t,output_tokens:Vd(e.output_tokens),cache_creation_tokens:0,cache_creation_1h_tokens:0}}a(Mx,"mapCodexUsage");var Wd=/^\*\*\* (?:Update|Add|Delete) File: (.+)$/gm;function SM(e){if(typeof e!="string"||e.length===0)return[];let t=[];Wd.lastIndex=0;for(let n=Wd.exec(e);n!==null;n=Wd.exec(e)){let r=n[1]?.trim();r&&!t.includes(r)&&t.push(r)}return t}a(SM,"codexEditedPaths");async function Uo(e){if(!e||!wM(e))return{turns:[],skipped:0};let t=[],n=0,r=null,o=null,i=[];return await new Promise(s=>{let l=vM({input:kM(e,{encoding:"utf-8"})});l.on("line",u=>{let d=u.trim();if(!d)return;let f;try{f=JSON.parse(d)}catch{return}let p=f.payload??{};if(f.type==="session_meta"||f.type==="turn_context"){typeof p.cwd=="string"&&p.cwd&&(o=p.cwd),typeof p.model=="string"&&p.model&&(r=p.model);return}if(p.name==="apply_patch"){for(let g of SM(p.input))i.includes(g)||i.push(g);return}if(p.type!=="token_count")return;let h=p.info?.last_token_usage;if(!h){n++;return}let _=Mx(h);if(_.input_tokens+_.output_tokens+_.cache_read_tokens===0){n++;return}let b=f.timestamp?Date.parse(f.timestamp):Number.NaN;t.push({ts:Number.isFinite(b)?b:0,model:r??"<unknown>",synthetic:!1,..._,sidechain:!1,stream:"main",edited_paths:i,cwd:o}),i=[]});let c=a(()=>s({turns:t,skipped:n}),"done");l.on("close",c),l.on("error",c)})}a(Uo,"collectCodexTurns");var Lx="2026-10-11",RM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,EM="maind",AM=new Set(["function_call","custom_tool_call","web_search_call"]);function Px(e){let t={user_turns:0,assistant_turns:0,tool_calls:0,session_id:null,lines_seen:e.length,maind_tool_calls:{},coordination_ids:[]};for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=r.payload??{},i=typeof o.type=="string"?o.type:"";if(r.type==="session_meta"&&!t.session_id){let s=typeof o.session_id=="string"&&o.session_id?o.session_id:o.id;typeof s=="string"&&s&&(t.session_id=s)}r.type==="event_msg"&&(i==="user_message"?t.user_turns++:i==="agent_message"?t.assistant_turns++:i==="mcp_tool_call_end"&&TM(t,o.invocation)),r.type==="response_item"&&AM.has(i)&&t.tool_calls++}return t}a(Px,"countCodexRecords");function TM(e,t){if(!t||typeof t!="object")return;let n=t;if(n.server!==EM||typeof n.tool!="string"||!n.tool)return;e.maind_tool_calls[n.tool]=(e.maind_tool_calls[n.tool]??0)+1;let r=n.arguments;if(!r||typeof r!="object")return;let o=r.session_id;if(typeof o!="string"||!RM.test(o.trim()))return;let i=o.trim().toLowerCase();e.coordination_ids.includes(i)||e.coordination_ids.push(i)}a(TM,"countMaindCall");async function qd(e,t={}){let n=t.turns??(await Uo(e)).turns,r=[],{readFile:o}=await import("node:fs/promises"),i;try{i=await o(e,"utf-8")}catch{return null}for(let u of i.split(`
473
473
  `)){let d=u.trim();if(d)try{r.push(JSON.parse(d))}catch{}}let s=Px(r);if(!s.session_id)return null;let l=a(u=>n.reduce((d,f)=>d+(typeof f[u]=="number"?f[u]:0),0),"sum"),c=new Map;for(let u of n){let d=c.get(u.model)??{first:u.ts,last:u.ts,turns:0,output_tokens:0};d.first=Math.min(d.first||u.ts,u.ts||d.first),d.last=Math.max(d.last,u.ts),d.turns++,d.output_tokens+=u.output_tokens,c.set(u.model,d)}return{session_id:s.session_id,user_turns:s.user_turns,assistant_turns:s.assistant_turns,tool_calls:s.tool_calls,agent_questions:0,input_tokens:l("input_tokens"),output_tokens:l("output_tokens"),cache_read_tokens:l("cache_read_tokens"),cache_creation_tokens:l("cache_creation_tokens"),user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,momentum_series:[],effort_at_end:null,lines_seen:s.lines_seen,model_mix:[...c.entries()].map(([u,d])=>({model:u,sidechain:!1,turns:d.turns,output_tokens:d.output_tokens,first_ts:d.first,last_ts:d.last})),ai_title:null,session_slug:null,analyzer_version:Lx,maind_tool_calls:s.maind_tool_calls,maind_connected:Object.keys(s.maind_tool_calls).length>0?"connected":"unknown",client:"codex",coordination_ids:s.coordination_ids}}a(qd,"analyzeCodexSession");import{createReadStream as Xd,existsSync as Jd}from"node:fs";import{createInterface as Zd}from"node:readline";var _e="=== Project Conventions",Gx="[truncated]",Fx=`
474
474
  - [`,CM=/^## maind\b/,Rr="## maind MCP integration",Bo="Project Conventions",da=/\[maind(?: guard)?\] Session briefing\b/,Yd=/…\d+ (?:tokens|chars) truncated…/,Hx="Full hook output saved to:",Vx="hooks.additional_context",Qd="<!-- maind:conventions v1 begin -->",Wx="<!-- maind:conventions v1 end -->";function Ae(e,t=Gx){let n=typeof t=="string"?e.indexOf(t):e.search(t),r=n>=0?n:null,o=e.indexOf(_e);if(o<0||r!==null&&o>r)return{headerOffset:null,truncatedAt:r,conventionsVisible:0,complete:!1,blockLength:e.length};let i=r??e.length,s=e.indexOf(`
475
475