@aistastudio/myc 0.4.7 → 0.4.9
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/dist/myc.js +210 -210
- package/package.json +1 -1
package/dist/myc.js
CHANGED
|
@@ -495,7 +495,7 @@ VALUES (?, ?, '', ?, ?, '{"op":"wal_checkpoint"}', ?)`,ex="DELETE FROM jobs WHER
|
|
|
495
495
|
last_hlc_seen = greatest(sync_state.last_hlc_seen, excluded.last_hlc_seen),
|
|
496
496
|
last_seq_sent = greatest(sync_state.last_seq_sent, excluded.last_seq_sent),
|
|
497
497
|
last_sync_at = excluded.last_sync_at,
|
|
498
|
-
endpoint = excluded.endpoint`)}}),ZO=new Map});var X2="0.4.
|
|
498
|
+
endpoint = excluded.endpoint`)}}),ZO=new Map});var X2="0.4.9";import{createHash as sh}from"crypto";function rh($){let X=$.regex.flags.includes("g")?$.regex.flags:`${$.regex.flags}g`,Z=$.regex.flags.replace(/[gy]/g,"");return{...$,compiled:new RegExp($.regex.source,X),sticky:new RegExp($.regex.source,`${Z}y`),literal:$.prefilter===void 0?void 0:new RegExp($.prefilter.literal.source,`${$.prefilter.literal.flags.replace(/[gy]/g,"")}g`)}}function Um($){let X=new Map;for(let z of $)X.set(z,(X.get(z)??0)+1);let Z=$.length,Y=0;for(let z of X.values()){let J=z/Z;Y-=J*Math.log2(J)}return Y}function Km($){return Zm.has($.length)&&Ym.test($)}function Wm($){return/data:[a-z0-9./+-]+;base64,/i.test($)}function Vm($){let X=[];UO.lastIndex=0;let Z;while((Z=UO.exec($))!==null){let Y=Z[1],z=Z[Xm];if(z.length<eh||z.length>$m)continue;if(Jm.test(Y))continue;if(Km(z))continue;if(zm.test(z))continue;let J=$.lastIndexOf(`
|
|
499
499
|
`,Z.index)+1,U=$.indexOf(`
|
|
500
500
|
`,Z.index),K=$.slice(J,U===-1?$.length:U);if(Wm(K))continue;if(Um(z)<th)continue;let W=Z.index+Z[0].lastIndexOf(z);X.push({kind:"high_entropy_assignment",confidence:"medium",start:W,end:W+z.length,value:z})}return X}function*VO($,X){let Z=$.literal,Y=$.prefilter?.back;Z.lastIndex=0;let z=0,J;while((J=Z.exec(X))!==null){if(J.index<z)continue;let U=J.index;if(Y!==void 0)while(U>z&&Y.test(X[U-1]))U-=1;for(let K=U;K<=J.index;K+=1){$.sticky.lastIndex=K;let W=$.sticky.exec(X);if(W===null||W[0].length===0)continue;yield W,z=W.index+W[0].length;break}}}function Gm($){let X=[];for(let Z of WO){if(Z.compiled.lastIndex=0,Z.literal!==void 0){for(let z of VO(Z,$))lz(Z,z,X);continue}let Y;while((Y=Z.compiled.exec($))!==null){if(Y[0].length===0){Z.compiled.lastIndex+=1;continue}lz(Z,Y,X)}}return X}function Hm($,X){let Z=[];for(let Y of WO){if(X&&Y.literal!==void 0){for(let J of VO(Y,$))lz(Y,J,Z);continue}Y.compiled.lastIndex=0;let z;while((z=Y.compiled.exec($))!==null){if(z[0].length===0){Y.compiled.lastIndex+=1;continue}lz(Y,z,Z)}}return Z}function lz($,X,Z){let Y=X[0],z=$.valueGroup,J=z!==void 0?X[z]:void 0;if(z!==void 0&&J===void 0)return;let U=J??Y,K=z!==void 0?X.index+Y.lastIndexOf(U):X.index;Z.push({kind:$.kind,confidence:$.confidence,start:K,end:K+U.length,value:U})}function Qm($){let X=[...$].sort((z,J)=>{if(z.start!==J.start)return z.start-J.start;return J.end-J.start-(z.end-z.start)}),Z=[],Y=-1;for(let z of X){if(z.start<Y)continue;Z.push(z),Y=z.end}return Z}function Nm($,X){let Z=sh("sha1").update(X).digest("hex").slice(0,8);return`<redacted:${$}:${Z}>`}function SV($){let X=Gm($),Z=X.map((W)=>[W.start,W.end]),Y=Vm($).filter((W)=>!Z.some(([V,G])=>W.start<G&&W.end>V)),z=Qm([...X,...Y]);if(z.length===0)return{text:$,findings:[]};let J="",U=0,K=[];for(let W of z){J+=$.slice(U,W.start);let V=Nm(W.kind,W.value);J+=V,K.push({kind:W.kind,start:W.start,end:W.end,confidence:W.confidence,placeholder:V}),U=W.end}return J+=$.slice(U),{text:J,findings:K}}var KO,WO,th=4,eh=32,$m=256,UO,Xm=3,Zm,Ym,zm,Jm;var GO=v(()=>{KO=[{kind:"aws_access_key_id",confidence:"high",regex:/\bAKIA[0-9A-Z]{16}\b/},{kind:"aws_secret_access_key",confidence:"medium",regex:/\baws_secret_access_key\s*[:=]\s*["']?([A-Za-z0-9/+=]{40})["']?/i,valueGroup:1},{kind:"gcp_api_key",confidence:"high",regex:/\bAIza[0-9A-Za-z\-_]{35}\b/},{kind:"google_oauth_client_secret",confidence:"high",regex:/\bGOCSPX-[A-Za-z0-9_-]{20,}\b/},{kind:"openai_project_key",confidence:"high",regex:/\bsk-proj-[A-Za-z0-9_-]{20,}\b/},{kind:"openai_key",confidence:"high",regex:/\bsk-[A-Za-z0-9]{20,}\b/},{kind:"anthropic_key",confidence:"high",regex:/\bsk-ant-[A-Za-z0-9-]{20,}\b/},{kind:"slack_token",confidence:"high",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/},{kind:"slack_webhook",confidence:"high",regex:/\bhooks\.slack\.com\/services\/T[A-Za-z0-9]+\/B[A-Za-z0-9]+\/[A-Za-z0-9]+\b/},{kind:"github_token",confidence:"high",regex:/\bgh[pousr]_[A-Za-z0-9]{36}\b/},{kind:"github_fine_grained_pat",confidence:"high",regex:/\bgithub_pat_[A-Za-z0-9_]{20,}\b/},{kind:"stripe_key",confidence:"high",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{20,}\b/},{kind:"npm_token",confidence:"high",regex:/\bnpm_[A-Za-z0-9]{36}\b/},{kind:"sendgrid_key",confidence:"high",regex:/\bSG\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/},{kind:"mailgun_key",confidence:"medium",regex:/\bkey-[a-f0-9]{32}\b/},{kind:"digitalocean_token",confidence:"high",regex:/\bdop_v1_[a-f0-9]{64}\b/},{kind:"azure_storage_connection_string",confidence:"high",regex:/\bDefaultEndpointsProtocol=https?;[^;\n]*AccountKey=([A-Za-z0-9+/=]{20,})/,valueGroup:1,prefilter:{literal:/DefaultEndpointsProtocol=/}},{kind:"private_key_pem",confidence:"high",regex:/-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----[\s\S]+?-----END (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/},{kind:"jwt",confidence:"high",regex:/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/},{kind:"db_connection_string",confidence:"high",regex:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis):\/\/[^:\s/@]+:[^@\s]+@[^\s'"`]+/i,prefilter:{literal:/(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis):\/\//i}},{kind:"basic_auth_url",confidence:"medium",regex:/\bhttps?:\/\/[^:\s/@]+:[^@\s]+@[^\s'"`]+/i},{kind:"authorization_header",confidence:"high",regex:/\bAuthorization\s*:\s*(?:Bearer|Basic)\s+([A-Za-z0-9\-._~+/]+=*)/i,valueGroup:1},{kind:"twilio_api_key_sid",confidence:"medium",regex:/\bSK[a-f0-9]{32}\b/},{kind:"generic_key_assignment",confidence:"medium",regex:/\b((?:[A-Za-z][A-Za-z0-9]*(?:[_.-][A-Za-z0-9]+)*[_.-])?(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD|CREDENTIAL)S?)\s*[:=]\s*["']?([A-Za-z0-9\-_/+.=]{8,})["']?/i,valueGroup:2,prefilter:{literal:/(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD|CREDENTIAL)S?\s*[:=]/i,back:/[A-Za-z0-9_.-]/}},{kind:"screaming_key_assignment",confidence:"medium",regex:/\b([A-Z][A-Z0-9]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD|CREDENTIAL)S?)\s*[:=]\s*["']?([A-Za-z0-9\-_/+.=]{8,})["']?/,valueGroup:2}];WO=KO.map(rh),UO=/([A-Za-z](?=([\w.$-]{1,40}))\2)\s*[:=]\s*["']?([A-Za-z0-9+/_=\-]{32,256})["']?/g,Zm=new Set([32,40,64]),Ym=/^[0-9a-f]+$/i,zm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Jm=/^(?:id|uuid|hash|sha|sha1|sha256|md5|commit|rev|revision|version|src|href|url|path|class|style|guid|digest|checksum|etag|blob|oid)$/i});function Lm($){let X={};if($.tags!==void 0)X.tags=[...$.tags];if($.source!==void 0)X.source=$.source;if($.topic!==void 0)X.topic=$.topic;return{id:$.id,kind:"note",scope:$.scope,layer:$.layer,title:$.title,body:$.body??null,attrs:X}}function c7($){let X={type:NO};if($.external_ref!==void 0)X.external_ref=$.external_ref;if($.external_created_at!==void 0)X.external_created_at=$.external_created_at;return{kind:"note",layer:1,scope:$.scope,title:$.title??LO($.text),body:$.text,...$.actor!==void 0&&$.actor.length>0?{actor:$.actor}:{},...$.acl!==void 0?{acl:$.acl}:{},attrs:X}}function LO($){return($.split(`
|
|
501
501
|
`)[0]??"").slice(0,80)}function qm($){for(let[X,Z]of Tm)if(X.test($))return Z;return null}function Fm($){let X=[];HO.lastIndex=0;for(let Z of $.matchAll(HO))X.push({index:Z.index,headerEnd:Z.index+Z[0].length,text:Z[1]??""});return X}function jm($,X,Z){let Y=X,z=Z;while(Y<z&&/\s/u.test($[Y]??""))Y++;while(z>Y&&/\s/u.test($[z-1]??""))z--;return{start:Y,end:z}}function Z2($,X=80){let[Z=""]=$.split(/\r?\n/u),Y=Z.replace(/\s+/gu," ").trim();return Y.length<=X?Y:`${Y.slice(0,X-1)}\u2026`}function Om($){let X=Fm($),Z=[],Y=0,z=(J,U,K)=>{let W=jm($,J,U);if(W.end<=W.start)return;let V=$.slice(W.start,W.end),G=K===null?null:qm(K);if(G!==null){QO.lastIndex=0;let H=[...V.matchAll(QO)];if(H.length>0){for(let N of H){let Q=N[1]??"";if(Q.trim().length===0)continue;let L=N.index+N[0].indexOf(Q);Z.push({frag_type:G,ord:Y++,char_start:W.start+L,char_end:W.start+L+Q.length,title:Z2(Q),body:Q})}return}Z.push({frag_type:G,ord:Y++,char_start:W.start,char_end:W.end,title:K!==null?Z2(K):Z2(V),body:V});return}Z.push({frag_type:"section",ord:Y++,char_start:W.start,char_end:W.end,title:K!==null?Z2(K):Z2(V),body:V})};if(X.length===0)return z(0,$.length,null),Z;if(X[0].index>0)z(0,X[0].index,null);for(let J=0;J<X.length;J++){let U=X[J],K=X[J+1],W=K!==void 0?K.index:$.length;z(U.headerEnd,W,U.text)}return Z}function Cm($,X){let Z={n_fragments:X,parsed_by:BO};if($.uri!==void 0)Z.uri=$.uri;if($.mime!==void 0)Z.mime=$.mime;return{id:$.id,kind:"doc",scope:$.scope,layer:$.layer,title:$.title,body:$.body,attrs:Z}}function Am($,X){return{kind:"fragment",scope:$.scope,title:X.title,body:X.body,attrs:{frag_type:X.frag_type,ord:X.ord,char_start:X.char_start,char_end:X.char_end}}}function Pm($){let X={};if($.agent!==void 0)X.agent=$.agent;if($.model!==void 0)X.model=$.model;if($.started_at!==void 0)X.started_at=$.started_at;if($.cwd!==void 0)X.cwd=$.cwd;if($.git_head!==void 0)X.git_head=$.git_head;return{id:$.id,kind:"session",scope:$.scope,title:$.title??"",attrs:X}}function Dm($,X){let Z=X.id??n$(),Y=X.replyTo?.thread_root??X.replyTo?.id??Z,z={session_id:$.id,role:X.role,ord:X.ord,thread_root:Y};if(X.tokens_in!==void 0)z.tokens_in=X.tokens_in;if(X.tokens_out!==void 0)z.tokens_out=X.tokens_out;return{id:Z,threadRoot:Y,input:{id:Z,kind:"message",scope:X.scope??$.scope,title:X.title??"",body:X.body??null,attrs:z}}}function Mm($){return $.replace(/\s+/gu," ").trim().toLowerCase()}function Rm($){let X={etype:$.etype};if($.aliases!==void 0)X.aliases=[...$.aliases];if($.canonical!==void 0)X.canonical=$.canonical;return{id:$.id,kind:"entity",scope:$.scope,title:$.name,attrs:X}}var NO="comment",Bm,BO="core/memory.parseFragments@1",HO,QO,Tm;var TO=v(()=>{iW();Bm=["claim","plan_item","reference","risk","section"],HO=/^#{1,6}[ \t]+(.+?)[ \t]*$/gmu,QO=/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+(.+?)[ \t]*$/gmu,Tm=[[/claim|\u0443\u0442\u0432\u0435\u0440\u0436\u0434/iu,"claim"],[/plan|\u043F\u043B\u0430\u043D|todo|\u0437\u0430\u0434\u0430\u0447/iu,"plan_item"],[/reference|\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A|\u0441\u0441\u044B\u043B\u043A|citation/iu,"reference"],[/risk|\u0440\u0438\u0441\u043A/iu,"risk"]]});function _m($){return`${$.src}|${$.dst}`}function qO($,X,Z){let Y=[];for(let z of X)for(let J of Z.versionChain(z)){if($.has(J))continue;$.add(J),Y.push(J)}return Y}function gV($,X,Z={}){let Y=new Set($);qO(Y,[...Y],X);let z=Z.withBlockers===!0,J=!1;if(z)for(;;){let K=[];for(let W of[...Y])for(let V of X.blockLinks(W)){let G=V.src===W?V.dst:V.src;if(G===W||Y.has(G))continue;Y.add(G),K.push(G)}if(K.length===0)break;J=!0,K.push(...qO(Y,K,X))}let U=new Map;for(let K of Y)for(let W of X.blockLinks(K)){if(Y.has(W.src)===Y.has(W.dst))continue;U.set(_m(W),W)}return{members:[...Y].sort(),crossing:[...U.values()].sort((K,W)=>K.src===W.src?K.dst.localeCompare(W.dst):K.src.localeCompare(W.src)),expanded:J}}var i7="moved_from";function FO($,X){let Z=$.one(iz.digest_lookup,[X.scope,X.profile,X.variant??""]),Y=Z?.now_seq??0;if(Z===void 0||Z.entry_seq===null)return{seq:Y,cache:"miss",reason:"cold",payload:void 0};if(Z.payload===null)return{seq:Y,cache:"miss",reason:"stale",payload:void 0};try{return{seq:Y,cache:"hit",reason:void 0,payload:JSON.parse(Z.payload)}}catch{return{seq:Y,cache:"miss",reason:"stale",payload:void 0}}}function jO($,X,Z,Y){$.run(iz.digest_put,[X.scope,X.profile,X.variant??"",Z,JSON.stringify(Y)])}function km($,X){return $.run(iz.digest_drop_scope,[X]).changes}function Y2($,X,Z){let Y=FO($,X);if(Y.cache==="hit"&&Y.payload!==void 0)return{payload:Y.payload,cache:"hit",reason:void 0,seq:Y.seq};let z=Z();return jO($,X,Y.seq,z),{payload:z,cache:"miss",reason:Y.reason,seq:Y.seq}}var pz="prime",cz="ready",Im,iz;var OO=v(()=>{W6();Im=[pz,cz],iz=Z0({digest_lookup:{name:"digest_lookup",sql:`SELECT s.now_seq AS now_seq,
|
|
@@ -2575,7 +2575,7 @@ SELECT a.node_id AS node_id, a.path AS path, a.span_start AS s, a.span_end AS e,
|
|
|
2575
2575
|
ON CONFLICT (repo_id, path) DO UPDATE SET
|
|
2576
2576
|
lang = excluded.lang, mtime_ms = excluded.mtime_ms,
|
|
2577
2577
|
size_bytes = excluded.size_bytes, file_hash = excluded.file_hash,
|
|
2578
|
-
indexed_at = excluded.indexed_at`),H=$.query("DELETE FROM code_defs WHERE repo_id = ?1 AND path = ?2"),N=$.query("INSERT OR REPLACE INTO code_defs (repo_id, path, name, kind, span_start, span_end, exported) VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0)"),Q=$.query("DELETE FROM code_files WHERE repo_id = ?1 AND path = ?2"),L=$.query("DELETE FROM code_ref_sites WHERE repo_id = ?1 AND path = ?2"),B=$.query("INSERT OR REPLACE INTO code_ref_sites (repo_id, path, line, name, kind, from_name, from_start) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)");z.batches++;let T=performance.now(),q=new Map,j=(F)=>{let P=q.get(F);if(P===void 0){let _=ZN([F]);P=_.length>0,q.set(F,P);for(let M of _){let E=z.missing.get(M.grammar)??{grammar:M.grammar,langs:new Set,bytes:M.bytes,files:0};for(let b of M.langs)E.langs.add(b);z.missing.set(M.grammar,E)}}return P},O=[];for(let F of Y){let P=F.entity_id;if(P===null){f0.complete($,F.id,U);continue}if(U7(P)){O.push({job:F,path:P,cleanup:!0,lang:"",mtimeMs:0,size:0,hash:"",source:"",skip:!1,pending:null});continue}let _=lN(X.root,P),M,E,b;try{M=Y_(_);let h=z_(_);E=Math.round(h.mtimeMs),b=h.size}catch{O.push({job:F,path:P,cleanup:!0,lang:"",mtimeMs:0,size:0,hash:"",source:"",skip:!1,pending:null});continue}let k=Y5(P),y=V?K_(M):"",g=B$.has(k)&&X.parse===void 0&&j(k),S=B$.has(k)&&!g,w=S?M.toString("utf8"):"";O.push({job:F,path:P,cleanup:!1,lang:k,mtimeMs:E,size:b,hash:y,source:w,skip:g,pending:S&&J!==null?bd(J.parse(w,k)):null})}let A=new Set;for(let F of O)if(!F.cleanup&&!F.skip&&B$.has(F.lang))A.add(F.lang);if(A.size>0)await GN(A);let R=[];for(let F of O){if(F.cleanup){R.push({job:F.job,plan:{kind:"cleanup",path:F.path}});continue}if(F.skip){z.skipped++;let P=z.missing.get(vd(F.lang));if(P!==void 0)P.files++;R.push({job:F.job,plan:{kind:"skip"}});continue}if(!B$.has(F.lang)){R.push({job:F.job,plan:{kind:"write",path:F.path,lang:F.lang,defs:[],refs:[],mtimeMs:F.mtimeMs,size:F.size,hash:F.hash}});continue}try{let P;if(F.pending!==null){let _=await F.pending;if(_.ok)P=_.parsed,z.pooled++;else P=W(F.source,F.lang)}else P=W(F.source,F.lang);z.parsed++,z.refs+=P.refs.length,R.push({job:F.job,plan:{kind:"write",path:F.path,lang:F.lang,defs:P.defs,refs:P.refs,mtimeMs:F.mtimeMs,size:F.size,hash:F.hash}})}catch(P){z.failed++,f0.fail($,F.job.id,`parse ${F.path}: ${P instanceof Error?P.message:String(P)}`,{holder:U,now:K})}}z.parseMs+=performance.now()-T;let D=performance.now();$.exec("BEGIN IMMEDIATE");try{for(let{job:F,plan:P}of R){if(P.kind==="skip"){f0.complete($,F.id,U);continue}if(P.kind==="cleanup")H.run(X.repoId,P.path),L.run(X.repoId,P.path),Q.run(X.repoId,P.path),z.cleaned++;else{G.run(X.repoId,P.path,P.lang,P.mtimeMs,P.size,P.hash,K),H.run(X.repoId,P.path),L.run(X.repoId,P.path);for(let _ of P.defs)N.run(X.repoId,P.path,_.name,_.kind,_.startLine,_.endLine);for(let _ of P.refs)B.run(X.repoId,P.path,_.line,_.name,_.kind,_.from,_.fromStart);z.written++}f0.complete($,F.id,U)}if(R.length>0)Q_($,X.repoId);$.exec("COMMIT")}catch(F){throw $.exec("ROLLBACK"),F}z.applyMs+=performance.now()-D}async function xd($,X,Z={}){let Y=await H_($,X),z=await N_($,X,Z);return{scan:Y,drain:z}}var OY="code_index",J_=8,U_=64,Ed=67108864,W_="MYC_PARSE_POOL_MUTATION";var B_=v(()=>{n0();h1();X_();Z_();O6();q2();VY();O6()});function hd($){return $.match(pN)??[]}function md($){if($.prefix||$.words.length!==1)return $;let X=$.words[0];if(X.length<6)return $;return{words:[X.slice(0,Math.max(5,X.length-3))],prefix:!0}}function T_($,X,Z){if($.length-X<2)return"";let Y=[],z=[],J=(U,K)=>{if(K.length===X){z.push([...K]);return}for(let W=U;W<$.length;W++)K.push(W),J(W+1,K),K.pop()};J(0,[]);for(let U of z){let K=$.filter((W,V)=>!U.includes(V));Y.push(`(${K.map(Z.term).join(Z.and)})`)}return Y.join(Z.or)}function pd($){let X=$.trim();if(X.length===0)return null;let Z=[],Y=0,z=X.length;while(Y<z){if(X[Y]==='"'){let V=Y+1;while(V<z&&X[V]!=='"')V++;let G=hd(X.slice(Y+1,V));if(G.length>0)Z.push({words:G,prefix:!1});Y=V<z?V+1:V;continue}pN.lastIndex=Y;let U=pN.exec(X);if(U===null||U.index!==Y){Y++;continue}let K=U[0],W=Y+K.length;if(X[W]==="*")Z.push({words:[K],prefix:!0}),Y=W+1;else Z.push({words:[K],prefix:!1}),Y=W}return Z.length===0?null:Z}function WU($,X="sqlite"){let Z=pd($);if(Z===null)return null;let Y=X==="pg"?ld:ud,z=Z.map(md),J=(U,K)=>U.map(Y.term).join(K);return{terms:Z.map(Y.term),and:J(Z,Y.and),prefixAnd:J(z,Y.and),prefixRelaxed:T_(z,1,Y),prefixRelaxed2:T_(z,2,Y),or:J(Z,Y.or),prefixOr:J(z,Y.or)}}var
|
|
2578
|
+
indexed_at = excluded.indexed_at`),H=$.query("DELETE FROM code_defs WHERE repo_id = ?1 AND path = ?2"),N=$.query("INSERT OR REPLACE INTO code_defs (repo_id, path, name, kind, span_start, span_end, exported) VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0)"),Q=$.query("DELETE FROM code_files WHERE repo_id = ?1 AND path = ?2"),L=$.query("DELETE FROM code_ref_sites WHERE repo_id = ?1 AND path = ?2"),B=$.query("INSERT OR REPLACE INTO code_ref_sites (repo_id, path, line, name, kind, from_name, from_start) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)");z.batches++;let T=performance.now(),q=new Map,j=(F)=>{let P=q.get(F);if(P===void 0){let _=ZN([F]);P=_.length>0,q.set(F,P);for(let M of _){let E=z.missing.get(M.grammar)??{grammar:M.grammar,langs:new Set,bytes:M.bytes,files:0};for(let b of M.langs)E.langs.add(b);z.missing.set(M.grammar,E)}}return P},O=[];for(let F of Y){let P=F.entity_id;if(P===null){f0.complete($,F.id,U);continue}if(U7(P)){O.push({job:F,path:P,cleanup:!0,lang:"",mtimeMs:0,size:0,hash:"",source:"",skip:!1,pending:null});continue}let _=lN(X.root,P),M,E,b;try{M=Y_(_);let h=z_(_);E=Math.round(h.mtimeMs),b=h.size}catch{O.push({job:F,path:P,cleanup:!0,lang:"",mtimeMs:0,size:0,hash:"",source:"",skip:!1,pending:null});continue}let k=Y5(P),y=V?K_(M):"",g=B$.has(k)&&X.parse===void 0&&j(k),S=B$.has(k)&&!g,w=S?M.toString("utf8"):"";O.push({job:F,path:P,cleanup:!1,lang:k,mtimeMs:E,size:b,hash:y,source:w,skip:g,pending:S&&J!==null?bd(J.parse(w,k)):null})}let A=new Set;for(let F of O)if(!F.cleanup&&!F.skip&&B$.has(F.lang))A.add(F.lang);if(A.size>0)await GN(A);let R=[];for(let F of O){if(F.cleanup){R.push({job:F.job,plan:{kind:"cleanup",path:F.path}});continue}if(F.skip){z.skipped++;let P=z.missing.get(vd(F.lang));if(P!==void 0)P.files++;R.push({job:F.job,plan:{kind:"skip"}});continue}if(!B$.has(F.lang)){R.push({job:F.job,plan:{kind:"write",path:F.path,lang:F.lang,defs:[],refs:[],mtimeMs:F.mtimeMs,size:F.size,hash:F.hash}});continue}try{let P;if(F.pending!==null){let _=await F.pending;if(_.ok)P=_.parsed,z.pooled++;else P=W(F.source,F.lang)}else P=W(F.source,F.lang);z.parsed++,z.refs+=P.refs.length,R.push({job:F.job,plan:{kind:"write",path:F.path,lang:F.lang,defs:P.defs,refs:P.refs,mtimeMs:F.mtimeMs,size:F.size,hash:F.hash}})}catch(P){z.failed++,f0.fail($,F.job.id,`parse ${F.path}: ${P instanceof Error?P.message:String(P)}`,{holder:U,now:K})}}z.parseMs+=performance.now()-T;let D=performance.now();$.exec("BEGIN IMMEDIATE");try{for(let{job:F,plan:P}of R){if(P.kind==="skip"){f0.complete($,F.id,U);continue}if(P.kind==="cleanup")H.run(X.repoId,P.path),L.run(X.repoId,P.path),Q.run(X.repoId,P.path),z.cleaned++;else{G.run(X.repoId,P.path,P.lang,P.mtimeMs,P.size,P.hash,K),H.run(X.repoId,P.path),L.run(X.repoId,P.path);for(let _ of P.defs)N.run(X.repoId,P.path,_.name,_.kind,_.startLine,_.endLine);for(let _ of P.refs)B.run(X.repoId,P.path,_.line,_.name,_.kind,_.from,_.fromStart);z.written++}f0.complete($,F.id,U)}if(R.length>0)Q_($,X.repoId);$.exec("COMMIT")}catch(F){throw $.exec("ROLLBACK"),F}z.applyMs+=performance.now()-D}async function xd($,X,Z={}){let Y=await H_($,X),z=await N_($,X,Z);return{scan:Y,drain:z}}var OY="code_index",J_=8,U_=64,Ed=67108864,W_="MYC_PARSE_POOL_MUTATION";var B_=v(()=>{n0();h1();X_();Z_();O6();q2();VY();O6()});function hd($){return $.match(pN)??[]}function md($){if($.prefix||$.words.length!==1)return $;let X=$.words[0];if(X.length<6)return $;return{words:[X.slice(0,Math.max(5,X.length-3))],prefix:!0}}function T_($,X,Z){if($.length-X<2)return"";let Y=[],z=[],J=(U,K)=>{if(K.length===X){z.push([...K]);return}for(let W=U;W<$.length;W++)K.push(W),J(W+1,K),K.pop()};J(0,[]);for(let U of z){let K=$.filter((W,V)=>!U.includes(V));Y.push(`(${K.map(Z.term).join(Z.and)})`)}return Y.join(Z.or)}function pd($){let X=$.trim();if(X.length===0)return null;let Z=[],Y=0,z=X.length;while(Y<z){if(X[Y]==='"'){let V=Y+1;while(V<z&&X[V]!=='"')V++;let G=hd(X.slice(Y+1,V));if(G.length>0)Z.push({words:G,prefix:!1});Y=V<z?V+1:V;continue}pN.lastIndex=Y;let U=pN.exec(X);if(U===null||U.index!==Y){Y++;continue}let K=U[0],W=Y+K.length;if(X[W]==="*")Z.push({words:[K],prefix:!0}),Y=W+1;else Z.push({words:[K],prefix:!1}),Y=W}return Z.length===0?null:Z}function WU($,X="sqlite"){let Z=pd($);if(Z===null)return null;let Y=X==="pg"?ld:ud,z=Z.map(md),J=(U,K)=>U.map(Y.term).join(K);return{terms:Z.map(Y.term),and:J(Z,Y.and),prefixAnd:J(z,Y.and),prefixRelaxed:T_(z,1,Y),prefixRelaxed2:T_(z,2,Y),or:J(Z,Y.or),prefixOr:J(z,Y.or)}}var GV0,pN,ud,ld;var VU=v(()=>{o();K8();GV0=Z0({ftsSearch:{name:"ftsSearch",sql:`
|
|
2579
2579
|
WITH matches AS (
|
|
2580
2580
|
SELECT n.id AS node_id,
|
|
2581
2581
|
bm25(nodes_fts, 10.0, 1.0, 1.0) AS bm25_score
|
|
@@ -2780,7 +2780,7 @@ SELECT g.src AS id, n.kind AS kind, n.title AS title, n.status AS status,
|
|
|
2780
2780
|
ELSE (SELECT group_concat(an.state || ':' || an.drift, ',')
|
|
2781
2781
|
FROM edges t JOIN anchors an ON an.node_id = t.dst
|
|
2782
2782
|
WHERE t.src = ${$}.id AND t.type = 'touches' AND t.deleted_at IS NULL)
|
|
2783
|
-
END`}function aa($,X){let Z=$.fts??X.missingRank,Y=$.vec??X.missingRank;return X.weightFts/(X.rrfK+Z)+X.weightVec/(X.rrfK+Y)}function ra($,X,Z){let Y=$.priority,z=1+(Y===0?Z.priorityBoostP0:0)+(Y===1?Z.priorityBoostP1:0)-(Y===3?Z.priorityPenaltyP3:0),J=Math.max(0,Math.floor((X-$.updatedAt)/sa)),U=1+Z.freshnessAmplitude*Math.exp(-J/Z.freshnessTauDays),W=(Z.layerWeights[Z.profile]??BU[Z.profile])[Math.min(3,Math.max(0,$.layer))];return z*U*W}function ta($,X){if($===null||$.length===0)return $L;let Z=null;for(let Y of $.split(",")){let z=Y.indexOf(":"),J=z<0?Y:Y.slice(0,z),U=z<0?Number.NaN:Number(Y.slice(z+1)),K;if(J==="stale")K={weight:X.anchorStateWeights.stale,state:"stale"};else if(J==="lost")K={weight:X.anchorStateWeights.lost,state:"lost"};else if(J==="drifted")K={weight:X.anchorDriftWeight&&Number.isFinite(U)?Math.min(1,Math.max(0,U)):1,state:"drifted"};else K=$L;if(Z===null||K.weight>Z.weight||K.weight===Z.weight&&K.state===null)Z=K}return Z??$L}function ea($,X){if($.length<X)return Number.NaN;let Z=$.map((J)=>-J).sort((J,U)=>U-J),Y=Z[0],z=Z[Math.floor(Z.length/2)];if(!(Y>0))return 0;return(Y-z)/Y}function $s($,X,Z,Y=!1){let z=ia($),J=z.filter(ca).length,U=ea(X,Z.spreadMinHits),K=J>0&&X.length>0,W=X.length<Z.minLexicalHits&&!(Z.anchorHitSuppressesFewResults&&K),V=Number.isFinite(U)&&U<Z.minBm25Spread,G=z.length<=Z.shortQueryTerms&&J===0,H=[];if(W)H.push("few_results");if(V)H.push("low_bm25_spread");if(G)H.push("short_query_no_anchor");if(Y)H.push("lexical_fallback");return{fired:H.length>0,reasons:H,checks:{fewResults:W,lowBm25Spread:V,shortQueryNoAnchor:G,lexicalFallback:Y},anchorHit:K,metrics:{lexicalHits:X.length,bm25Spread:U,queryTerms:z.length,anchorTerms:J}}}function t_($,X,Z,Y=[]){return{hits:[],mode_used:{sources:[],vector:"skipped",lexical:Ys,vectorOnly:!1,emptyReason:Z,why:$,trigger:Zs,roundTrips:X,vectorRoundTrips:0,degraded:Y,graphSeeds:"lexical",graph:Xs,cache:"off"}}}function zs($){let X=$.mode_used;if(X.degraded.length>0)return!1;return X.vector!=="unavailable"&&X.vector!=="degraded"}function XL($,X,Z){return{hits:$.hits,mode_used:{...$.mode_used,cache:X,...Z===void 0?{}:{roundTrips:Z,vectorRoundTrips:0}}}}function XI($,X){let Z=X.cache;if(Z===void 0)return XL(e_($,X),"off");let Y=a_($),z=s_({text:X.text,scopes:X.scopes,layerMin:X.layerMin??0,layerMax:X.layerMax??3,limit:$I(X.limit),vectorMode:X.vectorMode??"auto",caller:X.caller,config:{...q$,...X.config}}),J=(X.cacheClock??Date.now)(),U=Z.get(z,Y,J);if(U.outcome==="hit")return XL(U.value,"hit",1);let K=e_($,X);return Z.set(z,Y,J,K,zs(K)),XL(K,"miss",K.mode_used.roundTrips+1)}function e_($,X){let Z={...q$,...X.config},Y=$I(X.limit),z=X.now??Date.now(),J=X.layerMin??0,U=X.layerMax??3,K=[],W=0,V=0,G=WU(X.text),H=[X.caller.ownerId,X.caller.teamId,X.caller.agentId,JSON.stringify(X.caller.principals)],N=JSON.stringify([...X.scopes]),Q=()=>{if(X.scopes.length===0)return{size:0,atLeast:!1};W++;let p=$.all(LU.hybridCorpusSize,[N,J,U,...H])[0]?.n??0;return{size:Math.min(p,1000),atLeast:p>1000}};if(G===null){let p=Q();return t_("empty query: no terms left after parsing",W,{code:"empty_query",text:"query contains no words: no terms left after parsing \u2014 "+"nothing to search for, the database is not the cause",corpusSize:p.size,corpusAtLeast:p.atLeast})}if(X.scopes.length===0)return t_("empty scope list: a query without a partition key is not run (S27)",W,{code:"no_scopes",text:"a query without a partition key (empty scope list) is not run \u2014 S27",corpusSize:0,corpusAtLeast:!1});let L=Z.graphMaxHops>=1?Z.graphSeeds:0,B=Z.graphMaxHops>=2&&Z.graphDecayByHop.length>=2?Z.graphHop2Seeds:0,T=(p)=>{let G0=$.all(LU.hybridLexicalPass,[p,N,J,U,...H,Z.poolSize,L,Z.graphMinEdgeWeight,B,Z.graphHopFanout]);W++;let O0=new Map,b0=[],_$=new Map,x0=[];for(let L0 of G0){let h8={id:L0.id,kind:L0.kind,layer:L0.layer,priority:L0.priority,updated_at:L0.updated_at,fresh_at:L0.fresh_at,title:L0.title,excerpt:L0.excerpt,anchors:L0.anchors},E4=O0.get(L0.id)??{id:L0.id,node:h8,sources:new Set};if(L0.fts_rank!==null){if(E4.ftsRank=L0.fts_rank,E4.sources.add("fts"),L0.bm25!==null)b0.push(L0.bm25),_$.set(L0.id,L0.bm25)}else if(L0.via_id!==null)x0.push({id:L0.id,viaId:L0.via_id,weight:L0.edge_weight??0,type:L0.edge_type??"",depth:L0.depth}),E4.sources.add("graph");O0.set(L0.id,E4)}return{byId:O0,bm25:b0,bm25ById:_$,graphRaw:x0}},q={prefix_and:G.prefixAnd===G.and?"":G.prefixAnd,prefix_relaxed:G.terms.length>=Z.fallbackMinTerms?G.prefixRelaxed:"",prefix_relaxed2:G.terms.length>=Z.fallbackMinTerms&&G.terms.length<=Z.relaxed2MaxTerms?G.prefixRelaxed2:"",prefix_or:G.terms.length>=Z.fallbackMinTerms||G.prefixOr!==G.and?G.prefixOr:"",or:G.terms.length>=Z.fallbackMinTerms?G.or:""},j=Z.lexicalMode==="or_always"&&q.or!=="",O=T(j?G.or:G.and),A=j?0:O.bm25.length,R=j?"or":"and",D=!1,F=!1,P=0;if(Z.lexicalMode==="and_then_fallback"&&O.bm25.length===0)for(let p of Z.fallbackStages){let G0=q[p];if(G0===""||G0===G.and)continue;P++;let O0=T(G0);if(O0.bm25.length>0){O=O0,R=p,D=!0;break}}if(R!=="and"&&R!=="prefix_and"&&Z.orCoverageBoost&&O.bm25.length>1){let p=[...O.bm25ById.keys()],G0=new Map;for(let O0 of $.all(LU.hybridOrCoverage,[JSON.stringify(R==="or"?[...G.terms]:[...G.terms].map(Us)),JSON.stringify(p)]))G0.set(O0.id,O0.cov);if(W++,G0.size>0)F=!0,p.slice().sort((b0,_$)=>{let x0=(G0.get(_$)??0)-(G0.get(b0)??0);if(x0!==0)return x0;let L0=(O.bm25ById.get(b0)??0)-(O.bm25ById.get(_$)??0);if(L0!==0)return L0;return b0<_$?-1:1}).forEach((b0,_$)=>{let x0=O.byId.get(b0);if(x0!==void 0)x0.ftsRank=_$+1})}let{byId:M,bm25:E,graphRaw:b}=O,k={operator:R,fallbackUsed:D,andHits:A,hits:E.length,terms:G.terms.length,stagesTried:P,coverageApplied:F},y=X.vectorMode??"auto",g=$s(X.text,E,Z,D),S,w,h,u,d;if(y==="never")h=!1,S="disabled",w="vector branch explicitly off (vectorMode: never)";else if(y==="always")h=!0,S="used",w="vector branch unconditionally on (vectorMode: always) \u2014 the reference for comparison";else if(g.fired)h=!0,S="used",w=`lexical fell short: ${g.reasons.join(", ")}`;else h=!1,S="skipped",w=`lexical is enough (${g.metrics.lexicalHits} candidates, BM25 spread ${Ks(g.metrics.bm25Spread)}, anchor terms ${g.metrics.anchorTerms}/${g.metrics.queryTerms}) \u2014 `+"query embedding not computed, ~23 ms saved (S31)";if(h){let p=X.embedQuery?X.embedQuery():null;if(p===null)S="unavailable",w=`${w}; but there is no query embedding \u2014 results only from lexical and graph`,K.push("vector-branch: query embedding unavailable (no embedder or cache) \u2014 "+"the vector branch did not take part");else{let O0=(X.vectorSource??o_)($,{vector:p,scopes:X.scopes,layerMin:X.layerMin,layerMax:X.layerMax,caller:X.caller,limit:Z.poolSize,candidateLimit:200});if(V+=O0.degraded?1:O0.reranked?4:2,O0.degraded)S="degraded",w=`${w}; vector source degraded: ${O0.reason??"no reason given"}`,K.push(`vector-source: ${O0.reason??"degraded"}`);else if(O0.hits.length===0)S="empty",w=`${w}; the vector branch ran but gave no candidates`;else{u=O0.distanceMean,d=O0.distanceStd;let b0=new Map(O0.hits.map((x0)=>[x0.id,x0.distance])),_$=[];for(let x0 of O0.hits){let L0=M.get(x0.id);if(L0===void 0)_$.push(x0.id);else L0.vecRank=x0.rank,L0.vecDistance=x0.distance,L0.sources.add("vector")}if(_$.length>0){let x0=$.all(LU.hybridHydrate,[JSON.stringify(_$),N,J,U,...H]);W++;let L0=new Map(x0.map((h8)=>[h8.id,h8]));for(let h8 of O0.hits){if(M.has(h8.id))continue;let E4=L0.get(h8.id);if(E4===void 0)continue;M.set(h8.id,{id:h8.id,node:E4,vecRank:h8.rank,vecDistance:b0.get(h8.id),sources:new Set(["vector"])})}}}}}let a=new Map,e=[],r=new Map,c=(p)=>{let G0=r.get(p.id);if(G0===void 0)r.set(p.id,G0=ta(p.node.anchors,Z));return G0};for(let p of M.values()){if(p.ftsRank===void 0&&p.vecRank===void 0)continue;let G0=aa({fts:p.ftsRank,vec:p.vecRank},Z),O0=G0*ra({priority:p.node.priority,layer:p.node.layer,updatedAt:p.node.fresh_at},z,Z)*c(p).weight;a.set(p.id,O0),e.push({cand:p,rrf:G0,score:O0})}let l=2*(L+B),m=new Map,n=new Map(a),X0=[];for(let p of[...b].sort((G0,O0)=>G0.depth-O0.depth)){if(p.depth>Z.graphMaxHops)continue;let G0=Z.graphDecayByHop[p.depth-1];if(G0===void 0)continue;let O0=n.get(p.viaId);if(O0===void 0)continue;let b0=M.get(p.id);if(b0===void 0)continue;if(b0.ftsRank!==void 0||b0.vecRank!==void 0)continue;let _$=Z.graphTypeWeights[p.type]??Z.graphTypeWeightDefault,x0=O0*G0*p.weight*_$*c(b0).weight,L0=m.get(p.id);if(L0===void 0)m.set(p.id,{cand:b0,rrf:0,score:x0,depth:p.depth}),X0[p.depth-1]=(X0[p.depth-1]??0)+1,n.set(p.id,x0);else if(x0>L0.score)L0.score=x0,L0.depth=p.depth,n.set(p.id,x0)}let _0=[...m.values()];_0.sort((p,G0)=>G0.score-p.score||(p.cand.id<G0.cand.id?-1:1));let q0=b.reduce((p,G0)=>G0.depth===1?p+1:p,0),P0={maxHops:Z.graphMaxHops,byDepth:Array.from({length:Math.max(0,Math.min(Z.graphMaxHops,2))},(p,G0)=>X0[G0]??0),hop2Capped:B>0&&q0>B,inHits:0},o6=[...e,..._0.slice(0,l)];o6.sort((p,G0)=>G0.score-p.score||(p.cand.id<G0.cand.id?-1:1));let k7=o6.slice(0,Y).map((p,G0)=>{let O0=p.cand.vecDistance!==void 0&&u!==void 0&&d!==void 0&&d>0?(u-p.cand.vecDistance)/d:void 0,b0=c(p.cand);return{id:p.cand.id,rank:G0+1,score:p.score,rrf:p.rrf,sources:[...p.cand.sources],...p.cand.ftsRank!==void 0?{ftsRank:p.cand.ftsRank}:{},...p.cand.vecRank!==void 0?{vecRank:p.cand.vecRank}:{},...p.cand.vecDistance!==void 0?{vecDistance:p.cand.vecDistance}:{},...O0!==void 0?{vecConfidence:O0}:{},...p.depth!==void 0?{graphDepth:p.depth}:{},kind:p.cand.node.kind,layer:p.cand.node.layer,priority:p.cand.node.priority,updatedAt:p.cand.node.fresh_at,title:p.cand.node.title,excerpt:p.cand.node.excerpt,...b0.state!==null?{anchorState:b0.state}:{},...b0.weight!==1?{anchorWeight:b0.weight}:{}}}),yW={...P0,inHits:k7.reduce((p,G0)=>G0.graphDepth!==void 0?p+1:p,0)},fW=new Set;for(let p of k7)for(let G0 of p.sources)fW.add(G0);let iF=k7.length>0&&k.hits===0&&fW.has("vector");if(iF)K.push("vector-only: lexical gave no candidates \u2014 the whole result rests on "+"a single weak vector with no confirmation (S47: MRR ~0.24 on this model)");if(D)w=`strict AND gave no candidates (${G.terms.length} ${G.terms.length===1?"term":"terms"}) \u2014 `+`the pool was built by fallback stage '${R}' (${Js[R]??"fallback"})${F?" with a full-match boost":""}, BM25 ranking; ${w}`;let c3;if(k7.length===0){let p=Q();if(p.size===0)c3={code:"store_empty",text:"this tier has no visible nodes \u2014 there is nothing to search, which is not 'not found'",corpusSize:0,corpusAtLeast:!1};else{let G0=p.atLeast?"1000+":String(p.size),O0=S==="used"||S==="empty"?"lexical and vector both ran":`the vector branch did not take part (${S})`,b0=`${G.terms.length} ${G.terms.length===1?"term":"terms"}`,_$=P===0?`strict AND, ${b0}`:D?`fallback stage '${R}', ${b0}`:`strict AND and ${P} fallback ${P===1?"stage":"stages"}, ${b0} \u2014 no match at any`;c3={code:"no_match",text:`none of the ${G0} visible nodes matched the query (${_$}); ${O0}`,corpusSize:p.size,corpusAtLeast:p.atLeast}}}return{hits:k7,mode_used:{sources:[...fW].sort(),vector:S,lexical:k,vectorOnly:iF,...c3!==void 0?{emptyReason:c3}:{},why:w,trigger:g,roundTrips:W,vectorRoundTrips:V,degraded:K,graphSeeds:"lexical",graph:yW,cache:"off"}}}function Us($){if($.endsWith("*"))return $;let X=$.slice(1,-1);if(X.includes(" ")||X.includes('""')||X.length<6)return $;return`"${X.slice(0,Math.max(5,X.length-3))}"*`}function Ks($){return Number.isFinite($)?$.toFixed(3):"n/a"}var BU,ZL,YL,q$,mV0,uV0,lV0,pa,na=12,da=100,eN=`
|
|
2783
|
+
END`}function aa($,X){let Z=$.fts??X.missingRank,Y=$.vec??X.missingRank;return X.weightFts/(X.rrfK+Z)+X.weightVec/(X.rrfK+Y)}function ra($,X,Z){let Y=$.priority,z=1+(Y===0?Z.priorityBoostP0:0)+(Y===1?Z.priorityBoostP1:0)-(Y===3?Z.priorityPenaltyP3:0),J=Math.max(0,Math.floor((X-$.updatedAt)/sa)),U=1+Z.freshnessAmplitude*Math.exp(-J/Z.freshnessTauDays),W=(Z.layerWeights[Z.profile]??BU[Z.profile])[Math.min(3,Math.max(0,$.layer))];return z*U*W}function ta($,X){if($===null||$.length===0)return $L;let Z=null;for(let Y of $.split(",")){let z=Y.indexOf(":"),J=z<0?Y:Y.slice(0,z),U=z<0?Number.NaN:Number(Y.slice(z+1)),K;if(J==="stale")K={weight:X.anchorStateWeights.stale,state:"stale"};else if(J==="lost")K={weight:X.anchorStateWeights.lost,state:"lost"};else if(J==="drifted")K={weight:X.anchorDriftWeight&&Number.isFinite(U)?Math.min(1,Math.max(0,U)):1,state:"drifted"};else K=$L;if(Z===null||K.weight>Z.weight||K.weight===Z.weight&&K.state===null)Z=K}return Z??$L}function ea($,X){if($.length<X)return Number.NaN;let Z=$.map((J)=>-J).sort((J,U)=>U-J),Y=Z[0],z=Z[Math.floor(Z.length/2)];if(!(Y>0))return 0;return(Y-z)/Y}function $s($,X,Z,Y=!1){let z=ia($),J=z.filter(ca).length,U=ea(X,Z.spreadMinHits),K=J>0&&X.length>0,W=X.length<Z.minLexicalHits&&!(Z.anchorHitSuppressesFewResults&&K),V=Number.isFinite(U)&&U<Z.minBm25Spread,G=z.length<=Z.shortQueryTerms&&J===0,H=[];if(W)H.push("few_results");if(V)H.push("low_bm25_spread");if(G)H.push("short_query_no_anchor");if(Y)H.push("lexical_fallback");return{fired:H.length>0,reasons:H,checks:{fewResults:W,lowBm25Spread:V,shortQueryNoAnchor:G,lexicalFallback:Y},anchorHit:K,metrics:{lexicalHits:X.length,bm25Spread:U,queryTerms:z.length,anchorTerms:J}}}function t_($,X,Z,Y=[]){return{hits:[],mode_used:{sources:[],vector:"skipped",lexical:Ys,vectorOnly:!1,emptyReason:Z,why:$,trigger:Zs,roundTrips:X,vectorRoundTrips:0,degraded:Y,graphSeeds:"lexical",graph:Xs,cache:"off"}}}function zs($){let X=$.mode_used;if(X.degraded.length>0)return!1;return X.vector!=="unavailable"&&X.vector!=="degraded"}function XL($,X,Z){return{hits:$.hits,mode_used:{...$.mode_used,cache:X,...Z===void 0?{}:{roundTrips:Z,vectorRoundTrips:0}}}}function XI($,X){let Z=X.cache;if(Z===void 0)return XL(e_($,X),"off");let Y=a_($),z=s_({text:X.text,scopes:X.scopes,layerMin:X.layerMin??0,layerMax:X.layerMax??3,limit:$I(X.limit),vectorMode:X.vectorMode??"auto",caller:X.caller,config:{...q$,...X.config}}),J=(X.cacheClock??Date.now)(),U=Z.get(z,Y,J);if(U.outcome==="hit")return XL(U.value,"hit",1);let K=e_($,X);return Z.set(z,Y,J,K,zs(K)),XL(K,"miss",K.mode_used.roundTrips+1)}function e_($,X){let Z={...q$,...X.config},Y=$I(X.limit),z=X.now??Date.now(),J=X.layerMin??0,U=X.layerMax??3,K=[],W=0,V=0,G=WU(X.text),H=[X.caller.ownerId,X.caller.teamId,X.caller.agentId,JSON.stringify(X.caller.principals)],N=JSON.stringify([...X.scopes]),Q=()=>{if(X.scopes.length===0)return{size:0,atLeast:!1};W++;let p=$.all(LU.hybridCorpusSize,[N,J,U,...H])[0]?.n??0;return{size:Math.min(p,1000),atLeast:p>1000}};if(G===null){let p=Q();return t_("empty query: no terms left after parsing",W,{code:"empty_query",text:"query contains no words: no terms left after parsing \u2014 "+"nothing to search for, the database is not the cause",corpusSize:p.size,corpusAtLeast:p.atLeast})}if(X.scopes.length===0)return t_("empty scope list: a query without a partition key is not run (S27)",W,{code:"no_scopes",text:"a query without a partition key (empty scope list) is not run \u2014 S27",corpusSize:0,corpusAtLeast:!1});let L=Z.graphMaxHops>=1?Z.graphSeeds:0,B=Z.graphMaxHops>=2&&Z.graphDecayByHop.length>=2?Z.graphHop2Seeds:0,T=(p)=>{let G0=$.all(LU.hybridLexicalPass,[p,N,J,U,...H,Z.poolSize,L,Z.graphMinEdgeWeight,B,Z.graphHopFanout]);W++;let O0=new Map,b0=[],_$=new Map,x0=[];for(let L0 of G0){let h8={id:L0.id,kind:L0.kind,layer:L0.layer,priority:L0.priority,updated_at:L0.updated_at,fresh_at:L0.fresh_at,title:L0.title,excerpt:L0.excerpt,anchors:L0.anchors},E4=O0.get(L0.id)??{id:L0.id,node:h8,sources:new Set};if(L0.fts_rank!==null){if(E4.ftsRank=L0.fts_rank,E4.sources.add("fts"),L0.bm25!==null)b0.push(L0.bm25),_$.set(L0.id,L0.bm25)}else if(L0.via_id!==null)x0.push({id:L0.id,viaId:L0.via_id,weight:L0.edge_weight??0,type:L0.edge_type??"",depth:L0.depth}),E4.sources.add("graph");O0.set(L0.id,E4)}return{byId:O0,bm25:b0,bm25ById:_$,graphRaw:x0}},q={prefix_and:G.prefixAnd===G.and?"":G.prefixAnd,prefix_relaxed:G.terms.length>=Z.fallbackMinTerms?G.prefixRelaxed:"",prefix_relaxed2:G.terms.length>=Z.fallbackMinTerms&&G.terms.length<=Z.relaxed2MaxTerms?G.prefixRelaxed2:"",prefix_or:G.terms.length>=Z.fallbackMinTerms||G.prefixOr!==G.and?G.prefixOr:"",or:G.terms.length>=Z.fallbackMinTerms?G.or:""},j=Z.lexicalMode==="or_always"&&q.or!=="",O=T(j?G.or:G.and),A=j?0:O.bm25.length,R=j?"or":"and",D=!1,F=!1,P=0;if(Z.lexicalMode==="and_then_fallback"&&O.bm25.length===0)for(let p of Z.fallbackStages){let G0=q[p];if(G0===""||G0===G.and)continue;P++;let O0=T(G0);if(O0.bm25.length>0){O=O0,R=p,D=!0;break}}if(R!=="and"&&R!=="prefix_and"&&Z.orCoverageBoost&&O.bm25.length>1){let p=[...O.bm25ById.keys()],G0=new Map;for(let O0 of $.all(LU.hybridOrCoverage,[JSON.stringify(R==="or"?[...G.terms]:[...G.terms].map(Us)),JSON.stringify(p)]))G0.set(O0.id,O0.cov);if(W++,G0.size>0)F=!0,p.slice().sort((b0,_$)=>{let x0=(G0.get(_$)??0)-(G0.get(b0)??0);if(x0!==0)return x0;let L0=(O.bm25ById.get(b0)??0)-(O.bm25ById.get(_$)??0);if(L0!==0)return L0;return b0<_$?-1:1}).forEach((b0,_$)=>{let x0=O.byId.get(b0);if(x0!==void 0)x0.ftsRank=_$+1})}let{byId:M,bm25:E,graphRaw:b}=O,k={operator:R,fallbackUsed:D,andHits:A,hits:E.length,terms:G.terms.length,stagesTried:P,coverageApplied:F},y=X.vectorMode??"auto",g=$s(X.text,E,Z,D),S,w,h,u,d;if(y==="never")h=!1,S="disabled",w="vector branch explicitly off (vectorMode: never)";else if(y==="always")h=!0,S="used",w="vector branch unconditionally on (vectorMode: always) \u2014 the reference for comparison";else if(g.fired)h=!0,S="used",w=`lexical fell short: ${g.reasons.join(", ")}`;else h=!1,S="skipped",w=`lexical is enough (${g.metrics.lexicalHits} candidates, BM25 spread ${Ks(g.metrics.bm25Spread)}, anchor terms ${g.metrics.anchorTerms}/${g.metrics.queryTerms}) \u2014 `+"query embedding not computed, ~23 ms saved (S31)";if(h){let p=X.embedQuery?X.embedQuery():null;if(p===null)S="unavailable",w=`${w}; but there is no query embedding \u2014 results only from lexical and graph`,K.push("vector-branch: query embedding unavailable (no embedder or cache) \u2014 "+"the vector branch did not take part");else{let O0=(X.vectorSource??o_)($,{vector:p,scopes:X.scopes,layerMin:X.layerMin,layerMax:X.layerMax,caller:X.caller,limit:Z.poolSize,candidateLimit:200});if(V+=O0.degraded?1:O0.reranked?4:2,O0.degraded)S="degraded",w=`${w}; vector source degraded: ${O0.reason??"no reason given"}`,K.push(`vector-source: ${O0.reason??"degraded"}`);else if(O0.hits.length===0)S="empty",w=`${w}; the vector branch ran but gave no candidates`;else{u=O0.distanceMean,d=O0.distanceStd;let b0=new Map(O0.hits.map((x0)=>[x0.id,x0.distance])),_$=[];for(let x0 of O0.hits){let L0=M.get(x0.id);if(L0===void 0)_$.push(x0.id);else L0.vecRank=x0.rank,L0.vecDistance=x0.distance,L0.sources.add("vector")}if(_$.length>0){let x0=$.all(LU.hybridHydrate,[JSON.stringify(_$),N,J,U,...H]);W++;let L0=new Map(x0.map((h8)=>[h8.id,h8]));for(let h8 of O0.hits){if(M.has(h8.id))continue;let E4=L0.get(h8.id);if(E4===void 0)continue;M.set(h8.id,{id:h8.id,node:E4,vecRank:h8.rank,vecDistance:b0.get(h8.id),sources:new Set(["vector"])})}}}}}let a=new Map,e=[],r=new Map,c=(p)=>{let G0=r.get(p.id);if(G0===void 0)r.set(p.id,G0=ta(p.node.anchors,Z));return G0};for(let p of M.values()){if(p.ftsRank===void 0&&p.vecRank===void 0)continue;let G0=aa({fts:p.ftsRank,vec:p.vecRank},Z),O0=G0*ra({priority:p.node.priority,layer:p.node.layer,updatedAt:p.node.fresh_at},z,Z)*c(p).weight;a.set(p.id,O0),e.push({cand:p,rrf:G0,score:O0})}let l=2*(L+B),m=new Map,n=new Map(a),X0=[];for(let p of[...b].sort((G0,O0)=>G0.depth-O0.depth)){if(p.depth>Z.graphMaxHops)continue;let G0=Z.graphDecayByHop[p.depth-1];if(G0===void 0)continue;let O0=n.get(p.viaId);if(O0===void 0)continue;let b0=M.get(p.id);if(b0===void 0)continue;if(b0.ftsRank!==void 0||b0.vecRank!==void 0)continue;let _$=Z.graphTypeWeights[p.type]??Z.graphTypeWeightDefault,x0=O0*G0*p.weight*_$*c(b0).weight,L0=m.get(p.id);if(L0===void 0)m.set(p.id,{cand:b0,rrf:0,score:x0,depth:p.depth}),X0[p.depth-1]=(X0[p.depth-1]??0)+1,n.set(p.id,x0);else if(x0>L0.score)L0.score=x0,L0.depth=p.depth,n.set(p.id,x0)}let _0=[...m.values()];_0.sort((p,G0)=>G0.score-p.score||(p.cand.id<G0.cand.id?-1:1));let q0=b.reduce((p,G0)=>G0.depth===1?p+1:p,0),P0={maxHops:Z.graphMaxHops,byDepth:Array.from({length:Math.max(0,Math.min(Z.graphMaxHops,2))},(p,G0)=>X0[G0]??0),hop2Capped:B>0&&q0>B,inHits:0},o6=[...e,..._0.slice(0,l)];o6.sort((p,G0)=>G0.score-p.score||(p.cand.id<G0.cand.id?-1:1));let k7=o6.slice(0,Y).map((p,G0)=>{let O0=p.cand.vecDistance!==void 0&&u!==void 0&&d!==void 0&&d>0?(u-p.cand.vecDistance)/d:void 0,b0=c(p.cand);return{id:p.cand.id,rank:G0+1,score:p.score,rrf:p.rrf,sources:[...p.cand.sources],...p.cand.ftsRank!==void 0?{ftsRank:p.cand.ftsRank}:{},...p.cand.vecRank!==void 0?{vecRank:p.cand.vecRank}:{},...p.cand.vecDistance!==void 0?{vecDistance:p.cand.vecDistance}:{},...O0!==void 0?{vecConfidence:O0}:{},...p.depth!==void 0?{graphDepth:p.depth}:{},kind:p.cand.node.kind,layer:p.cand.node.layer,priority:p.cand.node.priority,updatedAt:p.cand.node.fresh_at,title:p.cand.node.title,excerpt:p.cand.node.excerpt,...b0.state!==null?{anchorState:b0.state}:{},...b0.weight!==1?{anchorWeight:b0.weight}:{}}}),yW={...P0,inHits:k7.reduce((p,G0)=>G0.graphDepth!==void 0?p+1:p,0)},fW=new Set;for(let p of k7)for(let G0 of p.sources)fW.add(G0);let iF=k7.length>0&&k.hits===0&&fW.has("vector");if(iF)K.push("vector-only: lexical gave no candidates \u2014 the whole result rests on "+"a single weak vector with no confirmation (S47: MRR ~0.24 on this model)");if(D)w=`strict AND gave no candidates (${G.terms.length} ${G.terms.length===1?"term":"terms"}) \u2014 `+`the pool was built by fallback stage '${R}' (${Js[R]??"fallback"})${F?" with a full-match boost":""}, BM25 ranking; ${w}`;let c3;if(k7.length===0){let p=Q();if(p.size===0)c3={code:"store_empty",text:"this tier has no visible nodes \u2014 there is nothing to search, which is not 'not found'",corpusSize:0,corpusAtLeast:!1};else{let G0=p.atLeast?"1000+":String(p.size),O0=S==="used"||S==="empty"?"lexical and vector both ran":`the vector branch did not take part (${S})`,b0=`${G.terms.length} ${G.terms.length===1?"term":"terms"}`,_$=P===0?`strict AND, ${b0}`:D?`fallback stage '${R}', ${b0}`:`strict AND and ${P} fallback ${P===1?"stage":"stages"}, ${b0} \u2014 no match at any`;c3={code:"no_match",text:`none of the ${G0} visible nodes matched the query (${_$}); ${O0}`,corpusSize:p.size,corpusAtLeast:p.atLeast}}}return{hits:k7,mode_used:{sources:[...fW].sort(),vector:S,lexical:k,vectorOnly:iF,...c3!==void 0?{emptyReason:c3}:{},why:w,trigger:g,roundTrips:W,vectorRoundTrips:V,degraded:K,graphSeeds:"lexical",graph:yW,cache:"off"}}}function Us($){if($.endsWith("*"))return $;let X=$.slice(1,-1);if(X.includes(" ")||X.includes('""')||X.length<6)return $;return`"${X.slice(0,Math.max(5,X.length-3))}"*`}function Ks($){return Number.isFinite($)?$.toFixed(3):"n/a"}var BU,ZL,YL,q$,iV0,nV0,dV0,pa,na=12,da=100,eN=`
|
|
2784
2784
|
(
|
|
2785
2785
|
(n.acl = 'private' AND n.owner_id = ?5)
|
|
2786
2786
|
OR (n.acl = 'team' AND n.team_id = ?6)
|
|
@@ -2790,7 +2790,7 @@ SELECT g.src AS id, n.kind AS kind, n.title AS title, n.status AS status,
|
|
|
2790
2790
|
WHERE g.node_id = n.id
|
|
2791
2791
|
AND g.principal IN (SELECT value FROM json_each(?8))
|
|
2792
2792
|
))
|
|
2793
|
-
)`,LU,sa=86400000,$L,
|
|
2793
|
+
)`,LU,sa=86400000,$L,oV0,Xs,Zs,Ys,Js;var TU=v(()=>{o();tN();VU();K8();rN();o();o();BU=Object.freeze({prime:[0.9,1,1.1,1.2],deep:[1.15,1.15,1,0.9],balanced:[1,1,1,1]}),ZL=Object.freeze([0.5,0.5]),YL=Object.freeze({mentions:0.5,touches:0.5}),q$={rrfK:60,missingRank:1000,poolSize:100,weightFts:1,weightVec:1,minLexicalHits:5,minBm25Spread:0.15,spreadMinHits:3,anchorHitSuppressesFewResults:!0,shortQueryTerms:2,lexicalMode:"and_then_fallback",fallbackStages:["prefix_and","prefix_relaxed"],fallbackMinTerms:2,relaxed2MaxTerms:4,orCoverageBoost:!1,profile:"balanced",priorityBoostP0:0.3,priorityBoostP1:0.15,priorityPenaltyP3:0.1,freshnessAmplitude:0.25,freshnessTauDays:90,layerWeights:BU,graphSeeds:15,graphMaxHops:2,graphDecayByHop:ZL,graphMinEdgeWeight:0.3,graphHopFanout:64,graphHop2Seeds:12,graphTypeWeights:YL,graphTypeWeightDefault:1,anchorStateWeights:Object.freeze({stale:0.5,lost:0.2}),anchorDriftWeight:!0},iV0=Object.freeze({anchorStateWeights:Object.freeze({stale:1,lost:1}),anchorDriftWeight:!1}),nV0=Object.freeze({graphMaxHops:0}),dV0=Object.freeze({graphMaxHops:1}),pa=/[\p{L}\p{N}_][\p{L}\p{N}_.\-/]*/gu;LU=Z0({hybridLexicalPass:{name:"hybridLexicalPass",sql:`
|
|
2794
2794
|
WITH matches AS MATERIALIZED (
|
|
2795
2795
|
SELECT n.id AS node_id,
|
|
2796
2796
|
bm25(nodes_fts, 10.0, 1.0, 1.0) AS bm25_score
|
|
@@ -2980,7 +2980,7 @@ SELECT g.src AS id, n.kind AS kind, n.title AS title, n.status AS status,
|
|
|
2980
2980
|
AND n.scope IN (SELECT value FROM json_each(?2))
|
|
2981
2981
|
AND n.layer BETWEEN ?3 AND ?4
|
|
2982
2982
|
AND ${eN}${i0("n")}
|
|
2983
|
-
`,params:["ids","scopes","layer_min","layer_max","owner_id","team_id","agent_id","principals"]}});$L=Object.freeze({weight:1,state:null});
|
|
2983
|
+
`,params:["ids","scopes","layer_min","layer_max","owner_id","team_id","agent_id","principals"]}});$L=Object.freeze({weight:1,state:null});oV0=Object.freeze({priorityBoostP0:0,priorityBoostP1:0,priorityPenaltyP3:0,freshnessAmplitude:0,layerWeights:Object.freeze({prime:[1,1,1,1],deep:[1,1,1,1],balanced:[1,1,1,1]})});Xs=Object.freeze({maxHops:0,byDepth:Object.freeze([]),hop2Capped:!1,inHits:0}),Zs={fired:!1,reasons:[],checks:{fewResults:!0,lowBm25Spread:!1,shortQueryNoAnchor:!1,lexicalFallback:!1},anchorHit:!1,metrics:{lexicalHits:0,bm25Spread:Number.NaN,queryTerms:0,anchorTerms:0}},Ys={operator:"and",fallbackUsed:!1,andHits:0,hits:0,terms:0,stagesTried:0,coverageApplied:!1};Js={prefix_and:"word forms differ, intersection by prefixes",prefix_relaxed:"an extra word in the question, all terms but one",prefix_relaxed2:"two extra words, all terms but any two",prefix_or:"union of prefixes",or:"flat union of terms"}});var eV0,$G0;var ZI=v(()=>{TU();eV0=Object.freeze({priorityBoostP0:q$.priorityBoostP0,priorityBoostP1:q$.priorityBoostP1,priorityPenaltyP3:q$.priorityPenaltyP3,freshnessAmplitude:q$.freshnessAmplitude,freshnessTauDays:q$.freshnessTauDays,layerWeights:BU}),$G0=Object.freeze({graphMaxHops:q$.graphMaxHops,graphDecayByHop:ZL,graphSeeds:q$.graphSeeds,graphMinEdgeWeight:q$.graphMinEdgeWeight,graphHopFanout:q$.graphHopFanout,graphHop2Seeds:q$.graphHop2Seeds,graphTypeWeights:YL,graphTypeWeightDefault:q$.graphTypeWeightDefault})});function Qs($){if($===void 0||!Number.isFinite($)||$<=0)return Ws;return Math.min(Math.floor($),100)}function Ns($){if($===void 0||!Number.isFinite($))return Gs;return Math.max(1,Math.floor($))}function Ls($){if($===void 0||!Number.isFinite($)||$<0)return Hs;return $}function Bs($,X,Z,Y){let z=$.filter((K)=>K.queried),J=$.filter((K)=>!K.queried),U=[`queried ${z.length} of ${$.length}: ${z.map((K)=>K.id).join(", ")}`];if(J.length>0)U.push(`skipped ${J.length}: ${J.map((K)=>`${K.id} (${K.skipped})`).join(", ")}`);if(U.push(`cap ${X}, deadline ${Z} ms`),!Y)U.push("personal tier not open \u2014 no second DB query was made (I1, S41)");return U.join("; ")}async function YI($){let X={...q$,...$.config},Z=Qs($.limit),Y=Math.min(100,Z*Vs),z=Ns($.maxSources),J=Ls($.deadlineMs),U=$.clock??(()=>performance.now()),{sources:K,maxSources:W,deadlineMs:V,clock:G,...H}=$;if(K.length===0)throw Error("federatedSearch: at least one source required");let N=[],Q=[],L=U();for(let D=0;D<K.length;D++){let F=K[D],P=F.weight??1;if(D>=z){N.push({id:F.id,kind:F.kind,weight:P,queried:!1,skipped:`over the cap of ${z} sources (I1: recall budget 25 ms)`,hits:0});continue}let _=U()-L;if(D>0&&_>=J){N.push({id:F.id,kind:F.kind,weight:P,queried:!1,skipped:`deadline ${J} ms exhausted at source #${D} (spent ${Math.round(_*10)/10} ms)`,hits:0});continue}let M=U(),E;try{let k=await F.open();E=XI(k,{...H,scopes:F.scopes,limit:Y})}catch(k){if(D===0)throw k;N.push({id:F.id,kind:F.kind,weight:P,queried:!1,skipped:`failed to open: ${k instanceof Error?k.message:String(k)}`,hits:0});continue}let b=U()-M;N.push({id:F.id,kind:F.kind,weight:P,queried:!0,mode:E.mode_used,hits:E.hits.length,took_ms:Math.round(b*10)/10}),Q.push({source:F,hits:E.hits,mode:E.mode_used})}let B=new Map;for(let D=0;D<Q.length;D++){let F=Q[D];for(let P of F.hits){let _=B.get(P.id);if(_===void 0)B.set(P.id,{hit:P,ranks:new Map([[F.source.id,P.rank]]),firstOrder:D});else _.ranks.set(F.source.id,P.rank)}}let T=[...B.values()].map((D)=>{let F=0;for(let M of Q){let E=M.source.weight??1,b=D.ranks.get(M.source.id)??X.missingRank;F+=E/(X.rrfK+b)}let P=Q[D.firstOrder].source,_=Q.filter((M)=>D.ranks.has(M.source.id)).map((M)=>M.source.id);return{entry:D,source:P.id,tier:P.kind,tierRank:D.ranks.get(P.id),foundIn:_,score:F}});T.sort((D,F)=>F.score-D.score||(D.entry.hit.id<F.entry.hit.id?-1:1));let q=T.slice(0,Z).map((D,F)=>({...D.entry.hit,rank:F+1,source:D.source,tier:D.tier,tierRank:D.tierRank,foundIn:D.foundIn})),j=N.filter((D)=>D.queried).length,O=N.find((D)=>D.kind==="project"&&D.queried),A=N.find((D)=>D.kind==="personal"&&D.queried),R=K.some((D)=>D.kind==="personal");return{hits:q,mode_used:{sources:N,queried:j,skipped:N.length-j,cap:z,deadlineMs:J,took_ms:Math.round((U()-L)*10)/10,why:Bs(N,z,J,R),project:(O??N.find((D)=>D.queried)).mode,...A!==void 0?{personal:A.mode}:{},personalQueried:A!==void 0}}}var Ws=12,Vs=3,Gs=8,Hs=18;var zI=v(()=>{TU()});function qU($){return $.length+1}function Ts($,X=300){if($===null||$===void 0)return"";if(X<1)return"";let Z=$.replace(/\s+/gu," ").trim(),Y=[...Z];if(Y.length<=X)return Z;let z=Y.slice(0,X+1).join(""),J=Math.floor(X*0.6),U=-1;for(let W=z.length-1;W>=J;W--){let V=z[W];if((V==="."||V==="!"||V==="?")&&(W+1>=z.length||z[W+1]===" ")){U=W+1;break}}if(U<0){let W=z.lastIndexOf(" ");U=W>=J?W:X-1}if(U>0){let W=z.charCodeAt(U-1);if(W>=55296&&W<=56319)U-=1}let K=z.slice(0,U).trimEnd();return/[.!?\u2026]$/.test(K)?K:`${K}\u2026`}function qs($,X){return $===X.trim()||$===X.replace(/\s+/gu," ").trim()}function KI($,X,Z,Y=performance.now){let z=Number.isFinite(Z.charBudget)&&Z.charBudget>0?Math.floor(Z.charBudget):0,J=Math.min(Math.max(Z.reserveRatio??0.1,0),0.9),U=Math.max(0,Math.floor(z*(1-J))),K=Z.cruxMax??300,W=Z.timeoutMs??20,G=(Z.startAt??Y())+Math.max(0,W),H=[],N=0,Q=0;for(let T of $){let q=X.content(T),j=X.excerpt(T)||q||"",O=Ts(j,K);if(q!==null&&q!==void 0&&qs(O,q)){let R=qU(q.trim());if(N+R<=U){H.push({item:T,kind:"full",text:q.trim()}),N+=R;continue}Q++;continue}let A=qU(O);if(N+A<=U)H.push({item:T,kind:"crux",text:O}),N+=A;else Q++}let L=!1,B=0;if(Z.upgradeContent??!0)for(let T=0;T<H.length;T++){let q=H[T];if(Y()>=G){L=!0;break}if(q.kind==="full")continue;let j=X.content(q.item);if(j===null||j===void 0)continue;let O=j.trim();if(O.length===0)continue;let A=qU(q.text),R=qU(O);if(N-A+R<=U)H[T]={item:q.item,kind:"full",text:O},N+=R-A,B++}return{items:H,omitted:Q,timedOut:L,usedChars:N,upgrades:B}}var JI=12000,UI=20;var DY=v(()=>{VU();rN();TU();ZI();zI();tN();K8()});var TI={};s(TI,{stopEmbedDaemon:()=>QI,spawnEmbedDaemon:()=>KL,runEmbedDaemon:()=>LI,requestVector:()=>jU,pingEmbedDaemon:()=>UL,openWarmQueue:()=>BI,enqueueWarmJob:()=>FU,embedViaDaemon:()=>As,embedSocketPath:()=>RY,embedJobQueries:()=>E5,dbWatchIntervalFromEnv:()=>NI,createEmbeddCommand:()=>Ms,WARM_JOB_PRIORITY:()=>HI,WARM_JOB_KIND:()=>I5,WARM_JOB_ENTITY:()=>k5,DEFAULT_DAEMON_TTL_MS:()=>OU,DB_WATCH_INTERVAL_MS:()=>zL});import{createHash as Fs}from"crypto";import{existsSync as MY,unlinkSync as WI}from"fs";import{tmpdir as js}from"os";import{join as VI,resolve as GI}from"path";function FU($,X,Z=Date.now()){let Y=$.all(E5.warm_pending,[I5,k5])[0];if(Y!==void 0&&Y.attempts>=Y.max_attempts)return!1;return $.run(E5.warm_enqueue,[I5,k5,X,HI,Z]),!0}function RY($){let X=Fs("sha1").update(GI($)).digest("hex").slice(0,16);return VI(js(),`myc-embed-${X}.sock`)}async function JL($,X,Z){if(!MY($))return{ok:!1,why:"no_socket"};return await Cs($,X,Z)}async function Cs($,X,Z){return await new Promise((Y)=>{let z=!1,J=!1,U="",K=(V)=>{if(z)return;z=!0,clearTimeout(W),Y(V)},W=setTimeout(()=>K({ok:!1,why:"timeout"}),Z);Bun.connect({unix:$,socket:{open(V){J=!0,V.write(`${JSON.stringify(X)}
|
|
2984
2984
|
`)},data(V,G){U+=G.toString("utf8");let H=U.indexOf(`
|
|
2985
2985
|
`);if(H<0)return;let N=U.slice(0,H);try{K({ok:!0,reply:JSON.parse(N)})}catch{K({ok:!1,why:"bad_reply"})}V.end()},error(){K({ok:!1,why:J?"bad_reply":"refused"})},close(){K({ok:!1,why:J?"bad_reply":"refused"})}}}).catch(()=>K({ok:!1,why:"refused"}))})}async function UL($,X=200){let Z=await JL($,{op:"ping"},X);if(!Z.ok||Z.reply.ok!==!0)return null;let Y=Z.reply;return{state:String(Y.state??"unknown"),dim:Number(Y.dim??0),warmMs:Number(Y.warm_ms??0),served:Number(Y.served??0)}}async function jU($,X,Z){if(!MY($))return{ok:!1,daemon:"absent",reason:"no warm embedder"};let Y=await JL($,{op:"embed",text:X},Z);if(!Y.ok){if(Y.why==="refused")return{ok:!1,daemon:"absent",reason:"socket left by a dead daemon"};return{ok:!1,daemon:"error",reason:`no reply within ${Z} ms`}}let z=Y.reply;if(z.ok!==!0){let K=String(z.reason??"no reason given");return{ok:!1,daemon:K.includes("warming")?"warming":"error",reason:K}}let J=z.vec;if(!Array.isArray(J)||J.length===0)return{ok:!1,daemon:"error",reason:"the daemon returned an empty vector"};let U=new Float32Array(J.length);for(let K=0;K<J.length;K++){let W=Number(J[K]);if(!Number.isFinite(W))return{ok:!1,daemon:"error",reason:`component ${K} is not finite`};U[K]=W}return{ok:!0,vec:U}}async function As($,X,Z){let Y=await jU($,X,Z);return Y.ok?Y.vec:null}async function QI($,X=500){let Z=await JL($,{op:"stop"},X);return Z.ok&&Z.reply.ok===!0}function KL($,X){try{let Z=process.argv[1],Y=typeof Z==="string"&&/\.(ts|js|mjs)$/.test(Z),z=[process.execPath,...Y?[Z]:[],"embedd","--db",$,...X!==void 0?["--ttl",String(X)]:[]];Bun.spawn(z,{stdin:"ignore",stdout:"ignore",stderr:"ignore",detached:!0}).unref()}catch{}}function NI($=process.env){let X=$.MYC_EMBED_DB_WATCH_MS;if(X===void 0||X.trim().length===0)return zL;let Z=Number(X);return Number.isFinite(Z)&&Z>=10?Math.floor(Z):zL}async function LI($){let X=RY($.dbPath),Z=$.ttlMs??OU;if(await UL(X,300))return{socketPath:X,warmMs:0,state:"already-running",served:0,leased:!1,stopped:"signal"};if(MY(X))try{WI(X)}catch{}let Y="warming",z=0,J=0,U="idle",K,W,V=new Promise((A)=>{W=A}),G=()=>{if(K!==void 0)clearTimeout(K);K=setTimeout(()=>{U="idle",W?.()},Z)},H,N=()=>{H=setInterval(()=>{if(MY($.dbPath))return;U="db_gone",W?.()},$.dbWatchMs??NI())},Q,L;try{L=Bun.listen({unix:X,socket:{data(A,R){G();for(let D of R.toString("utf8").split(`
|
|
2986
2986
|
`)){if(D.trim().length===0)continue;let F;try{F=JSON.parse(D)}catch{A.write(`${JSON.stringify({ok:!1,reason:"bad JSON"})}
|
|
@@ -3020,32 +3020,32 @@ SELECT e.src AS owner
|
|
|
3020
3020
|
`)}
|
|
3021
3021
|
`}function iI($,X){let Z=$.resolve(X),Y=X.join(" ");if(!Z)return gU($);let z=[`myc ${Y} \u2014 ${Z.summary}`,"",`Usage: myc ${Y} [args] [flags]`];if(Z.help)z.push("",Z.help);let J=$.flagsFor(X);if(J.length>0)z.push("","Flags:",cI(J));let U=Z.subcommands??[];if(U.length>0){z.push("","Subcommands:");let K=U.map((V)=>[` ${V.name}`,V.summary]),W=Math.max(...K.map(([V])=>V.length));for(let[V,G]of K)z.push(`${V.padEnd(W)} ${G}`)}return z.push("","Global flags: see `myc --help`."),`${z.join(`
|
|
3022
3022
|
`)}
|
|
3023
|
-
`}function kY($,X,Z,Y){let z={code:"usage.invalid",msg:$,exit:2,hint:Y},J=new I2;if(X.json||X.ndjson)return{code:2,stdout:s7(TH(Z,z,J))};return{code:2,stdout:"",stderr:mJ(z,J,X.color)}}function gr($){return $.top.flatMap((X)=>[X,...X.subcommands??[]].map((Z)=>({c:Z,top:X}))).filter(({c:X})=>X.remote===!0).map(({c:X,top:Z})=>X===Z?X.name:`${Z.name} ${X.name}`).sort()}function
|
|
3024
|
-
`};if(K.help===!0){if(z.length===0)await Z.materializeAll();return{code:0,stdout:z.length>0?iI(Z,z):gU(Z)}}if(z.length===0){if(W.length>0)return kY(`unknown command '${W[0]}'`,U,J);return await Z.materializeAll(),{code:0,stdout:gU(Z)}}let V=Z.resolve(z);if(!V)return kY(`unknown command '${J}'`,U,J);if(!V.handler){let
|
|
3025
|
-
`),!0}catch{return!1}}function tI($,X,Z){let Y=nz(X,$);if(Y===null)return{...Z,status:"unreachable",current:$,reason:CL({code:"bad_version",version:X},!0)};if(Y===1)return{...Z,status:"update_available",current:$,latest:X,upgrade:bU};return{...Z,status:Y===-1?"ahead":"up_to_date",current:$,latest:X}}function AL($=process.env){return`${($.MYC_REGISTRY??
|
|
3026
|
-
`)}function G9($,X="init"){let Z
|
|
3023
|
+
`}function kY($,X,Z,Y){let z={code:"usage.invalid",msg:$,exit:2,hint:Y},J=new I2;if(X.json||X.ndjson)return{code:2,stdout:s7(TH(Z,z,J))};return{code:2,stdout:"",stderr:mJ(z,J,X.color)}}function gr($){return $.top.flatMap((X)=>[X,...X.subcommands??[]].map((Z)=>({c:Z,top:X}))).filter(({c:X})=>X.remote===!0).map(({c:X,top:Z})=>X===Z?X.name:`${Z.name} ${X.name}`).sort()}function wr($,X,Z){let Y=new I2;if(X.json||X.ndjson)return{code:$.exit,stdout:FL(Z,$,Y)};return{code:$.exit,stdout:"",stderr:mJ({code:$.code,msg:$.msg,hint:$.hint},Y,X.color)}}function FL($,X,Z){return s7(TH($,{code:X.code,msg:X.msg,exit:X.exit,hint:X.hint},Z))}async function EY($,X={}){let Z=X.registry??E7;await Z.materialize(cC($));let Y=OH($,Z);if(!Y.ok&&Z.pending>0)await Z.materializeAll(),Y=OH($,Z);let z=Y.ok?Y.argv.commandPath:[],J=z.join(" "),U={json:IY(Y,"json"),ndjson:IY(Y,"ndjson"),strict:IY(Y,"strict"),quiet:IY(Y,"quiet"),color:(X.tty??!1)&&!IY(Y,"no-color")&&!X.env?.NO_COLOR,db:pI(Y,"db"),directory:pI(Y,"directory")};if(U.json&&U.ndjson)return kY("flags --json and --ndjson are mutually exclusive",U,J);if(!Y.ok)return kY(Y.failure.msg,U,J,Y.failure.hint);let{flags:K,positionals:W}=Y.argv;if(K.version===!0)return{code:0,stdout:`myc ${E0} (schema ${e4})
|
|
3024
|
+
`};if(K.help===!0){if(z.length===0)await Z.materializeAll();return{code:0,stdout:z.length>0?iI(Z,z):gU(Z)}}if(z.length===0){if(W.length>0)return kY(`unknown command '${W[0]}'`,U,J);return await Z.materializeAll(),{code:0,stdout:gU(Z)}}let V=Z.resolve(z);if(!V)return kY(`unknown command '${J}'`,U,J);if(!V.handler){let F=(V.subcommands??[]).map((P)=>P.name);return kY(`command '${J}' requires a subcommand`,U,J,`subcommands: ${F.join(", ")}`)}let G=typeof K.server==="string"&&String(K.server).trim()!=="",H=(X.env?.MYC_SERVER??process.env.MYC_SERVER??"").trim()!=="",N=new I2;if(V.remote!==!0){if(G)return await Z.materializeAll(),wr({ok:!1,code:"precond.no_remote",msg:`command '${J}' works only with a local database: it cannot talk to a server yet`,exit:5,hint:"commands that can: "+gr(Z).join(", ")},U,J);if(H&&!br.has(J))N.add("server.local_only",`'${J}' has no server mode: MYC_SERVER is set, so this run used the LOCAL database`)}let Q={args:W,flags:K,globals:U,warn:(F,P)=>N.add(F,P),diagnostics:N},L;try{L=await V.handler(Q)}catch(F){L={ok:!1,code:"internal.unexpected",msg:F instanceof Error?F.message:String(F),exit:1}}if(L.ok){let{drainAfterCommand:F}=await Promise.resolve().then(() => (TL(),lI));await F(U,X.env)}let B=!L.ok?L.exit:U.strict&&N.size>0?6:0;if(U.json)return{code:B,stdout:L.ok?s7(fX(J,L.data,L.meta,N)):FL(J,L,N)};if(U.ndjson){if(L.ok&&AH(L.data)){let{data:F,meta:P}=L;function*_(){for(let M of F)yield s7(fX(J,M,P,N))}return{code:B,stdout:_()}}return{code:B,stdout:L.ok?s7(fX(J,L.data,L.meta,N)):FL(J,L,N)}}if(!L.ok)return{code:B,stdout:"",stderr:mJ(L,N,U.color)};let T=PH(N,U.color),q=V.renderHuman?V.renderHuman(L.data,Q):nC(L.data,U.color),j=V.machineStdout?.(Q)===!0,O=j?"":T,A=j&&T.length>0?{stderr:T}:{};if(typeof q==="string")return{code:B,stdout:(U.quiet?"":q)+O,...A};let R=U.quiet?[]:q;function*D(){yield*R,yield O}return{code:B,stdout:D(),...A}}function jL($){let X=0,Z=!1,Y=[],z=()=>{if(X>0&&!Z)return;let U=Y;Y=[];for(let K of U)K()},J=$.write.bind($);return $.write=(U,K,W)=>{let V=typeof K==="function"?K:W,G=typeof K==="string"?K:void 0;if((typeof U==="string"?U.length:U instanceof Uint8Array?U.byteLength:1)===0||Z)return J(U,G,V);return X++,J(U,G,(N)=>{if(X--,N)Z=!0;V?.(N),z()})},$.on("error",()=>{Z=!0,z()}),()=>X===0||Z?Promise.resolve():new Promise((U)=>Y.push(U))}function W9(){if(qL===null)qL={stdout:jL(process.stdout),stderr:jL(process.stderr)};return qL}async function OL($){let X=W9();if(process.exitCode=$.code,typeof $.stdout==="string")process.stdout.write($.stdout);else for(let Z of $.stdout)process.stdout.write(Z);if(await X.stdout(),$.stderr!==void 0)process.stderr.write($.stderr);await X.stderr(),process.exit($.code)}var E0,br,qL=null;var v8=v(()=>{o();V0();xJ();iC();$X();o();$X();E0=X2;br=new Set(["bootstrap","callers","doctor","embedd","init","merge-driver","mcp","models","queue","release","report","run","serve","skeleton","statusline","unwire","version","viz","wire"])});import{existsSync as xr,mkdirSync as hr,readFileSync as mr,writeFileSync as ur}from"fs";import{homedir as lr}from"os";import{dirname as pr,join as cr}from"path";function v5($=process.env){let X=($.MYC_UPDATE_CHECK??"").trim().toLowerCase();if(X==="0"||X==="off"||X==="false"||X==="no")return"off";if(X==="1"||X==="on"||X==="true"||X==="yes"||X==="auto")return"auto";return"manual"}function sI($=process.env){return cr($.MYC_HOME??lr(),".myc","update-check.json")}function rI($=process.env){let X=sI($);try{if(!xr(X))return null;let Z=JSON.parse(mr(X,"utf8"));if(typeof Z.checked_at!=="number"||!Number.isFinite(Z.checked_at))return null;if(Z.package!==N4)return null;let Y=typeof Z.latest==="string"?Z.latest:null,z=typeof Z.build==="string"?Z.build:null,J=Y===null?dr(Z.failure)??{code:"unknown"}:null;return{package:N4,latest:Y,checked_at:Z.checked_at,build:z,failure:J}}catch{return null}}function dr($){if($===null||typeof $!=="object")return null;let X=$,Z=(z)=>typeof X[z]==="string"?X[z]:null,Y=(z)=>typeof X[z]==="number"&&Number.isFinite(X[z])?X[z]:null;switch(X.code){case"http_status":{let z=Y("status");return z===null?null:{code:"http_status",status:z}}case"timeout":{let z=Y("ms");return z===null?null:{code:"timeout",ms:z}}case"bad_json":case"network":{let z=Z("detail");return z===null?null:{code:X.code,detail:z}}case"bad_version":{let z=Z("version");return z===null?null:{code:"bad_version",version:z}}case"no_latest":case"unknown":return{code:X.code};default:return null}}function CL($,X){switch($.code){case"http_status":return`the registry answered ${$.status}`;case"bad_json":return`the registry response did not parse as JSON${X?`: ${$.detail}`:""}`;case"no_latest":return"the registry response has no dist-tags.latest";case"timeout":return`the registry did not answer within ${$.ms} ms`;case"network":return`network unavailable${X?`: ${$.detail}`:""}`;case"bad_version":return`the registry returned a version that could not be parsed${X?`: ${JSON.stringify($.version)}`:""}`;case"unknown":return X?"the last attempt failed, no reason recorded":"the last attempt failed; its reason was recorded by another myc build (re-check: `myc version --check`)"}}function oI($,X=process.env){let Z=sI(X);try{return hr(pr(Z),{recursive:!0}),ur(Z,`${JSON.stringify($,null,2)}
|
|
3025
|
+
`),!0}catch{return!1}}function tI($,X,Z){let Y=nz(X,$);if(Y===null)return{...Z,status:"unreachable",current:$,reason:CL({code:"bad_version",version:X},!0)};if(Y===1)return{...Z,status:"update_available",current:$,latest:X,upgrade:bU};return{...Z,status:Y===-1?"ahead":"up_to_date",current:$,latest:X}}function AL($=process.env){return`${($.MYC_REGISTRY??ir).replace(/\/+$/,"")}/${N4.replace("/","%2f")}`}function or($=process.env){let X=$.MYC_UPDATE_CHECK_TIMEOUT_MS;if(X===void 0||X.trim().length===0)return dI;let Z=Number(X);return Number.isFinite(Z)&&Z>0?Math.floor(Z):dI}async function ar($={}){let X=$.env??process.env,Z=$.timeoutMs??or(X),Y=$.fetchImpl??globalThis.fetch,z=AL(X),J=new AbortController,U=setTimeout(()=>J.abort(),Z);try{let K=await Y(z,{signal:J.signal,headers:{accept:"application/vnd.npm.install-v1+json"}});if(!K.ok)return{ok:!1,failure:{code:"http_status",status:K.status}};let W;try{W=await K.json()}catch(H){return{ok:!1,failure:{code:"bad_json",detail:aI(H)}}}let G=W?.["dist-tags"]?.latest;if(typeof G!=="string"||G.length===0)return{ok:!1,failure:{code:"no_latest"}};return{ok:!0,latest:G}}catch(K){return{ok:!1,failure:K instanceof Error&&(K.name==="AbortError"||K.name==="TimeoutError")?{code:"timeout",ms:Z}:{code:"network",detail:aI(K)}}}finally{clearTimeout(U)}}function aI($){return $ instanceof Error?$.message:String($)}function PL($){let X=$.env??process.env,Z=$.now??Date.now(),Y=v5(X);if($.offline===!0||Y==="off")return{status:"disabled",current:$.current,source:"none",reason:eI(X,$.offline===!0)};let z=rI(X);if(z===null)return{status:"never_checked",current:$.current,source:"none"};let J=Math.max(0,Z-z.checked_at);if(z.latest===null)return{status:"unreachable",current:$.current,source:"cache",checked_at:z.checked_at,age_ms:J,reason:CL(z.failure??{code:"unknown"},z.build===$.current)};return tI($.current,z.latest,{source:"cache",checked_at:z.checked_at,age_ms:J})}function eI($,X){if(X)return"the --offline flag forbids the network for this call";return`env MYC_UPDATE_CHECK=${JSON.stringify($.MYC_UPDATE_CHECK??"")}`}async function $k($){let X=$.env??process.env,Z=$.now??Date.now(),Y=v5(X);if($.offline===!0||Y==="off")return{status:"disabled",current:$.current,source:"none",reason:eI(X,$.offline===!0)};let z=await ar($);if(!z.ok)return oI({package:N4,latest:null,checked_at:Z,build:$.current,failure:z.failure},X),{status:"unreachable",current:$.current,source:"network",checked_at:Z,age_ms:0,reason:CL(z.failure,!0)};let J=tI($.current,z.latest,{source:"network",checked_at:Z,age_ms:0});return oI({package:N4,latest:J.status==="unreachable"?null:z.latest,checked_at:Z,build:$.current,failure:J.status==="unreachable"?{code:"bad_version",version:z.latest}:null},X),J}function sr($=process.env,X=Date.now()){if(v5($)!=="auto")return!1;let Z=rI($);if(Z===null)return!0;return X-Z.checked_at>=nr}function wU($=process.env,X=rr,Z=process.env){if(Z.NODE_ENV==="test"&&$.MYC_UPDATE_CHECK!=="1")return!1;if(!sr($))return!1;try{let Y=process.argv[1],z=typeof Y==="string"&&/\.(ts|js|mjs)$/.test(Y);return X([process.execPath,...z?[Y]:[],"version","--check","--quiet"]),!0}catch{return!1}}function rr($){Bun.spawn($,{stdin:"ignore",stdout:"ignore",stderr:"ignore",detached:!0}).unref()}function tr($){let X=Math.floor($/3600000);if(X<1)return`${Math.max(1,Math.floor($/60000))} min ago`;if(X<48)return`${X} h ago`;return`${Math.floor(X/24)} d ago`}function DL($){let X=$.age_ms!==void 0&&$.source==="cache"?` (${tr($.age_ms)})`:"";switch($.status){case"update_available":return`update: ${$.current} \u2192 ${$.latest}${X} \xB7 ${bU}`;case"unreachable":return`updates not checked: ${$.reason}${X}`;case"never_checked":return"updates never checked \u2014 `myc version --check`";case"disabled":case"up_to_date":case"ahead":return null}}function xU($,X=process.env){try{return DL(PL({current:$,env:X}))}catch{return null}}var N4="@aistastudio/myc",ir="https://registry.npmjs.org",nr=86400000,dI=3000,bU;var hU=v(()=>{o();bU=`bun install -g ${N4}`});import{existsSync as er,readFileSync as $t,writeFileSync as Xk}from"fs";import{join as Xt}from"path";function Zt(){return["# myc (S42): local files \u2014 kept out of git","# the oplog, meta.json, .gitattributes and workspace.toml are committed as is",...Zk,""].join(`
|
|
3026
|
+
`)}function G9($,X="init"){let Z=Xt($,".gitignore");if(!er(Z)){Xk(Z,Zt(),"utf8");return}let Y=$t(Z,"utf8"),z=new Set(Y.split(`
|
|
3027
3027
|
`).map((K)=>K.trim())),J=Zk.filter((K)=>!z.has(K));if(J.length===0)return;let U=Y.length>0&&!Y.endsWith(`
|
|
3028
3028
|
`)?`
|
|
3029
3029
|
`:"";Xk(Z,`${Y}${U}# myc: added automatically by ${X}
|
|
3030
3030
|
${J.join(`
|
|
3031
3031
|
`)}
|
|
3032
|
-
`,"utf8")}var Zk;var ML=v(()=>{Zk=["myc.db","myc.db-wal","myc.db-shm","myc.db-journal","projections/","state.json","hooks.json","wire.json","bootstrap.cache.json","anchor-dirty.log"]});var Tk={};s(Tk,{createInitCommand:()=>
|
|
3032
|
+
`,"utf8")}var Zk;var ML=v(()=>{Zk=["myc.db","myc.db-wal","myc.db-shm","myc.db-journal","projections/","state.json","hooks.json","wire.json","bootstrap.cache.json","anchor-dirty.log"]});var Tk={};s(Tk,{createInitCommand:()=>Ft,adoptWorkspaceDb:()=>yL});import{existsSync as e8,mkdirSync as Yt,readdirSync as zt,readFileSync as vL,rmSync as Nk,writeFileSync as Yk}from"fs";import{basename as Jt,join as b6,resolve as zk}from"path";import{Database as vY}from"bun:sqlite";function Kt($){let X=$.toLowerCase().replace(/[^a-z0-9]/g,"");if(X.length===0||!/^[a-z]/.test(X))X=`w${X}`;X=X.slice(0,8);while(X.length<2)X+="0";return X}function Wt($){try{let X=Bun.spawnSync(["git","rev-parse","--show-toplevel"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(!X.success)return;let Z=X.stdout.toString().trim();return Z.length>0?Z:void 0}catch{return}}function Jk($){let X=C2($,HH);return X.indexDir||X.bin!==null}function Uk($){return vC($,HH,QH($))}function Kk($){return{mode:$.mode,id:$.id,state:$.state,reason:$.reason,degraded:$.degraded}}function Wk($,X){for(let Z of X.degraded)$.warn(Z,X.reason)}function Vk($){let X=b6($,".myc","myc.db"),Z,Y;try{let J=new vY(X,{readonly:!0});try{Z=L6(J)??void 0,Y=J.query("SELECT count(*) AS n FROM nodes").get()?.n??void 0}finally{J.close()}}catch{}let z;try{let J=b6($,".myc","workspace.toml");if(e8(J))z=/^slug\s*=\s*"([a-z][a-z0-9]{1,7})"/m.exec(vL(J,"utf8"))?.[1]}catch{}return{schemaVersion:Z,nodeCount:Y,slug:z}}function Lk($){let X=b6($,"workspace.toml");if(!e8(X))return;try{return/^slug\s*=\s*"([a-z][a-z0-9]{1,7})"/m.exec(vL(X,"utf8"))?.[1]}catch{return}}function Vt($){if(!e8($))return;try{let X=new vY($,{readonly:!0});try{let Y=X.query("SELECT value FROM myc_meta WHERE key = 'slug'").get()?.value;return typeof Y==="string"&&/^[a-z][a-z0-9]{1,7}$/.test(Y)?Y:void 0}finally{X.close()}}catch{return}}function Gt($){return`# myc workspace config \u2014 commit this file (per-machine settings go in local.toml)
|
|
3033
3033
|
`+`slug = "${$}"
|
|
3034
3034
|
# code intel: builtin (default) | auto | graft | off
|
|
3035
3035
|
code_intel = "${vX}"
|
|
3036
|
-
`}function Gk($,X){let Z=b6($,"workspace.toml");if(!e8(Z)){Yk(Z,
|
|
3036
|
+
`}function Gk($,X){let Z=b6($,"workspace.toml");if(!e8(Z)){Yk(Z,Gt(X),"utf8");return}let Y=vL(Z,"utf8"),z=`slug = "${X}"`,J=/^slug\s*=\s*"[^"]*"/m.test(Y)?Y.replace(/^slug\s*=\s*"[^"]*"/m,z):`${Y}${Y.endsWith(`
|
|
3037
3037
|
`)?"":`
|
|
3038
3038
|
`}${z}
|
|
3039
|
-
`;if(J!==Y)Yk(Z,J,"utf8")}function
|
|
3039
|
+
`;if(J!==Y)Yk(Z,J,"utf8")}function Qt($){for(let X of zt($)){if(Ht.has(X))continue;Nk(b6($,X),{recursive:!0,force:!0})}}async function Bk($,X,Z){I$();let Y=new vY($,{create:!0});try{for(let K of Ut)Y.exec(K);await i8(Y,{migrations:X$,writable:!0});let z=X$.reduce((K,W)=>Math.max(K,W.version),0),{siteId:J}=d8({meta:EX(Y),dbPath:$,mint:()=>n8(X)});Y.prepare(x.meta_set.sql).run("slug",X);let U=tJ(Z)??process.env.USER??"agent";return Y.prepare(x.meta_set.sql).run(x2,U),Nt(Y),{siteId:J,schemaVersion:z,actor:U}}finally{Y.close()}}function Nt($){$.exec("PRAGMA wal_checkpoint(TRUNCATE)")}async function yL($){let X=b6($,"myc.db");if(e8(X))return;let Z=Lk($);if(Z===void 0)return;G9($);try{let{siteId:Y,schemaVersion:z}=await Bk(X,Z,$);return{dbPath:X,slug:Z,siteId:Y,schemaVersion:z}}catch(Y){throw Nk(X,{force:!0}),Y}}function RL(){let $=S$();if(!$.exists)return{dir:$.dir,exists:!1};let X,Z;try{let Y=new vY($.dbPath,{readonly:!0});try{X=L6(Y)??void 0,Z=Y.query("SELECT count(*) AS n FROM nodes").get()?.n??void 0}finally{Y.close()}}catch{}return{dir:$.dir,exists:!0,schemaVersion:X,nodeCount:Z}}function _L($){if(!$.exists)return" \xB7 personal ~/.myc not created \u2014 create it: myc init --global";let X=$.nodeCount!==void 0?y5($.nodeCount):"? nodes";return` \u2713 personal ~/.myc schema v${$.schemaVersion??"?"}, ${X}`}function IL($){return` ${$.state==="ok"?"\xB7":"!"} code intel ${$.reason}`}function Hk($){return $===void 0?{}:{worktree:{dir:$.worktreeDir,main:$.mainRoot}}}function kL($,X){let Z=X?"the workspace already exists":"the workspace was created";return` ! git worktree ${$.dir} is a branch, not a project: ${Z} in the main tree ${$.main}. One workspace per repository: a second one would split the queue and memory, and claim would stop meaning anything`}function Qk($=process.env){return v5($)==="auto"?"this command made no network calls (the update check runs in a separate process)":"no network used"}function Lt($){let X=$,Z=[],Y=E0;if(X.idempotent){let J=X.db.nodeCount!==void 0?y5(X.db.nodeCount):"? nodes";if(Z.push(`myc ${Y} \xB7 .myc already exists (slug=${X.slug}, schema v${X.db.schemaVersion??"?"}, ${J})`),Z.push("nothing changed. to recreate: myc init --force (deletes the local database)"),X.worktree!==void 0)Z.push(kL(X.worktree,!0));return Z.push(IL(X.code_intel)),Z.push(_L(X.personal)),Z.push(`next: ${X.next}`),`${Z.join(`
|
|
3040
3040
|
`)}
|
|
3041
3041
|
`}if(X.adopted){if(Z.push(`myc ${Y} \xB7 clone ${X.dir} \xB7 slug=${X.slug} from .myc/workspace.toml (untouched)`),Z.push(""),X.worktree!==void 0)Z.push(kL(X.worktree,!1));return Z.push(` \u2713 .myc/myc.db created, sqlite, schema v${X.db.schemaVersion??"?"}, wal`),Z.push(" \xB7 .myc/workspace.toml came from git \u2014 the shared identity of the workspace"),Z.push(` \xB7 graft ${X.graft?"found":"not found"}`),Z.push(IL(X.code_intel)),Z.push(_L(X.personal)),Z.push(""),Z.push("next:"),Z.push(` ${X.next}`),Z.push(""),Z.push(`done in ${X.took_ms} ms \xB7 ${Qk()}`),`${Z.join(`
|
|
3042
3042
|
`)}
|
|
3043
|
-
`}let z=X.git.isGit?"git":"NOT a git repository";if(Z.push(`myc ${Y} \xB7 repo ${X.dir} (${z}) \xB7 slug=${X.slug}`),Z.push(""),Z.push(` \u2713 .myc/myc.db sqlite, schema v${X.db.schemaVersion??"?"}, wal`),Z.push(` \u2713 .myc/workspace.toml slug=${X.slug}`),X.actor!==void 0)Z.push(
|
|
3043
|
+
`}let z=X.git.isGit?"git":"NOT a git repository";if(Z.push(`myc ${Y} \xB7 repo ${X.dir} (${z}) \xB7 slug=${X.slug}`),Z.push(""),Z.push(` \u2713 .myc/myc.db sqlite, schema v${X.db.schemaVersion??"?"}, wal`),Z.push(` \u2713 .myc/workspace.toml slug=${X.slug}`),X.actor!==void 0)Z.push(Bt(X.actor));if(X.worktree!==void 0)Z.push(kL(X.worktree,!1));if(X.slug_changed!==void 0){let J=X.slug_changed.nodes;Z.push(` ! slug changed ${X.slug_changed.from} \u2192 ${X.slug_changed.to}: ${J!==void 0?y5(J):"existing nodes"} keep scope=${X.slug_changed.from} and are no longer visible; to revert: myc init --slug ${X.slug_changed.from}`)}if(Z.push(` \xB7 graft ${X.graft?"found":"not found"}`),Z.push(IL(X.code_intel)),Z.push(" \xB7 embeddings not downloaded \u2014 the model is a separate command, `myc models fetch`; "+"tasks work without it (BM25)"),Z.push(_L(X.personal)),!X.git.isGit)Z.push(" ! not a git repo code anchors will have no blob_hash");return Z.push(""),Z.push("next:"),Z.push(` ${X.next}`),Z.push(""),Z.push(`done in ${X.took_ms} ms \xB7 ${Qk()}`),`${Z.join(`
|
|
3044
3044
|
`)}
|
|
3045
|
-
`}function
|
|
3045
|
+
`}function Bt($){return` \u2713 actor ${$} (from git; override with $MYC_ACTOR)`}function y5($){return`${$} ${$===1?"node":"nodes"}`}function EL($){return`${$} oplog ${$===1?"operation":"operations"}`}function Tt($){let X=$.ops===void 0||$.nodes===void 0?"the database can't be read \u2014 its contents are unknown":`${y5($.nodes)}, ${EL($.ops)}`;return{ok:!1,code:"precond.personal_memory",msg:`${$.dir}: ${X}. The personal tier is not committed to git \u2014 there would be nothing `+"to restore it from, so --force here erases only what can be rebuilt and does not touch the memory",exit:5,hint:`copy it first: cp -R ${$.dir} ${$.dir}.bak \xB7 `+"erase it for good: myc init --global --force --wipe-memory"}}function qt($){let X=$,Z=[];if(X.idempotent){let Y=X.db.nodeCount!==void 0?y5(X.db.nodeCount):"? nodes";Z.push(`personal workspace already exists: ${X.dir} (schema v${X.db.schemaVersion??"?"}, ${Y})`),Z.push("nothing changed. to recreate: myc init --global --force (the memory survives; to erase it too, add --wipe-memory)")}else{let Y=X.wiped!==void 0&&!X.wiped.memory&&X.wiped.memoryKept.length>0;if(Z.push(Y?`personal workspace kept in place, only rebuildable files erased: ${X.dir}`:`personal workspace created: ${X.dir}`),X.wiped!==void 0&&X.wiped.memory){let z=X.wiped.nodes!==void 0?y5(X.wiped.nodes):"nodes",J=X.wiped.ops!==void 0?`, ${EL(X.wiped.ops)}`:"";Z.push(` ! memory erased ${z}${J} \u2014 nothing to restore it from, no copy left`)}if(Y&&X.wiped!==void 0){let z=X.wiped.nodes!==void 0?y5(X.wiped.nodes):"nodes",J=X.wiped.ops!==void 0?`, ${EL(X.wiped.ops)}`:"";if(Z.push(` \xB7 memory untouched ${z}${J} \xB7 ${X.wiped.memoryKept.join(", ")}`),X.wiped.entries.length>0)Z.push(` \u2713 erased (rebuildable) ${X.wiped.entries.join(", ")}`)}if(Z.push(` \u2713 myc.db sqlite, schema v${X.db.schemaVersion??"?"}, wal`),X.kept!==void 0&&X.kept.length>0)Z.push(` \xB7 left alone ${X.kept.join(", ")} \u2014 not created by myc`);Z.push(" \xB7 memory lands here only with an explicit --global on recall/remember; "+"by default writes go to the project .myc/ (S41)")}return Z.push(`next: ${X.next}`),Z.push(`done in ${X.took_ms} ms`),`${Z.join(`
|
|
3046
3046
|
`)}
|
|
3047
|
-
`}function
|
|
3048
|
-
`}}}var
|
|
3047
|
+
`}function Ft(){return{name:"init",summary:"create a workspace: .myc/ with sqlite db, migrations, site_id, slug",flags:[{name:"slug",value:"string",description:"workspace slug (default: from directory name)"},{name:"force",description:"wipe an existing .myc/ and recreate it"},{name:"global",description:"create/report the personal workspace ~/.myc instead of the project one (S41: memory written explicitly with --global, never silently)"},{name:"wipe-memory",description:"with --global --force: also erase the personal memory itself (db + oplog). "+"Nothing restores it \u2014 this is the explicit consent, not a convenience flag"}],help:"Zero questions, and no network call of its own: the update check is off by default (MYC_UPDATE_CHECK=1 turns it on, and even then it runs as a detached process this command never waits for). Autodetects the git root and slug from the directory name; both are shown, never confirmed. Re-running on an existing workspace is a no-op (exit 0) unless --force is given. The embeddings model is "+"not downloaded here \u2014 that's `myc models fetch`, and its absence never blocks task work. "+"`--global` targets the personal workspace ~/.myc (S41) instead: it is never created silently by a plain `myc init`, only reported. There `--force` erases only what can be rebuilt (caches); the memory itself is not in git and nothing restores it, so erasing it "+"takes a second, explicit `--wipe-memory` \u2014 a flag, not a question, because agents run "+"without a terminal.",handler:async($)=>{let X=performance.now();wU();let Z=w2($);if(Z!==void 0)return Z;if(K0($,"global")){let _=e$(),M=K0($,"force"),E=K0($,"wipe-memory"),b=S$(_);if(E&&!M)return{ok:!1,code:"usage.wipe_memory_without_force",msg:"--wipe-memory is permission for a destructive step, not the step itself: it only works together with --force",exit:2,hint:"myc init --global --force --wipe-memory"};if(b.exists&&!M){let w=RL(),h={dir:b.dir,slug:W8,idempotent:!0,db:{path:b.dbPath,schemaVersion:w.schemaVersion,nodeCount:w.nodeCount},next:"myc recall <query>",took_ms:Math.max(1,Math.round(performance.now()-X))};return{ok:!0,data:h,meta:{took_ms:h.took_ms,idempotent:!0}}}let k=hH(_);if(M&&k.hasMemory&&!E)return Tt(k);let y=M?mH(k,{memory:E}):[],g=await xH(_),S={dir:g.dir,slug:W8,idempotent:!1,db:{path:g.dbPath,schemaVersion:g.schemaVersion},siteId:g.siteId,...M?{wiped:{entries:[...y],memory:E,memoryKept:E?[]:[...k.memory],nodes:k.nodes,ops:k.ops},kept:[...k.kept]}:{},next:"myc recall <query>",took_ms:Math.max(1,Math.round(performance.now()-X))};return{ok:!0,data:S,meta:{took_ms:S.took_ms,idempotent:!1}}}let Y=zk($.globals.directory??process.cwd()),z=$.args[0]!==void 0?zk(Y,$.args[0]):Y,J=Wt(z),U=b2(z);if(U!==void 0&&!e8(U.mainRoot))return{ok:!1,code:"precond.worktree_main_missing",msg:`${U.worktreeDir} is a git worktree and the workspace belongs to the main tree, but ${U.mainRoot} does not exist: it was moved or deleted (the .git file points to ${U.gitDir})`,exit:5,hint:"git worktree repair <path to the main tree>"};let K=U?.mainRoot??J??z,W=K0($,"force"),V=b6(K,".myc"),G=b6(V,"myc.db"),H=$.flags.slug,N=typeof H==="string"&&/^[a-z][a-z0-9]{1,7}$/.test(H)?H:void 0,Q=Lk(V)??Vt(G),L=N??Q??Kt(Jt(K)),B=Q!==void 0&&L!==Q,T=e8(G);if(T&&!W&&!B){if(G9(V),!e8(b6(V,"workspace.toml")))Gk(V,L);let _=Vk(K),M=Uk(K);Wk($,M);let E={dir:K,slug:L,git:{root:J,isGit:J!==void 0},graft:Jk(K),code_intel:Kk(M),idempotent:!0,adopted:!1,db:{path:G,schemaVersion:_.schemaVersion,nodeCount:_.nodeCount},personal:RL(),...Hk(U),next:"myc ready",took_ms:Math.max(1,Math.round(performance.now()-X))};return{ok:!0,data:E,meta:{took_ms:E.took_ms,idempotent:!0}}}let q=T?Vk(K).nodeCount:void 0;if(W&&e8(V))Qt(V);Yt(V,{recursive:!0}),G9(V);let j=!T&&Q!==void 0&&!B,O,A,R;if(!e8(G)){let _=await Bk(G,L,K);A=_.siteId,O=_.schemaVersion,R=_.actor}else{let _=new vY(G);try{_.prepare(x.meta_set.sql).run("slug",L),O=L6(_)??void 0}finally{_.close()}}if(!e8(b6(V,"workspace.toml"))||B)Gk(V,L);if(B)$.warn("slug.changed",`workspace slug ${Q} \u2192 ${L}: ${q!==void 0?`${q} existing ${q===1?"node":"nodes"}`:"existing nodes"} keep scope=${Q} and are no longer visible; to revert: myc init --slug ${Q}`);let D=Jk(K),F=Uk(K);if(Wk($,F),$.warn("degraded.embeddings","embedding model not downloaded \u2014 recall falls back to BM25 until `myc models fetch`"),J===void 0)$.warn("degraded.git","not a git repository \u2014 code anchors will have no blob_hash");let P={dir:K,slug:L,git:{root:J,isGit:J!==void 0},graft:D,code_intel:Kk(F),idempotent:!1,adopted:j,...B?{slug_changed:{from:Q,to:L,nodes:q}}:{},db:{path:G,schemaVersion:O},...Hk(U),personal:RL(),...A!==void 0?{siteId:A}:{},...R!==void 0?{actor:R}:{},next:j?"myc import":'myc task "<first task>" -p P1',took_ms:Math.max(1,Math.round(performance.now()-X))};return{ok:!0,data:P,meta:{took_ms:P.took_ms,idempotent:!1}}},renderHuman:($,X)=>{let Z=typeof $==="object"&&$!==null&&"git"in $?Lt($):qt($),Y=xU(E0);return Y===null?Z:`${Z}${Y}
|
|
3048
|
+
`}}}var Ut,Ht;var fL=v(()=>{n0();BH();V0();v8();hU();j0();R8();ML();Ut=["PRAGMA journal_mode = WAL","PRAGMA synchronous = NORMAL","PRAGMA foreign_keys = ON"];Ht=new Set(["graph","workspace.toml","config.json",".gitignore"])});var Ak={};s(Ak,{modelsCommand:()=>It,createModelsCommand:()=>Ck});import{join as qk}from"path";import{rm as jt,stat as Fk}from"fs/promises";function mU($){if($<1024)return`${$}B`;let X=["KB","MB","GB"],Z=$/1024,Y=0;while(Z>=1024&&Y<X.length-1)Z/=1024,Y++;return`${Z.toFixed(1)}${X[Y]}`}async function Ct($,X){let Z=$.getModelSpec(X),Y=Z.files.reduce((W,V)=>W+V.bytes,0),z=$.modelDir(X);if(await $.isModelPresent(X)){let W=Z.files[0],V=W?(await $.sha256File(qk(z,W.name))).slice(0,12):null;return{id:X,status:"present",dim:Z.dim,expectedBytes:Y,localBytes:Y,fingerprint:V,badFiles:[]}}let J=!1,U=0,K=[];for(let W of Z.files){let V=qk(z,W.name),G;try{G=(await Fk(V)).size}catch{continue}J=!0,U+=G;let H=await $.sha256File(V).catch(()=>null);if(G!==W.bytes||H!==W.sha256)K.push(W.name)}return{id:X,status:J?"corrupt":"absent",dim:Z.dim,expectedBytes:Y,localBytes:U,fingerprint:null,badFiles:K}}function jk($,X){return $.args[0]??X.DEFAULT_MODEL_ID}function Ok($,X){return{ok:!1,code:"notfound.model",msg:`unknown model "${X}"; known: ${Object.keys($.MODELS).join(", ")}`,exit:3}}function At($){return process.stdout.isTTY===!0&&!$.globals.json&&!$.globals.ndjson&&!$.globals.quiet}function Pt($){let X=$.totalBytes!==null?` ${Math.min(100,Math.round($.loadedBytes/$.totalBytes*100))}%`:"",Z=$.totalBytes!==null?`${mU($.loadedBytes)}/${mU($.totalBytes)}`:mU($.loadedBytes);return`\r${$.file}${X} ${Z}\x1B[K`}function Mt($){return{name:"list",summary:"known models: staged locally or not, size, fingerprint",handler:async()=>{let X=await Promise.all(Object.keys($.MODELS).map((Z)=>Ct($,Z)));return{ok:!0,data:X.map((Z)=>({id:Z.id,status:Z.status,dim:Z.dim,size:Z.status==="absent"?"-":mU(Z.localBytes),fingerprint:Z.fingerprint??"-"})),meta:{count:X.length}}}}}function Rt($){return{name:"fetch",summary:"download a model with sha256 verification (idempotent)",help:"Calling it again for a model that is already installed downloads nothing.",handler:async(X)=>{let Z=jk(X,$);if(!(Z in $.MODELS))return Ok($,Z);if(await $.isModelPresent(Z)){let U=$.getModelSpec(Z);return{ok:!0,data:{modelId:Z,dir:$.modelDir(Z),downloaded:[],skipped:U.files.map((K)=>K.name),alreadyPresent:!0},meta:{note:"model already installed, the network was not used"}}}let Y=At(X),z=0,J=Y?(U)=>{let K=Pt(U);z=K.length,process.stdout.write(K)}:void 0;try{let U=await $.fetchModel({modelId:Z,onProgress:J});if(Y&&z>0)process.stdout.write("\r\x1B[K");let K=Object.keys(U.files).filter((W)=>!U.skipped.includes(W));return{ok:!0,data:{modelId:U.modelId,dir:U.dir,downloaded:K,skipped:U.skipped,alreadyPresent:!1}}}catch(U){if(Y&&z>0)process.stdout.write("\r\x1B[K");if(U instanceof R6)return{ok:!1,code:Dt[U.code]??"internal.unexpected",msg:U.message,exit:U.code==="unknown_model"?3:1};throw U}}}}function _t($){return{name:"rm",summary:"remove a locally staged model",handler:async(X)=>{let Z=jk(X,$);if(!(Z in $.MODELS))return Ok($,Z);let Y=$.modelDir(Z),z=!0;try{await Fk(Y)}catch{z=!1}if(!z)return{ok:!0,data:{modelId:Z,dir:Y,removed:!1}};return await jt(Y,{recursive:!0,force:!0}),{ok:!0,data:{modelId:Z,dir:Y,removed:!0}}}}}function Ck($=Ot){return{name:"models",summary:"manage local embedding models",subcommands:[Mt($),Rt($),_t($)]}}var Ot,Dt,It;var Pk=v(()=>{dX();V0();Ot={MODELS:z4,DEFAULT_MODEL_ID:Z$,getModelSpec:s8,modelDir:($)=>a8($),sha256File:bX,isModelPresent:($)=>p2($),fetchModel:($)=>X1($)};Dt={checksum_mismatch:"internal.checksum_mismatch",network_error:"internal.network",http_error:"internal.http",fs_error:"internal.fs",unknown_model:"notfound.model"};It=Ck()});var o0;var SL=v(()=>{o0=["claude","codex","opencode","kimi","mcode","mimo"]});function Ik($){return $.usdPerMCacheRead===0&&$.usdPerMCacheWrite===0}function kk($,X){return X-$>_k}function Dk($){if(o0.includes($))return $;throw new F$("usage.harness",`unknown harness "${$}"; allowed: ${o0.join(", ")}`)}function Mk($){if(f5.includes($))return $;throw new F$("usage.effort",`unknown reasoning effort "${$}"; allowed: ${f5.join(", ")}`)}function Rk($){if(!Number.isFinite($.usdPerMIn)||$.usdPerMIn<0)throw new F$("usage.price","usdPerMIn must be a number \u2265 0");if(!Number.isFinite($.usdPerMOut)||$.usdPerMOut<0)throw new F$("usage.price","usdPerMOut must be a number \u2265 0");for(let[X,Z]of[["usdPerMCacheRead",$.usdPerMCacheRead],["usdPerMCacheWrite",$.usdPerMCacheWrite]]){if(Z===void 0)continue;if(!Number.isFinite(Z)||Z<0)throw new F$("usage.price",`${X} must be a number \u2265 0`)}if(!Number.isInteger($.validFrom)||$.validFrom<=0)throw new F$("usage.price","a price must be stored with a date: validFrom (unix ms) is missing")}function gL($){return{modelId:$.model_id,family:$.family,version:$.version,parentModelId:$.parent_model_id,harness:$.harness,effort:$.effort,tokensPerSec:$.tokens_per_sec,strengths:JSON.parse($.strengths),active:$.active===1,createdAt:$.created_at,updatedAt:$.updated_at}}function bL($){return{modelId:$.model_id,validFrom:$.valid_from,usdPerMIn:$.usd_per_m_in,usdPerMOut:$.usd_per_m_out,usdPerMCacheRead:$.usd_per_m_cache_read,usdPerMCacheWrite:$.usd_per_m_cache_write}}class L4{#$;#X;constructor($,X=Date.now){this.#$=$,this.#X=X}#Z($){this.#$.exec("BEGIN IMMEDIATE");try{$(),this.#$.exec("COMMIT")}catch(X){throw this.#$.exec("ROLLBACK"),X}}addModel($){if($.modelId.trim()==="")throw new F$("usage.input","modelId must be non-empty");if($.family.trim()==="")throw new F$("usage.input","family must be non-empty");Dk($.harness);let X=$.effort??"medium";Mk(X),Rk($.price);let Z=this.#X();try{this.#Z(()=>{this.#$.query(`INSERT INTO swarm_model (model_id, family, version, parent_model_id, harness,
|
|
3049
3049
|
effort, tokens_per_sec, strengths, active,
|
|
3050
3050
|
created_at, updated_at)
|
|
3051
3051
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 1, ?9, ?9)`).run($.modelId,$.family,$.version??"",$.parentModelId??null,$.harness,X,$.tokensPerSec??60,JSON.stringify($.strengths??[]),Z),this.#z($.modelId,$.price)})}catch(Y){if(Y instanceof Error&&/UNIQUE constraint failed: swarm_model/.test(Y.message))throw new F$("conflict.model",`model "${$.modelId}" is already in the roster; change it with update`);throw Y}return this.#Y($.modelId)}updateModel($,X){if(this.#Y($),X.harness!==void 0)Dk(X.harness);if(X.effort!==void 0)Mk(X.effort);if(X.price!==void 0)Rk(X.price);let Z=this.#X();return this.#Z(()=>{let Y=[],z=[],J=(U,K)=>{Y.push(`${U} = ?${z.length+1}`),z.push(K)};if(X.family!==void 0)J("family",X.family);if(X.harness!==void 0)J("harness",X.harness);if(X.effort!==void 0)J("effort",X.effort);if(X.version!==void 0)J("version",X.version);if(X.parentModelId!==void 0)J("parent_model_id",X.parentModelId);if(X.tokensPerSec!==void 0)J("tokens_per_sec",X.tokensPerSec);if(X.strengths!==void 0)J("strengths",JSON.stringify(X.strengths));if(Y.length>0)J("updated_at",Z),this.#$.query(`UPDATE swarm_model SET ${Y.join(", ")} WHERE model_id = ?${z.length+1}`).run(...z,$);if(X.price!==void 0)this.#z($,X.price)}),this.#Y($)}disableModel($){return this.#J($,!1),this.#Y($)}enableModel($){return this.#J($,!0),this.#Y($)}getModel($,X=this.#X()){let Z=this.#$.query("SELECT * FROM swarm_model WHERE model_id = ?1").get($);if(Z===null)return;return this.#U(gL(Z),X)}listModels($={}){let X=$.now??this.#X();return($.includeInactive===!0?this.#$.query("SELECT * FROM swarm_model ORDER BY model_id").all():this.#$.query("SELECT * FROM swarm_model WHERE active = 1 ORDER BY model_id").all()).map((Y)=>this.#U(gL(Y),X))}priceHistory($){return this.#Y($),this.#$.query("SELECT * FROM swarm_model_price WHERE model_id = ?1 ORDER BY valid_from DESC").all($).map(bL)}#z($,X){this.#$.query(`INSERT INTO swarm_model_price
|
|
@@ -3059,12 +3059,12 @@ code_intel = "${vX}"
|
|
|
3059
3059
|
usd_per_m_cache_write = excluded.usd_per_m_cache_write`).run($,X.validFrom,X.usdPerMIn,X.usdPerMOut,X.usdPerMCacheRead??0,X.usdPerMCacheWrite??0)}#J($,X){this.#Y($),this.#$.query("UPDATE swarm_model SET active = ?1, updated_at = ?2 WHERE model_id = ?3").run(X?1:0,this.#X(),$)}#Y($){let X=this.#$.query("SELECT * FROM swarm_model WHERE model_id = ?1").get($);if(X===null)throw new F$("notfound.model",`model "${$}" not found in the roster`);return gL(X)}#U($,X){let Z=this.#K($.modelId,X);return{model:$,price:Z,priceAgeDays:Z===null?null:Math.floor((X-Z.validFrom)/86400000),priceStale:Z!==null&&kk(Z.validFrom,X),cacheUnpriced:Z!==null&&Ik(Z)}}#K($,X){let Z=this.#$.query(`SELECT * FROM swarm_model_price
|
|
3060
3060
|
WHERE model_id = ?1 AND valid_from <= ?2
|
|
3061
3061
|
ORDER BY valid_from DESC LIMIT 1`).get($,X);if(Z!==null)return bL(Z);let Y=this.#$.query(`SELECT * FROM swarm_model_price
|
|
3062
|
-
WHERE model_id = ?1 ORDER BY valid_from ASC LIMIT 1`).get($);return Y===null?null:bL(Y)}}var f5,_k=7776000000,F$;var wL=v(()=>{SL();SL();f5=["low","medium","high"];F$=class F$ extends Error{code;constructor($,X){super(X);this.name="RosterError",this.code=$}}});function S5($,X){for(let Z of X){let Y=$[Z];if(Y!==void 0&&Y.trim()!=="")return Y.trim()}return null}function Ek($){if($===null)return null;if(!/^\d+$/.test($))return null;let X=Number($);return Number.isSafeInteger(X)&&X>0?X:null}function uU($){let X=S5($,
|
|
3063
|
-
`)}async function lk($,X){let Z=new Map,Y=[];for(let U of X){let K;try{K=xk(pL($,U))}catch{Z.set(U,
|
|
3062
|
+
WHERE model_id = ?1 ORDER BY valid_from ASC LIMIT 1`).get($);return Y===null?null:bL(Y)}}var f5,_k=7776000000,F$;var wL=v(()=>{SL();SL();f5=["low","medium","high"];F$=class F$ extends Error{code;constructor($,X){super(X);this.name="RosterError",this.code=$}}});function S5($,X){for(let Z of X){let Y=$[Z];if(Y!==void 0&&Y.trim()!=="")return Y.trim()}return null}function Ek($){if($===null)return null;if(!/^\d+$/.test($))return null;let X=Number($);return Number.isSafeInteger(X)&&X>0?X:null}function uU($){let X=S5($,kt),Z=Ek(S5($,Et)),Y=S5($,ft);return{sessionId:X,sessionSource:X===null?"none":"env",agentPid:Z,pidSource:Z===null?"none":"env",terminal:S5($,vt),paneKey:S5($,yt),dispatchId:Y,dispatchSource:Y===null?"none":"env",runId:S5($,St),harnessBuild:S5($,gt)}}function yY($,X){return{...$,...X.sessionId!==void 0?{sessionId:X.sessionId,sessionSource:X.sessionSource??"flag"}:{},...X.agentPid!==void 0?{agentPid:X.agentPid,pidSource:"flag"}:{},...X.dispatchId!==void 0?{dispatchId:X.dispatchId,dispatchSource:X.dispatchSource??"flag"}:{},...X.runId!==void 0?{runId:X.runId}:{},...X.terminal!==void 0?{terminal:X.terminal}:{}}}function xL($){return $.sessionId===null&&$.agentPid===null&&$.terminal===null&&$.paneKey===null&&$.dispatchId===null&&$.runId===null}function vk($){if($.dispatchSource==="none")return!0;if($.selfPid!==null&&$.agentPid===$.selfPid)return!0;return!1}function pU($){if($===void 0||$.sessionId===null)return{confirmed:!1,sessionId:null,reason:"no_session"};if($.sessionSource==="flag"||$.sessionSource==="search")return{confirmed:!0,sessionId:$.sessionId,by:"linked"};if($.dispatchSource!=="none")return{confirmed:!0,sessionId:$.sessionId,by:"dispatch"};return{confirmed:!1,sessionId:$.sessionId,reason:"no_dispatch"}}function cU($,X,Z){if(X===null)return"unknown";if(X){if($.finishedAt===null)return"working";if(Z!==void 0&&vk(Z))return"done";return"orphan"}return $.finishedAt===null?"lost":"done"}function fY($){return $==="working"||$==="orphan"}function hL($){if($===null||$<=0)return null;try{return process.kill($,0),!0}catch(X){if(X.code==="EPERM")return!0;return!1}}var kt,Et,vt,yt,ft,St,gt,lU;var mL=v(()=>{kt=["MYC_SESSION_ID","CLAUDE_CODE_SESSION_ID"],Et=["MYC_AGENT_PID","CLAUDE_PID"],vt=["ORCA_TERMINAL_HANDLE"],yt=["ORCA_PANE_KEY"],ft=["MYC_DISPATCH_ID","ORCA_DISPATCH_ID"],St=["MYC_RUN_ID","ORCA_RUN_ID"],gt=["AI_AGENT"];lU={working:"in progress",orphan:"finished, but still alive",lost:"no process, work not closed",done:"finished",unknown:"process unknown"}});function pt($){return $.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((Z)=>Z.length>0).map((Z)=>Z.slice(0,5))}function ct($){return ht.test($)||xt.test($)}function it($){return ut.test($)||lt.test($)}function nt($){if($===void 0)return;return iU.includes($)?$:void 0}function dt($){let X=new Set(pt($)),Z=new Set;for(let Y of iU)for(let z of wt[Y]){for(let J of X)if(J.startsWith(z)){Z.add(Y);break}if(Z.has(Y))break}if(Z.size===0)return;return bt.find((Y)=>Z.has(Y))}function ot($){if($.length===0)return"feature";if($.every(ct))return"test";if($.every((X)=>mt.test(X)))return"docs";if($.every(it))return"config";return"feature"}function at($){let X=$.replace(/^\.?\//,""),Z=X.indexOf("/");return Z===-1?X:X.slice(0,Z)}function fk($=[]){let X=[...new Set($.filter((Y)=>Y.trim()!==""))];if(X.length===0)return"unknown";if(X.length===1)return"local";let Z=new Set(X.map(at));if(X.length<=5&&Z.size===1)return"module";return"cross"}function Sk($){let X=$.anchorPaths??[],Z=fk(X),Y=nt($.intent),z="declared";if(Y===void 0&&$.type==="bug")Y="fix",z="type";if(Y===void 0){let J=dt($.title);if(J!==void 0)Y=J,z="title"}if(Y===void 0)Y=ot(X),z="anchors";return{intent:Y,scope:Z,taskClass:`${Y}:${Z}`,intentSource:z,fpVersion:1}}function st($){return[...new Set(($??[]).filter((X)=>X.trim()!==""))].sort()}function gk($){for(let X of["touched","anchors","text"]){let Z=st($[X]);if(Z.length>0)return{paths:Z,source:X}}return{paths:[],source:"none"}}function uL($){let X=new Set;for(let Z of $.matchAll(rt)){let Y=Z[1];if(Y!==void 0)X.add(Y.replace(/^\.\//,""))}return[...X].sort()}function dU($){let X=gk($.sources);return{...Sk({title:$.title,...$.type!==void 0?{type:$.type}:{},...$.intent!==void 0?{intent:$.intent}:{},anchorPaths:X.paths}),scopeSource:X.source,scopePaths:X.paths}}function y8($){let[X,Z]=$.split(":");return X!==void 0&&Z!==void 0&&iU.includes(X)&&yk.includes(Z)}var iU,yk,bt,wt,xt,ht,mt,ut,lt,nU,rt;var oU=v(()=>{iU=["fix","feature","refactor","test","docs","config","investigate"],yk=["local","module","cross","unknown"],bt=["fix","config","test","docs","refactor","feature","investigate"],wt={fix:["fix","bug","crash","broke","regre","fail","repai","patch","hotfi","\u0438\u0441\u043F\u0440\u0430","\u043F\u043E\u0447\u0438\u043D","\u043F\u0430\u0434\u0430\u0435","\u043E\u0448\u0438\u0431\u043A","\u0447\u0438\u043D\u0438\u0442","\u0441\u043B\u043E\u043C\u0430","\u0434\u0435\u0444\u0435\u043A","\u0431\u0430\u0433"],feature:["add","imple","suppo","featu","creat","intro","build","enabl","new","\u0434\u043E\u0431\u0430\u0432","\u0440\u0435\u0430\u043B\u0438","\u0441\u0434\u0435\u043B\u0430","\u0432\u0432\u0435\u0441\u0442","\u0437\u0430\u0432\u0435\u0441","\u0441\u043E\u0437\u0434\u0430","\u043F\u043E\u0441\u0442\u0440","\u043D\u0430\u0443\u0447\u0438"],refactor:["refac","extra","renam","clean","simpl","inlin","move","split","unify","\u0440\u0435\u0444\u0430\u043A","\u0432\u044B\u043D\u0435\u0441","\u043F\u0435\u0440\u0435\u0438","\u0443\u043F\u0440\u043E\u0441","\u043F\u0435\u0440\u0435\u043D","\u0440\u0430\u0437\u0434\u0435","\u043F\u0440\u0438\u0432\u0435","\u043F\u043E\u0447\u0438\u0441"],test:["test","spec","cover","fuzz","mutat","\u0442\u0435\u0441\u0442","\u043F\u043E\u043A\u0440\u044B","\u043C\u0443\u0442\u0430\u0446","\u043F\u0440\u043E\u0432\u0435"],docs:["doc","readm","comme","guide","chang","\u0434\u043E\u043A\u0443\u043C","\u043E\u043F\u0438\u0441\u0430","\u043A\u043E\u043C\u043C\u0435","\u043F\u043E\u044F\u0441\u043D","\u0437\u0430\u043C\u0435\u0442"],config:["ci","deps","bump","upgra","confi","docke","lint","build","relea","packa","\u0437\u0430\u0432\u0438\u0441","\u043E\u0431\u043D\u043E\u0432","\u043A\u043E\u043D\u0444\u0438","\u0441\u0431\u043E\u0440\u043A","\u0432\u044B\u043A\u0430\u0442","\u0440\u0435\u043B\u0438\u0437"],investigate:["inves","why","analy","expla","explo","audit","check","resea","\u0440\u0430\u0437\u0431\u043E","\u043F\u043E\u0447\u0435\u043C","\u0432\u044B\u044F\u0441\u043D","\u043E\u0431\u044A\u044F\u0441","\u0438\u0441\u0441\u043B\u0435","\u043F\u043E\u043D\u044F\u0442","\u0441\u0440\u0430\u0432\u043D"]},xt=/(^|\/)(__tests__|tests?|spec)\//i,ht=/(\.test\.|\.spec\.|_test\.|(^|\/)test_)/i,mt=/\.(md|mdx|rst|txt|adoc)$/i,ut=/\.(ya?ml|toml|json|lock|ini|cfg|conf|env)$/i,lt=/(^|\/)(dockerfile|makefile|\.gitignore|\.npmrc)$/i;nU=["touched","anchors","text","none"];rt=/(?<![\w./~-])((?:\.\/)?(?:(?:\.[A-Za-z_]|[A-Za-z0-9_@-])[A-Za-z0-9_@.-]*\/)+(?:\.[A-Za-z_]|[A-Za-z0-9_@-])[A-Za-z0-9_@.-]*\.[A-Za-z][A-Za-z0-9]*)(?::\d+(?:-\d+)?)?(?![A-Za-z0-9_@/-])/g});import{existsSync as tt,readdirSync as et,readFileSync as $e,realpathSync as Xe,statSync as xk}from"fs";import{basename as Ze,dirname as Ye,isAbsolute as ze,join as pL,relative as Je,resolve as hk,sep as bk}from"path";async function g5($,X,Z){try{let Y=Bun.spawn(["git","--no-optional-locks","-C",$,...X],{stdin:Z===void 0?"ignore":Buffer.from(Z),stdout:"pipe",stderr:"ignore"}),z=setTimeout(()=>Y.kill(),mk),[J,U]=await Promise.all([new Response(Y.stdout).text(),Y.exited]);return clearTimeout(z),U===0?J:null}catch{return null}}function aU($){try{return Xe($)}catch{return hk($)}}function lL($){return $.split("\x00").filter((X)=>X.length>0)}function uk($){return!$.endsWith("/")&&$.split("/")[0]!==".myc"&&!$.includes(`
|
|
3063
|
+
`)}async function lk($,X){let Z=new Map,Y=[];for(let U of X){let K;try{K=xk(pL($,U))}catch{Z.set(U,Ue);continue}if(K.isFile())Y.push(U)}if(Y.length===0)return Z;let z=await g5($,["hash-object","--stdin-paths"],`${Y.join(`
|
|
3064
3064
|
`)}
|
|
3065
3065
|
`);if(z===null)return null;let J=z.split(`
|
|
3066
|
-
`).filter((U)=>U.length>0);if(J.length!==Y.length)return null;return Y.forEach((U,K)=>Z.set(U,J[K])),Z}async function
|
|
3067
|
-
`);if(Z===void 0||Z===""||Y===void 0||Y==="")return null;let z=aU(Z),J=aU(hk($,Y)),U=
|
|
3066
|
+
`).filter((U)=>U.length>0);if(J.length!==Y.length)return null;return Y.forEach((U,K)=>Z.set(U,J[K])),Z}async function Ke($){let X=await g5($,["rev-parse","--show-toplevel","--git-common-dir"]);if(X===null)return null;let[Z,Y]=X.split(`
|
|
3067
|
+
`);if(Z===void 0||Z===""||Y===void 0||Y==="")return null;let z=aU(Z),J=aU(hk($,Y)),U=Ze(J)===".git"?Ye(J):z;return{root:z,mainRoot:U}}function wk($,X){let Z=Je($,X);if(Z==="")return"";if(Z===".."||Z.startsWith(`..${bk}`)||ze(Z))return null;return Z.split(bk).join("/")}function We($){let X;try{X=et($,{withFileTypes:!0})}catch{return[]}let Z=[];for(let Y of X){if(!Y.isDirectory()||Y.name===".git"||Y.name===".myc"||Y.name==="node_modules")continue;let z=pL($,Y.name,".git"),J;try{J=xk(z)}catch{continue}if(J.isFile()){let U="";try{U=$e(z,"utf8")}catch{continue}let K=/^gitdir:\s*(.+?)\s*$/m.exec(U);if(K===null||K[1].split(/[\\/]/).includes("worktrees"))continue}Z.push(Y.name)}return Z.sort()}async function Ve($,X){let[Z,Y]=await Promise.all([g5($,["rev-parse","-q","--verify","HEAD"]),g5($,["status","--porcelain=v1","-z","--untracked-files=all","--no-renames","--ignore-submodules=all"])]);if(Y===null)return null;let z=lL(Y).map((W)=>W.slice(3)).filter(uk),J=await lk($,z);if(J===null)return null;let U={};for(let[W,V]of[...J.entries()].sort(([G],[H])=>G<H?-1:G>H?1:0))U[W]=V;let K=Z===null?null:Z.trim()||null;return{root:$,prefix:X,head:K,dirty:U}}async function cL($,X){let Z=aU(X),Y=aU($),z=await Ke(Y),J=[];if(z!==null){let V=wk(Z,z.mainRoot);if(V!==null)J.push({root:z.root,prefix:V})}if(z===null?wk(Z,Y)!==null:z.root===Z&&z.mainRoot===Z)for(let V of We(Z)){let G=pL(Z,V);if(J.some((H)=>H.root===G))continue;J.push({root:G,prefix:V})}if(J.length===0)return null;let K=await Promise.all(J.map((V)=>Ve(V.root,V.prefix)));if(z!==null&&J[0].root===z.root&&K[0]===null)return null;let W=K.filter((V)=>V!==null);return W.length===0?null:{v:1,checkouts:W}}async function Ge($){if(!tt($.root))return null;let[X,Z]=await Promise.all([$.head===null?g5($.root,["ls-files","-z"]):g5($.root,["diff","--name-only","-z","--no-renames","--ignore-submodules=all",$.head]),g5($.root,["ls-files","-z","--others","--exclude-standard"])]);if(X===null||Z===null)return null;let Y=new Set([...lL(X),...lL(Z)].filter(uk)),z=Object.keys($.dirty),J=await lk($.root,z);if(J===null)return null;let U=new Set;for(let K of Y)if(!(K in $.dirty))U.add(K);for(let K of z){let W=J.get(K);if(W!==void 0&&W!==$.dirty[K])U.add(K)}return[...U].sort().map((K)=>({prefix:$.prefix,path:K}))}async function iL($){if($.checkouts.length===0)return null;let X=await Promise.all($.checkouts.map(Ge));if(X[0]===null)return null;return X.flatMap((Z)=>Z??[])}function nL($){if($===null)return null;try{let X=JSON.parse($);if(X.v!==1||!Array.isArray(X.checkouts))return null;let Z=X.checkouts.filter((Y)=>Y!==null&&typeof Y==="object"&&typeof Y.root==="string"&&typeof Y.prefix==="string"&&(Y.head===null||typeof Y.head==="string")&&Y.dirty!==null&&typeof Y.dirty==="object");return Z.length===0?null:{v:1,checkouts:Z}}catch{return null}}var mk=1e4,Ue="-";var dL=()=>{};import{randomBytes as He}from"crypto";function sU($,X=[]){if($==="rejected")return 0;let Z=[...new Set(X)].reduce((Y,z)=>Y+(Ne[z]??0),0);return Math.max(Le,Qe[$]-Z)}function Be($){let X;try{X=JSON.parse($)}catch{return[]}if(!Array.isArray(X))return[];return X.filter((Z)=>x6.includes(Z))}function b5($){let X=$.verdict===null?null:$.verdict,Z=Be($.caveats);return{attemptId:$.attempt_id,taskId:$.task_id,modelId:$.model_id,effort:$.effort,harness:$.harness,actor:$.actor,taskClass:$.task_class,classSource:$.class_source,predictedClass:$.predicted_class??null,scopeSource:$.scope_source??null,startedAt:$.started_at,finishedAt:$.finished_at,verdict:X,caveats:Z,retries:$.retries,tokensIn:$.tokens_in,tokensOut:$.tokens_out,tokensCacheRead:$.tokens_cache_read,tokensCacheWrite:$.tokens_cache_write,costUsd:$.cost_usd,priceValidFrom:$.price_valid_from,costBasis:$.cost_basis,source:$.source,note:$.note,quality:X===null?null:sU(X,Z),wallMs:$.finished_at===null?null:$.finished_at-$.started_at}}function ck(){return`att_${He(6).toString("hex")}`}function Te($){if(w6.includes($))return $;throw new z$("usage.verdict",`unknown verdict "${$}"; allowed: ${w6.join(", ")}`)}function pk($){if($===void 0||nU.includes($))return;throw new z$("usage.input",`unknown scope source "${$}"; allowed: ${nU.join(", ")}`)}function qe($){let X=[];for(let Z of $){if(!x6.includes(Z))throw new z$("usage.caveat",`unknown caveat "${Z}"; allowed: ${x6.join(", ")}`);if(!X.includes(Z))X.push(Z)}return X}function N8($,X){if($===void 0)return 0;if(!Number.isSafeInteger($)||$<0)throw new z$("usage.input",`${X} must be an integer \u2265 0 and at most ${Number.MAX_SAFE_INTEGER}`);return $}function Fe($){if($===null)return null;try{let X=JSON.parse($);if(!Array.isArray(X))return null;return X.filter((Z)=>typeof Z==="string")}catch{return null}}function oL($){return{attemptId:$.attempt_id,sessionId:$.session_id,sessionSource:$.session_source,transcriptPath:$.transcript_path,dispatchId:$.dispatch_id,dispatchSource:$.dispatch_source,runId:$.run_id,terminal:$.terminal,paneKey:$.pane_key,agentPid:$.agent_pid,pidSource:$.pid_source,harnessBuild:$.harness_build,procState:$.proc_state,procCheckedAt:$.proc_checked_at,procExitedAt:$.proc_exited_at,gitHead:$.git_head,gitBase:nL($.git_base??null),filesTouched:Fe($.files_touched),recordedAt:$.recorded_at}}class SY{#$;#X;constructor($,X=Date.now){this.#$=$,this.#X=X}#Z($){this.#$.exec("BEGIN IMMEDIATE");try{let X=$();return this.#$.exec("COMMIT"),X}catch(X){throw this.#$.exec("ROLLBACK"),X}}startAttempt($){if($.taskId.trim()==="")throw new z$("usage.input","taskId must be non-empty");if(!y8($.taskClass))throw new z$("usage.class",`task class "${$.taskClass}" is not in the intent:scope taxonomy`);if(pk($.scopeSource),$.predictedClass!==void 0&&!y8($.predictedClass))throw new z$("usage.class",`predicted class "${$.predictedClass}" is not in the intent:scope taxonomy`);let X=this.#$.query("SELECT model_id, harness, effort FROM swarm_model WHERE model_id = ?1").get($.modelId);if(X===null)throw new F$("notfound.model",`model "${$.modelId}" not found in the roster; add it: myc model add`);let Z=ck(),Y=$.startedAt??this.#X();return this.#Z(()=>{if(this.#$.query(`INSERT INTO swarm_attempt
|
|
3068
3068
|
(attempt_id, task_id, model_id, effort, harness, actor, task_class,
|
|
3069
3069
|
class_source, started_at, tokens_in, tokens_out, tokens_cache_read,
|
|
3070
3070
|
tokens_cache_write, source, note, predicted_class, scope_source)
|
|
@@ -3085,7 +3085,7 @@ code_intel = "${vX}"
|
|
|
3085
3085
|
task_class = ?2, scope_source = ?3
|
|
3086
3086
|
WHERE attempt_id = ?1 AND class_source = 'derived'
|
|
3087
3087
|
AND (task_class <> ?2 OR scope_source IS NOT ?3 OR predicted_class IS NULL)`).run($,X.taskClass,X.scopeSource,X.predictedClass??null).changes),Y=this.getAttempt($);if(Y===void 0)throw new z$("notfound.attempt",`attempt "${$}" not found`);return{record:Y,changed:Z>0}}fillPrediction($,X){if(!y8(X))throw new z$("usage.class",`predicted class "${X}" is not in the intent:scope taxonomy`);return this.#Z(()=>this.#$.query(`UPDATE swarm_attempt SET predicted_class = ?2
|
|
3088
|
-
WHERE attempt_id = ?1 AND predicted_class IS NULL`).run($,X).changes)>0}finishAttempt($,X){let Z=
|
|
3088
|
+
WHERE attempt_id = ?1 AND predicted_class IS NULL`).run($,X).changes)>0}finishAttempt($,X){let Z=Te(X.verdict),Y=qe(X.caveats??[]),z=N8(X.retries,"retries"),J=X.finishedAt??this.#X();if(this.#Z(()=>{let K=this.#$.query("SELECT * FROM swarm_attempt WHERE attempt_id = ?1").get($);if(K===null)throw new z$("notfound.attempt",`attempt "${$}" not found`);let W=N8(X.tokensIn??K.tokens_in,"tokensIn"),V=N8(X.tokensOut??K.tokens_out,"tokensOut"),G=N8(X.tokensCacheRead??K.tokens_cache_read,"tokensCacheRead"),H=N8(X.tokensCacheWrite??K.tokens_cache_write,"tokensCacheWrite"),N=this.#J(K.model_id,K.started_at,{tokensIn:W,tokensOut:V,tokensCacheRead:G,tokensCacheWrite:H});return this.#$.query(`UPDATE swarm_attempt
|
|
3089
3089
|
SET finished_at = ?1, verdict = ?2, caveats = ?3, retries = ?4,
|
|
3090
3090
|
tokens_in = ?5, tokens_out = ?6, tokens_cache_read = ?7,
|
|
3091
3091
|
tokens_cache_write = ?8, cost_usd = ?9, price_valid_from = ?10,
|
|
@@ -3110,7 +3110,7 @@ code_intel = "${vX}"
|
|
|
3110
3110
|
usd_per_m_cache_read, usd_per_m_cache_write
|
|
3111
3111
|
FROM swarm_model_price
|
|
3112
3112
|
WHERE model_id = ?1 AND valid_from <= ?2
|
|
3113
|
-
ORDER BY valid_from DESC LIMIT 1`).get($,X);if(z===null)return{costUsd:null,priceValidFrom:null,basis:"no_price"};return{costUsd:(Z.tokensIn*z.usd_per_m_in+Z.tokensOut*z.usd_per_m_out+Z.tokensCacheRead*z.usd_per_m_cache_read+Z.tokensCacheWrite*z.usd_per_m_cache_write)/1e6,priceValidFrom:z.valid_from,basis:"priced"}}}var w6,x6,aL=1,
|
|
3113
|
+
ORDER BY valid_from DESC LIMIT 1`).get($,X);if(z===null)return{costUsd:null,priceValidFrom:null,basis:"no_price"};return{costUsd:(Z.tokensIn*z.usd_per_m_in+Z.tokensOut*z.usd_per_m_out+Z.tokensCacheRead*z.usd_per_m_cache_read+Z.tokensCacheWrite*z.usd_per_m_cache_write)/1e6,priceValidFrom:z.valid_from,basis:"priced"}}}var w6,x6,aL=1,Qe,Ne,Le=0.1,z$;var sL=v(()=>{mL();wL();oU();dL();w6=["accepted","rework","rejected"],x6=["coordinator_fixed","tests_weak","report_inaccurate","scope_missed"],Qe={accepted:1,rework:0.5,rejected:0},Ne={coordinator_fixed:0.35,tests_weak:0.4,report_inaccurate:0.25,scope_missed:0.3};z$=class z$ extends Error{code;constructor($,X){super(X);this.name="AttributionError",this.code=$}}});function rU($){if($<0.5)return Math.log(Math.PI/Math.sin(Math.PI*$))-rU(1-$);let X=$-1,Z=0.9999999999998099,Y=X+7.5;for(let z=0;z<ik.length;z++)Z+=ik[z]/(X+z+1);return 0.5*Math.log(2*Math.PI)+(X+0.5)*Math.log(Y)-Y+Math.log(Z)}function nk($,X,Z){let U=$+X,K=$+1,W=$-1,V=1,G=1-U*Z/K;if(Math.abs(G)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)G=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;G=1/G;let H=G;for(let N=1;N<=300;N++){let Q=2*N,L=N*(X-N)*Z/((W+Q)*($+Q));if(G=1+L*G,Math.abs(G)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)G=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(V=1+L/V,Math.abs(V)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)V=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(G=1/G,H*=G*V,L=-($+N)*(U+N)*Z/(($+Q)*(K+Q)),G=1+L*G,Math.abs(G)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)G=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(V=1+L/V,Math.abs(V)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)V=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;G=1/G;let B=G*V;if(H*=B,Math.abs(B-1)<0.00000000000003)break}return H}function ak($,X,Z){if($<=0)return 0;if($>=1)return 1;let Y=Math.exp(rU(X+Z)-rU(X)-rU(Z)+X*Math.log($)+Z*Math.log(1-$));return $<(X+1)/(X+Z+2)?Y*nk(X,Z,$)/X:1-Y*nk(Z,X,1-$)/Z}function rL($,X,Z){if($<=0)return 0;if($>=1)return 1;let Y=0,z=1;for(let J=0;J<60;J++){let U=(Y+z)/2;if(ak(U,X,Z)<$)Y=U;else z=U}return(Y+z)/2}function sk($,X=tL){let Z=$.reduce((U,K)=>U+K,0),Y=1+Z,z=1+($.length-Z),J=(1-X)/2;return{lo:rL(J,Y,z),hi:rL(1-J,Y,z)}}function je($){try{let X=JSON.parse($);return Array.isArray(X)?X:[]}catch{return[]}}function Oe($){if($.cost_usd===null||$.usd_per_m_in===null)return!1;let X=($.tokens_in*$.usd_per_m_in+$.tokens_out*($.usd_per_m_out??0)+$.tokens_cache_read*($.usd_per_m_cache_read??0)+$.tokens_cache_write*($.usd_per_m_cache_write??0))/1e6;return Math.abs(X-$.cost_usd)>0.000000001}function dk($){return $.reduce((X,Z)=>X+Z,0)/$.length}function Ce($,X){let Z=$.qualities.length;return{arm:`${$.modelId}|${$.effort}`,modelId:$.modelId,effort:$.effort,harness:$.harness,attempts:Z,qualityMean:dk($.qualities),quality:sk($.qualities),costUsdMean:$.costs.length===0?null:dk($.costs),costUsdTotal:$.costs.reduce((Y,z)=>Y+z,0),costedAttempts:$.costs.length,costCoverage:$.costs.length/Z,cleanRate:$.clean/Z,caveatCounts:$.caveatCounts,verdictCounts:$.verdictCounts,enoughData:Z>=X}}function Ae($){let X=$.filter((W)=>W.enoughData);if(X.length===0)return{qualityLeader:null,equalGroup:[],cheapest:null,separationPending:!1,answer:"insufficient_attempts",why:`no arm has the required number of closed attempts (max ${Math.max(0,...$.map((W)=>W.attempts))})`};if(X.length===1)return{qualityLeader:X[0].arm,equalGroup:[X[0].arm],cheapest:null,separationPending:!1,answer:"single_arm",why:`only ${X[0].arm} has observations; nothing to compare with`};let Z=X.reduce((W,V)=>V.qualityMean>W.qualityMean?V:W),Y=X.filter((W)=>W.quality.hi>=Z.quality.lo&&Z.quality.hi>=W.quality.lo),z=Y.filter((W)=>W.costUsdMean!==null);if(z.length===0)return{qualityLeader:Z.arm,equalGroup:Y.map((W)=>W.arm),cheapest:null,separationPending:!1,answer:"no_cost_data",why:"results are comparable, but no arm has a computed cost: no tokens or no price at the time of the attempt"};let J=z.reduce((W,V)=>V.costUsdMean<W.costUsdMean?V:W),U=J.qualityMean<Z.qualityMean-0.000000001,K;if(Y.length===1)K=`${Z.arm} has no equal on result (the other intervals do not overlap); take it`;else if(K=`${Y.length} arms are indistinguishable on result; the cheapest is ${J.arm} ($${J.costUsdMean.toFixed(4)} vs $${Math.max(...z.map((W)=>W.costUsdMean)).toFixed(4)} per attempt)`,U)K+=`; WARNING: mean quality of ${J.arm} is lower (${J.qualityMean.toFixed(2)} vs ${Z.qualityMean.toFixed(2)}), the intervals still overlap \u2014 `+"not enough observations to tell them apart";return{qualityLeader:Z.arm,equalGroup:Y.map((W)=>W.arm),cheapest:J.arm,separationPending:U,answer:"ok",why:K}}function gY($,X={}){let Z=X.minAttempts??ok;if(X.taskClass!==void 0&&!y8(X.taskClass))throw Error(`task class "${X.taskClass}" is not in the intent:scope taxonomy`);let Y=["a.finished_at IS NOT NULL","a.verdict IS NOT NULL"],z=[];if(X.taskClass!==void 0)z.push(X.taskClass),Y.push(`a.task_class = ?${z.length}`);if(X.since!==void 0)z.push(X.since),Y.push(`a.finished_at >= ?${z.length}`);let J=$.query(`SELECT a.model_id, a.effort, a.harness, a.task_class, a.verdict, a.caveats,
|
|
3114
3114
|
a.cost_usd, a.cost_basis,
|
|
3115
3115
|
CASE WHEN a.tokens_cache_read + a.tokens_cache_write > 0
|
|
3116
3116
|
AND coalesce(p.usd_per_m_cache_read, 0) = 0
|
|
@@ -3122,7 +3122,7 @@ code_intel = "${vX}"
|
|
|
3122
3122
|
FROM swarm_attempt a
|
|
3123
3123
|
LEFT JOIN swarm_model_price p
|
|
3124
3124
|
ON p.model_id = a.model_id AND p.valid_from = a.price_valid_from
|
|
3125
|
-
WHERE ${Y.join(" AND ")}`).all(...z),U=new Map,K=0,W=0,V=0;for(let Q of J){let L=
|
|
3125
|
+
WHERE ${Y.join(" AND ")}`).all(...z),U=new Map,K=0,W=0,V=0;for(let Q of J){let L=je(Q.caveats),B=sU(Q.verdict,L),T=`${Q.model_id}|${Q.effort}`,q=U.get(Q.task_class);if(q===void 0)q=new Map,U.set(Q.task_class,q);let j=q.get(T);if(j===void 0)j={modelId:Q.model_id,effort:Q.effort,harness:Q.harness,qualities:[],costs:[],clean:0,caveatCounts:{},verdictCounts:{}},q.set(T,j);if(j.qualities.push(B),j.verdictCounts[Q.verdict]=(j.verdictCounts[Q.verdict]??0)+1,Q.verdict==="accepted"&&L.length===0)j.clean+=1;for(let O of L)j.caveatCounts[O]=(j.caveatCounts[O]??0)+1;if(Q.cost_usd!==null&&Q.cost_basis==="priced"){if(j.costs.push(Q.cost_usd),K+=1,Q.cache_unpriced===1)W+=1;if(Oe(Q))V+=1}}let G=[],H=0;for(let[Q,L]of[...U.entries()].sort((B,T)=>B[0].localeCompare(T[0]))){let B=[...L.values()].map((T)=>Ce(T,Z)).sort((T,q)=>q.qualityMean-T.qualityMean||T.arm.localeCompare(q.arm));H+=B.length,G.push({taskClass:Q,arms:B,...Ae(B)})}let N=$.query("SELECT count(*) AS n, sum(CASE WHEN finished_at IS NOT NULL THEN 1 ELSE 0 END) AS f FROM swarm_attempt").get();return{outcomeVersion:aL,minAttempts:Z,credibleMass:tL,classes:G,coverage:{attempts:N.n,finished:N.f??0,withCost:K,costCacheUnpriced:W,costStale:V,arms:H,classes:G.length}}}var ok=3,tL=0.9,ik;var rk=v(()=>{sL();oU();ik=[676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116]});var eL;var $B=v(()=>{eL={version:1,name:"swarm_model",sql:`CREATE TABLE swarm_model (
|
|
3126
3126
|
model_id TEXT PRIMARY KEY, -- "anthropic/claude-sonnet-5" \u2014 \u0432\u0441\u0435\u0433\u0434\u0430 \u0441 \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u043E\u043C
|
|
3127
3127
|
family TEXT NOT NULL, -- "claude-sonnet", "glm" \u2014 \u0434\u043B\u044F \u043D\u0430\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u043D\u0438\u044F \u043F\u0440\u0438\u043E\u0440\u043E\u0432 \u043C\u0435\u0436\u0434\u0443 \u0432\u0435\u0440\u0441\u0438\u044F\u043C\u0438
|
|
3128
3128
|
version TEXT NOT NULL DEFAULT '', -- "5" \u0438\u043B\u0438 "5.4", \u043F\u0443\u0441\u0442\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430 = \u043D\u0435 \u0443\u043A\u0430\u0437\u0430\u043D\u0430
|
|
@@ -3192,7 +3192,7 @@ code_intel = "${vX}"
|
|
|
3192
3192
|
recorded_at INTEGER NOT NULL
|
|
3193
3193
|
)`,objects:["swarm_attempt_run"]}});var HB;var QB=v(()=>{HB={version:7,name:"swarm_attempt_run_session",sql:`CREATE INDEX swarm_attempt_run_session
|
|
3194
3194
|
ON swarm_attempt_run (session_id)
|
|
3195
|
-
WHERE session_id IS NOT NULL`,objects:["swarm_attempt_run_session"]}});var
|
|
3195
|
+
WHERE session_id IS NOT NULL`,objects:["swarm_attempt_run_session"]}});var Pe,NB;var LB=v(()=>{Pe=["ALTER TABLE swarm_model RENAME TO swarm_model_pre8","ALTER TABLE swarm_model_price RENAME TO swarm_model_price_pre8","ALTER TABLE swarm_attempt RENAME TO swarm_attempt_pre8","ALTER TABLE swarm_attempt_run RENAME TO swarm_attempt_run_pre8",`CREATE TABLE swarm_model (
|
|
3196
3196
|
model_id TEXT PRIMARY KEY, -- "anthropic/claude-sonnet-5" \u2014 \u0432\u0441\u0435\u0433\u0434\u0430 \u0441 \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u043E\u043C
|
|
3197
3197
|
family TEXT NOT NULL, -- "claude-sonnet", "glm" \u2014 \u0434\u043B\u044F \u043D\u0430\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u043D\u0438\u044F \u043F\u0440\u0438\u043E\u0440\u043E\u0432 \u043C\u0435\u0436\u0434\u0443 \u0432\u0435\u0440\u0441\u0438\u044F\u043C\u0438
|
|
3198
3198
|
version TEXT NOT NULL DEFAULT '', -- "5" \u0438\u043B\u0438 "5.4", \u043F\u0443\u0441\u0442\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430 = \u043D\u0435 \u0443\u043A\u0430\u0437\u0430\u043D\u0430
|
|
@@ -3262,8 +3262,8 @@ code_intel = "${vX}"
|
|
|
3262
3262
|
)`,"INSERT INTO swarm_model SELECT * FROM swarm_model_pre8","INSERT INTO swarm_model_price SELECT * FROM swarm_model_price_pre8","INSERT INTO swarm_attempt SELECT * FROM swarm_attempt_pre8","INSERT INTO swarm_attempt_run SELECT * FROM swarm_attempt_run_pre8","DROP TABLE swarm_attempt_run_pre8","DROP TABLE swarm_attempt_pre8","DROP TABLE swarm_model_price_pre8","DROP TABLE swarm_model_pre8","CREATE INDEX swarm_attempt_task ON swarm_attempt (task_id, started_at DESC)",`CREATE INDEX swarm_attempt_arm
|
|
3263
3263
|
ON swarm_attempt (task_class, model_id, effort, finished_at)`,`CREATE INDEX swarm_attempt_run_session
|
|
3264
3264
|
ON swarm_attempt_run (session_id)
|
|
3265
|
-
WHERE session_id IS NOT NULL`],NB={version:8,name:"harness_codex",sql:
|
|
3266
|
-
CHECK (scope_source IN ('touched','anchors','text','none'))`,"ALTER TABLE swarm_attempt_run ADD COLUMN git_base TEXT"],BB={version:9,name:"swarm_attempt_scope",sql:
|
|
3265
|
+
WHERE session_id IS NOT NULL`],NB={version:8,name:"harness_codex",sql:Pe,objects:["swarm_model","swarm_model_price","swarm_attempt","swarm_attempt_run","swarm_attempt_task","swarm_attempt_arm","swarm_attempt_run_session"]}});var De,BB;var TB=v(()=>{De=["ALTER TABLE swarm_attempt ADD COLUMN predicted_class TEXT",`ALTER TABLE swarm_attempt ADD COLUMN scope_source TEXT
|
|
3266
|
+
CHECK (scope_source IN ('touched','anchors','text','none'))`,"ALTER TABLE swarm_attempt_run ADD COLUMN git_base TEXT"],BB={version:9,name:"swarm_attempt_scope",sql:De,objects:["swarm_attempt","swarm_attempt_run"]}});var Me,qB;var FB=v(()=>{Me=["ALTER TABLE swarm_model RENAME TO swarm_model_pre10","ALTER TABLE swarm_model_price RENAME TO swarm_model_price_pre10","ALTER TABLE swarm_attempt RENAME TO swarm_attempt_pre10","ALTER TABLE swarm_attempt_run RENAME TO swarm_attempt_run_pre10",`CREATE TABLE swarm_model (
|
|
3267
3267
|
model_id TEXT PRIMARY KEY, -- "anthropic/claude-sonnet-5" \u2014 \u0432\u0441\u0435\u0433\u0434\u0430 \u0441 \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u043E\u043C
|
|
3268
3268
|
family TEXT NOT NULL, -- "claude-sonnet", "glm" \u2014 \u0434\u043B\u044F \u043D\u0430\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u043D\u0438\u044F \u043F\u0440\u0438\u043E\u0440\u043E\u0432 \u043C\u0435\u0436\u0434\u0443 \u0432\u0435\u0440\u0441\u0438\u044F\u043C\u0438
|
|
3269
3269
|
version TEXT NOT NULL DEFAULT '', -- "5" \u0438\u043B\u0438 "5.4", \u043F\u0443\u0441\u0442\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430 = \u043D\u0435 \u0443\u043A\u0430\u0437\u0430\u043D\u0430
|
|
@@ -3337,104 +3337,104 @@ code_intel = "${vX}"
|
|
|
3337
3337
|
)`,"INSERT INTO swarm_model SELECT * FROM swarm_model_pre10","INSERT INTO swarm_model_price SELECT * FROM swarm_model_price_pre10","INSERT INTO swarm_attempt SELECT * FROM swarm_attempt_pre10","INSERT INTO swarm_attempt_run SELECT * FROM swarm_attempt_run_pre10","DROP TABLE swarm_attempt_run_pre10","DROP TABLE swarm_attempt_pre10","DROP TABLE swarm_model_price_pre10","DROP TABLE swarm_model_pre10","CREATE INDEX swarm_attempt_task ON swarm_attempt (task_id, started_at DESC)",`CREATE INDEX swarm_attempt_arm
|
|
3338
3338
|
ON swarm_attempt (task_class, model_id, effort, finished_at)`,`CREATE INDEX swarm_attempt_run_session
|
|
3339
3339
|
ON swarm_attempt_run (session_id)
|
|
3340
|
-
WHERE session_id IS NOT NULL`],qB={version:10,name:"harness_mcode_mimo",sql:
|
|
3340
|
+
WHERE session_id IS NOT NULL`],qB={version:10,name:"harness_mcode_mimo",sql:Me,objects:["swarm_model","swarm_model_price","swarm_attempt","swarm_attempt_run","swarm_attempt_task","swarm_attempt_arm","swarm_attempt_run_session"]}});var h6="swarm_schema_migrations",jB=`CREATE TABLE IF NOT EXISTS swarm_schema_migrations (
|
|
3341
3341
|
version INTEGER PRIMARY KEY,
|
|
3342
3342
|
name TEXT NOT NULL,
|
|
3343
3343
|
checksum TEXT NOT NULL,
|
|
3344
3344
|
applied_at INTEGER NOT NULL
|
|
3345
3345
|
)`;function tU($){return typeof $.sql==="string"?[$.sql]:$.sql}function H9($){return typeof $.sql==="string"?$.sql:$.sql.join(`;
|
|
3346
|
-
`)}var Q9;var OB=v(()=>{$B();ZB();zB();UB();WB();GB();QB();LB();TB();FB();$B();ZB();zB();UB();WB();GB();QB();LB();TB();FB();Q9=[eL,XB,YB,JB,KB,VB,HB,NB,BB,qB]});import{createHash as
|
|
3347
|
-
VALUES (?1, ?2, ?3, ?4)`).run(U.version,U.name,CB(H9(U)),J)}$.exec("COMMIT")}catch(z){throw $.exec("ROLLBACK"),z}}var bY;var tk=v(()=>{OB();bY=class bY extends Error{code;constructor($,X){super(X);this.name="SwarmSchemaError",this.code=$}}});import{existsSync as wY,readdirSync as
|
|
3348
|
-
`);for(let q=0;q<N.length;q+=1){let j=N[q];if(j.trim()==="")continue;let O;try{O=JSON.parse(j)}catch{continue}if(!B9(O))continue;if(X.until!==void 0||X.since!==void 0){let k=
|
|
3349
|
-
`)){if(K.trim()==="")continue;let W;try{W=JSON.parse(K)}catch{continue}if(!B9(W))continue;U+=1;let V=W.message;if(!B9(V))continue;let G=V.usage;if(!B9(G))continue;let H=V.id,N=W.requestId,Q=typeof H==="string"&&H!==""?H:typeof N==="string"&&N!==""?N:void 0;if(Q===void 0)continue;let L=J.get(Q)??{};for(let[B,T]of L9){let q=G[B];if(typeof q!=="number"||!Number.isSafeInteger(q)||q<0)continue;let j=L[T]??0;if(q>j)z[T]+=q-j,L[T]=q}if(J.set(Q,L),Y(z)){let B=W.timestamp;return{records:U,at:typeof B==="string"?B:null}}}return null}function DB($=process.env){let X=$.CLAUDE_CONFIG_DIR;return T9(X!==void 0&&X.trim()!==""?X:T9(Ie(),".claude"),"projects")}function XE($,X=process.env){let Z=X.MYC_TRANSCRIPT_DIR;if(Z!==void 0&&Z.trim()!=="")return Z;return T9(DB(X),$.replace(/[^A-Za-z0-9]/g,"-"))}function F9($,X,Z=process.env){let Y=Z.MYC_TRANSCRIPT_DIR;if(Y!==void 0&&Y.trim()!=="")return YE(Y,$);let z=$.endsWith(".jsonl")?$.slice(0,-6):$,J=T9(XE(X,Z),`${z}.jsonl`);if(wY(J))return J;let U=DB(Z);ZE(U);let K;try{K=_e(U)}catch(W){throw new e0("transcript.unreadable",`transcript directory ${U} is unreadable: ${W.message}`)}for(let W of K.sort()){let V=T9(U,W,`${z}.jsonl`);if(wY(V))return V}throw new e0("notfound.session",`session "${z}" not found in any project directory under ${U}`,"myc attempt finish \u2026 --from-transcript <file>")}function AB($){return $.toLowerCase().split(/[^a-z0-9]+/).filter((X)=>X!=="")}function ek($,X){return $.length>0&&$.every((Z)=>X.has(Z))}function j9($,X){let Z=$.filter((U)=>!U.startsWith("<")),Y=AB(X.family),z=AB(X.modelId.split("/").pop()??X.modelId),J=Z.filter((U)=>{let K=new Set(AB(U));return!ek(Y,K)&&!ek(z,K)});return{ok:Z.length>0&&J.length===0,seen:Z,foreign:J}}function ZE($){if(!wY($))throw new e0("transcript.dir_missing",`no transcript directory: ${$}`,"give a file with --from-transcript or a directory with $MYC_TRANSCRIPT_DIR")}function YE($,X){ZE($);let Z=X.endsWith(".jsonl")?X.slice(0,-6):X,Y=T9($,`${Z}.jsonl`);if(!wY(Y))throw new e0("notfound.session",`session "${Z}" not found in ${$}`,"myc attempt finish \u2026 --from-transcript <file>");return Y}var e0,L9;var zE=v(()=>{e0=class e0 extends Error{code;hint;constructor($,X,Z){super(X);this.name="TranscriptError",this.code=$,this.hint=Z}};L9=[["input_tokens","tokensIn"],["output_tokens","tokensOut"],["cache_read_input_tokens","tokensCacheRead"],["cache_creation_input_tokens","tokensCacheWrite"]]});var B4=v(()=>{wL();sL();mL();rk();oU();dL();tk();OB();zE()});var LE={};s(LE,{modelCommand:()=>pe,createModelCommand:()=>NE,CACHE_PRICE_SHARES:()=>eU});import{existsSync as ye}from"fs";import{resolve as fe}from"path";import{Database as Se}from"bun:sqlite";function ge($){let X=fe($.globals.directory??process.cwd()),Z;if($.globals.db!==void 0){if(Z=$.globals.db,!ye(Z))return{ok:!1,code:"ws.not_initialized",msg:`workspace not initialized: no ${Z}`,exit:7,hint:"myc init"}}else{let J=K$(X);if(!("dbPath"in J))return h2(J);Z=J.dbPath}let Y=w2($);if(Y!==void 0)return Y;let z=new Se(Z);for(let J of j6)z.exec(J);return N9(z),{roster:new L4(z),close:()=>z.close()}}function xY($){if($ instanceof F$){let X=$.code==="notfound.model"?3:$.code==="conflict.model"?4:2;return{ok:!1,code:$.code,msg:$.message,exit:X}}throw $}function f8($,X){return{ok:!1,code:$,msg:X,exit:2}}function hY($){return{modelId:$.model.modelId,family:$.model.family,version:$.model.version,parentModelId:$.model.parentModelId,harness:$.model.harness,effort:$.model.effort,tokensPerSec:$.model.tokensPerSec,strengths:$.model.strengths,active:$.model.active,price:$.price===null?null:{usdPerMIn:$.price.usdPerMIn,usdPerMOut:$.price.usdPerMOut,usdPerMCacheRead:$.price.usdPerMCacheRead,usdPerMCacheWrite:$.price.usdPerMCacheWrite,validFrom:new Date($.price.validFrom).toISOString()},priceAgeDays:$.priceAgeDays,priceStale:$.priceStale,cacheUnpriced:$.cacheUnpriced,createdAt:new Date($.model.createdAt).toISOString(),updatedAt:new Date($.model.updatedAt).toISOString()}}function WE($){let X=f($,"price-date");if(X===void 0)return Date.now();let Z=f8("usage.date",`--price-date must be YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS[.mmm]Z, got "${X}"`);if(!JE.test(X)&&!we.test(X))return Z;let Y=Date.parse(JE.test(X)?`${X}T00:00:00Z`:X);if(!Number.isFinite(Y))return Z;return Y}function UE($,X){return Math.round($*X*1e6)/1e6}function VE($,X,Z){let Y=t($,"price-cache-read"),z=t($,"price-cache-write");for(let[V,G]of[["--price-cache-read",Y],["--price-cache-write",z]])if(G!==void 0&&(!Number.isFinite(G)||G<0))return f8("usage.price",`${V} must be a number \u2265 0, got "${G}"`);let J=[],U=(V,G,H)=>{if(V!==void 0)return{value:V,source:"flag"};let N=eU[G];if(Z!==void 0&&H!==void 0&&H!==UE(Z.usdPerMIn,N))return{value:H,source:"kept"};return J.push(`${G}=${N*100}%`),{value:UE(X,N),source:"default"}},K=U(Y,"read",Z?.usdPerMCacheRead),W=U(z,"write",Z?.usdPerMCacheWrite);return{usdPerMCacheRead:K.value,usdPerMCacheWrite:W.value,defaulted:J,sources:{read:K.source,write:W.source}}}function GE($,X,Z){if(X.defaulted.length===0)return;$.warn("price.cache_defaulted",`cache rates not set: applied the default ${X.defaulted.join(", ")} of --price-in ${Z} \u2192 read ${X.usdPerMCacheRead}, write ${X.usdPerMCacheWrite} $/1M. This is an assumption, not the provider's price list: set --price-cache-read/--price-cache-write`)}function HE($){let X=f($,"strengths");if(X===void 0)return;return X.split(",").map((Z)=>Z.trim()).filter((Z)=>Z!=="")}function he($){return{name:"add",summary:"add a model to the roster",help:"A price is required and stored with a date (--price-date, default today): a fact, not a constant.",flags:QE,handler:(X)=>{let Z=X.args[0];if(Z===void 0)return f8("usage.input","model id required: myc model add <id> \u2026");let Y=f(X,"family");if(Y===void 0)return f8("usage.input","--family required");let z=f(X,"harness");if(z===void 0)return f8("usage.input","--harness required");let J=t(X,"price-in"),U=t(X,"price-out");if(J===void 0||U===void 0)return f8("usage.price","--price-in and --price-out required (USD per 1M tokens)");let K=WE(X);if(typeof K!=="number")return K;let W=VE(X,J);if(!("usdPerMCacheRead"in W))return W;let V=$.openRoster(X);if(!("roster"in V))return V;try{let G={modelId:Z,family:Y,harness:z,effort:f(X,"effort"),version:f(X,"version"),parentModelId:f(X,"parent"),tokensPerSec:t(X,"tps"),strengths:HE(X),price:{usdPerMIn:J,usdPerMOut:U,usdPerMCacheRead:W.usdPerMCacheRead,usdPerMCacheWrite:W.usdPerMCacheWrite,validFrom:K}};GE(X,W,J);let H=V.roster.addModel(G),N=V.roster.getModel(H.modelId);return{ok:!0,data:hY(N)}}catch(G){return xY(G)}finally{V.close()}}}}function me($){return{name:"update",summary:"change roster fields; a new price is a new dated fact",flags:QE,handler:(X)=>{let Z=X.args[0];if(Z===void 0)return f8("usage.input","model id required: myc model update <id> \u2026");let Y={},z=f(X,"family");if(z!==void 0)Y.family=z;let J=f(X,"harness");if(J!==void 0)Y.harness=J;let U=f(X,"effort");if(U!==void 0)Y.effort=U;let K=f(X,"version");if(K!==void 0)Y.version=K;let W=f(X,"parent");if(W!==void 0)Y.parentModelId=W;let V=t(X,"tps");if(V!==void 0)Y.tokensPerSec=V;let G=HE(X);if(G!==void 0)Y.strengths=G;let H=t(X,"price-in"),N=t(X,"price-out"),Q=t(X,"price-cache-read")!==void 0||t(X,"price-cache-write")!==void 0,L=H!==void 0||N!==void 0||Q,B=0;if(L){if(H===void 0!==(N===void 0))return f8("usage.price","a price changes as a pair: --price-in and --price-out together");let q=WE(X);if(typeof q!=="number")return q;B=q}if(Object.keys(Y).length===0&&!L)return f8("usage.input","nothing to change: pass at least one flag");let T=$.openRoster(X);if(!("roster"in T))return T;try{let q;if(L){let O=T.roster.getModel(Z,B);if(O===void 0)return{ok:!1,code:"notfound.model",msg:`model "${Z}" not found in the roster`,exit:3};let A;if(H===void 0){if(O.price===null)return f8("usage.price","the model has no price to build on: set --price-in and --price-out");A={in:O.price.usdPerMIn,out:O.price.usdPerMOut}}else A={in:H,out:N};let R=VE(X,A.in,O.price??void 0);if(!("usdPerMCacheRead"in R))return R;GE(X,R,A.in),q=R.sources,Y.price={usdPerMIn:A.in,usdPerMOut:A.out,usdPerMCacheRead:R.usdPerMCacheRead,usdPerMCacheWrite:R.usdPerMCacheWrite,validFrom:B}}T.roster.updateModel(Z,Y);let j=T.roster.getModel(Z);return{ok:!0,data:hY(j),...q!==void 0?{meta:{cacheRates:q}}:{}}}catch(q){return xY(q)}finally{T.close()}}}}function ue($){return{name:"list",summary:"roster entries with current prices; stale prices are flagged",flags:[{name:"all",description:"include disabled models"}],handler:(X)=>{let Z=$.openRoster(X);if(!("roster"in Z))return Z;try{let Y=Z.roster.listModels({includeInactive:K0(X,"all")});return{ok:!0,data:Y.map(hY),meta:{count:Y.length}}}catch(Y){return xY(Y)}finally{Z.close()}}}}function le($){return{name:"show",summary:"one roster entry with full price history",handler:(X)=>{let Z=X.args[0];if(Z===void 0)return f8("usage.input","model id required: myc model show <id>");let Y=$.openRoster(X);if(!("roster"in Y))return Y;try{let z=Y.roster.getModel(Z);if(z===void 0)return{ok:!1,code:"notfound.model",msg:`model "${Z}" not found in the roster`,exit:3};let J=Y.roster.priceHistory(Z).map((U)=>({validFrom:new Date(U.validFrom).toISOString(),usdPerMIn:U.usdPerMIn,usdPerMOut:U.usdPerMOut,usdPerMCacheRead:U.usdPerMCacheRead,usdPerMCacheWrite:U.usdPerMCacheWrite}));return{ok:!0,data:{...hY(z),priceHistory:J}}}catch(z){return xY(z)}finally{Y.close()}}}}function KE($,X){let Z=X?"enable":"disable";return{name:Z,summary:X?"return a model to the roster":"soft-delete: hide from list, keep record and price history",handler:(Y)=>{let z=Y.args[0];if(z===void 0)return f8("usage.input",`model id required: myc model ${Z} <id>`);let J=$.openRoster(Y);if(!("roster"in J))return J;try{if(X)J.roster.enableModel(z);else J.roster.disableModel(z);let U=J.roster.getModel(z);return{ok:!0,data:hY(U)}}catch(U){return xY(U)}finally{J.close()}}}}function NE($=be){return{name:"model",summary:"model roster: harness, effort, dated prices (swarm routing data)",subcommands:[he($),me($),ue($),le($),KE($,!1),KE($,!0)]}}var be,eU,JE,we,xe,QE,pe;var BE=v(()=>{n0();B4();V0();j0();R8();be={openRoster:ge};eU={read:0.1,write:1.25},JE=/^\d{4}-\d{2}-\d{2}$/,we=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;xe=[{name:"price-in",value:"number",description:"USD per 1M input tokens"},{name:"price-out",value:"number",description:"USD per 1M output tokens"},{name:"price-cache-read",value:"number",description:`USD per 1M cache-read tokens (default: ${eU.read*100}% of --price-in)`},{name:"price-cache-write",value:"number",description:`USD per 1M cache-write tokens (default: ${eU.write*100}% of --price-in)`},{name:"price-date",value:"string",description:"price valid from YYYY-MM-DD or full ISO timestamp (default: now)"}],QE=[{name:"family",value:"string",description:"model family for prior inheritance, e.g. claude-sonnet"},{name:"harness",value:"string",description:`launch harness: ${o0.join("|")}`},{name:"effort",value:"string",description:`reasoning effort: ${f5.join("|")} (default medium)`},{name:"version",value:"string",description:"model version, e.g. 5.4"},{name:"parent",value:"string",description:"previous version's model id"},{name:"tps",value:"number",description:"tokens per second (cold-start latency estimate)"},{name:"strengths",value:"string",list:!0,description:"comma-separated task classes the model is good at"},...xe];pe=NE()});function ce($){return $.endsWith("/")?$.slice(0,-1):$}function ie($){let X;try{X=new URL($)}catch{return}if(X.protocol!=="http:"&&X.protocol!=="https:")return;let Z=X.pathname.replace(/^\/+|\/+$/g,"");return{url:ce(`${X.origin}`),ws:Z}}function ne($,X=process.env){let Z=typeof $.flags.server==="string"?String($.flags.server):X.MYC_SERVER;if(Z===void 0||Z.trim()==="")return{kind:"none"};let Y=ie(Z.trim());if(Y===void 0)return{kind:"bad",failure:{ok:!1,code:"usage.server",msg:`'${Z}' is not an http(s) address of a myc server`,exit:2,hint:"example: --server https://myc.example/cherry"}};let z=X.MYC_TOKEN??"";if(z!==""&&!/^[\x21-\x7e]+$/.test(z))return{kind:"bad",failure:{ok:!1,code:"usage.token",msg:"MYC_TOKEN has characters that cannot go into an HTTP header \u2014 it looks mangled, not wrong",exit:2,hint:"a myc token is myc_ followed by base32; copy it whole, without spaces or line breaks"}};if(z==="")return{kind:"bad",failure:{ok:!1,code:"precond.no_token",msg:"the server needs an access token, and MYC_TOKEN is empty",exit:5,hint:"ask the server owner for one: myc serve --pg <url> --add-token <tenant>:<name>"}};let U=(typeof $.flags.ws==="string"?String($.flags.ws):void 0)??(Y.ws!==""?Y.ws:X.MYC_WS??"");if(U==="")return{kind:"bad",failure:{ok:!1,code:"usage.ws",msg:"the workspace is not set: put it in the address or pass --ws",exit:2,hint:"example: --server https://myc.example/cherry"}};return{kind:"remote",target:{url:Y.url,token:z,ws:U}}}function de($){if($.startsWith("usage."))return 2;if($.startsWith("notfound."))return 3;if($.startsWith("conflict."))return 4;if($.startsWith("precond."))return 5;if($.startsWith("denied."))return 8;if($.startsWith("degraded."))return 6;if($.startsWith("timeout."))return 9;return 1}class TE{target;fetchImpl;constructor($,X=fetch){this.target=$;this.fetchImpl=X}get ws(){return this.target.ws}async call($,X,Z){let Y;try{Y=await this.fetchImpl(`${this.target.url}${X}`,{method:$,headers:{authorization:`Bearer ${this.target.token}`,...Z===void 0?{}:{"content-type":"application/json"}},...Z===void 0?{}:{body:JSON.stringify(Z)}})}catch(U){throw new mY({ok:!1,code:"degraded.unreachable",msg:`the server at ${this.target.url} did not answer: ${U instanceof Error?U.message:String(U)}`,exit:6},"unreachable")}let z=await Y.text(),J;try{J=JSON.parse(z)}catch{throw new mY({ok:!1,code:"internal.bad_answer",msg:`the server answered ${Y.status} with something that is not a myc envelope`,exit:1},"bad answer")}if(J.ok!==!0){let U=J.error?.code??`internal.http_${Y.status}`;throw new mY({ok:!1,code:U,msg:J.error?.msg??`the server answered ${Y.status}`,exit:de(U),...J.error?.hint===void 0?{}:{hint:J.error.hint}},U)}return{data:J.data,meta:J.meta??{}}}async workspaces(){return this.call("GET","/v1/ws")}async listNodes($){let X=new URLSearchParams;for(let[Y,z]of Object.entries($))if(z!==void 0&&z!=="")X.set(Y,String(z));let Z=X.toString();return this.call("GET",`/v1/ws/${encodeURIComponent(this.target.ws)}/nodes${Z===""?"":`?${Z}`}`)}async getNode($){return this.call("GET",`/v1/ws/${encodeURIComponent(this.target.ws)}/nodes/${encodeURIComponent($)}`)}async createNode($){return this.call("POST",`/v1/ws/${encodeURIComponent(this.target.ws)}/nodes`,$)}async patchNode($,X){return this.call("PATCH",`/v1/ws/${encodeURIComponent(this.target.ws)}/nodes/${encodeURIComponent($)}`,X)}async addEdge($){return this.call("POST",`/v1/ws/${encodeURIComponent(this.target.ws)}/edges`,$)}async removeEdge($){return this.call("DELETE",`/v1/ws/${encodeURIComponent(this.target.ws)}/edges`,$)}async ready($){let X=new URLSearchParams;for(let[Y,z]of Object.entries($))if(z!==void 0&&z!=="")X.set(Y,String(z));let Z=X.toString();return this.call("GET",`/v1/ws/${encodeURIComponent(this.target.ws)}/ready${Z===""?"":`?${Z}`}`)}async prime($){let X=new URLSearchParams;for(let[Y,z]of Object.entries($))if(z!==void 0&&z!=="")X.set(Y,String(z));let Z=X.toString();return this.call("GET",`/v1/ws/${encodeURIComponent(this.target.ws)}/prime${Z===""?"":`?${Z}`}`)}async sync($){return this.call("POST",`/v1/ws/${encodeURIComponent(this.target.ws)}/sync`,$)}async claim($,X){return this.call("POST",`/v1/ws/${encodeURIComponent(this.target.ws)}/ready/claim`,{id:$,...X===void 0?{}:{lease_minutes:X}})}}async function $8($,X,Z=process.env,Y=fetch){let z=ne($,Z);if(z.kind==="none")return;if(z.kind==="bad")return z.failure;try{return await X(new TE(z.target,Y))}catch(J){if(J instanceof mY)return J.failure;throw J}}var mY;var w5=v(()=>{V0();mY=class mY extends Error{failure;constructor($,X){super(X);this.failure=$;this.name="RemoteError"}}});var gB={};s(gB,{wsPathsOfTouched:()=>vE,withTranscript:()=>gE,transcriptFailure:()=>RE,tokenSource:()=>_E,tokenArgs:()=>pY,textPathsOf:()=>kE,taskClassOf:()=>X00,swarmOn:()=>C7,settleAttemptClass:()=>yB,scopeDistribution:()=>zK,runView:()=>M9,resolveModelId:()=>lY,resolveLaunch:()=>fB,reportCommand:()=>B00,renderLiveHuman:()=>SE,recordedSpend:()=>mE,realProbe:()=>ZK,realAttemptDeps:()=>EB,predictionAgreement:()=>yE,predictFromTask:()=>cY,openSwarmAt:()=>AE,observe:()=>fE,modelArg:()=>PE,keyFromTask:()=>P9,inertProbe:()=>te,finishWithFact:()=>JK,dbPathOf:()=>XK,createReportCommand:()=>pE,createAttemptCommand:()=>lE,classDistribution:()=>C9,caveatArgs:()=>YK,attemptView:()=>D9,attemptFailure:()=>$6,attemptCommand:()=>L00,anchorPathsOf:()=>vB,RECOST_ACTIONS:()=>uE});import{existsSync as CE,statSync as oe}from"fs";import{homedir as ae}from"os";import{join as kB,resolve as A9}from"path";import{Database as se}from"bun:sqlite";function XK($){if($.globals.db!==void 0)return $.globals.db;let X=A9($.globals.directory??process.cwd()),Z=K$(X);return"dbPath"in Z?Z.dbPath:kB(X,".myc","myc.db")}function AE($,X=Date.now){if(!CE($))return{ok:!1,code:"ws.not_initialized",msg:`workspace not initialized: no ${$}`,exit:7,hint:"myc init"};try{I$()}catch(Y){let z=N5(Y);if(z!==void 0)return z;throw Y}let Z=new se($);for(let Y of j6)Z.exec(Y);return N9(Z),{db:Z,roster:new L4(Z,X),attribution:new SY(Z,X),close:()=>Z.close()}}function re($,X,Z){try{let Y=Bun.spawnSync($,{cwd:X,stdout:"pipe",stderr:"ignore",timeout:Z});if(Y.exitCode!==0)return null;let z=Y.stdout.toString().trim();return z===""?null:z}catch{return null}}function M$($,X,Z){return{ok:!1,code:$,msg:X,exit:2,hint:Z}}function $6($){if($ instanceof F$)return{ok:!1,code:$.code,msg:$.message,exit:$.code==="notfound.model"?3:2,hint:$.code==="notfound.model"?"myc model list --all":void 0};if($ instanceof z$){let X=$.code==="notfound.attempt"?3:$.code==="conflict.finished"?4:2;return{ok:!1,code:$.code,msg:$.message,exit:X}}throw $}function lY($,X){if($.getModel(X)!==void 0)return{ok:!0,modelId:X};let Z=X.toLowerCase(),Y=$.listModels({includeInactive:!0}).filter((z)=>z.model.modelId.toLowerCase().includes(Z)||z.model.family.toLowerCase()===Z).map((z)=>z.model.modelId);if(Y.length===1)return{ok:!0,modelId:Y[0]};if(Y.length===0)return{ok:!1,failure:{ok:!1,code:"notfound.model",msg:`model "${X}" not found in the roster; an outcome cannot be recorded without a roster model`,exit:3,hint:"myc model list --all | myc model add <id> \u2026"}};return{ok:!1,failure:{ok:!1,code:"conflict.model",msg:`"${X}" matches several models: ${Y.join(", ")}`,exit:4,hint:"narrow down the model id"}}}function PE($,X){let Z=f($,"model")??process.env.MYC_MODEL;if(Z===void 0||Z.trim()==="")return{ok:!1,failure:M$("usage.model","no model given: which model ran the task?","--model <id> or the MYC_MODEL environment variable")};return lY(X,Z)}function ee($){let X=process.env[$];if(X===void 0)return;let Z=Number(X);return Number.isInteger(Z)&&Z>=0?Z:void 0}function pY($){let X=(z,J)=>t($,z)??ee(J),Z={},Y=[["tokens-in","MYC_TOKENS_IN","tokensIn"],["tokens-out","MYC_TOKENS_OUT","tokensOut"],["cache-read","MYC_TOKENS_CACHE_READ","tokensCacheRead"],["cache-write","MYC_TOKENS_CACHE_WRITE","tokensCacheWrite"]];for(let[z,J,U]of Y){let K=X(z,J);if(K!==void 0)Z[U]=K}return Z}function ME($){return $.startsWith("~/")?kB(ae(),$.slice(2)):$}function RE($){let X=$.code==="transcript.missing"||$.code==="transcript.dir_missing"||$.code==="notfound.session"||$.code==="notfound.task_session"?3:$.code==="conflict.session"?4:$.code==="transcript.unreadable"?1:5;return{ok:!1,code:$.code,msg:$.message,exit:X,hint:$.hint}}function _E($){let X=f($,"from-transcript"),Z=f($,"from-session");if(X!==void 0&&Z!==void 0)return M$("usage.token_source","--from-transcript and --from-session together: usage has exactly one source");if(X===void 0&&Z===void 0)return{tokens:pY($)};let Y=$00.filter((z)=>t($,z)!==void 0);if(Y.length>0)return M$("usage.token_source",`usage given both by a transcript and by flags (${Y.map((z)=>`--${z}`).join(", ")}); there must be exactly one source`);try{let z=X!==void 0?ME(X):F9(Z,A9($.globals.directory??process.cwd())),J=q9(z);return{tokens:{tokensIn:J.tokensIn,tokensOut:J.tokensOut,tokensCacheRead:J.tokensCacheRead,tokensCacheWrite:J.tokensCacheWrite},transcript:J}}catch(z){if(z instanceof e0)return RE(z);throw z}}function YK($){let X=f($,"caveat");if(X===void 0)return[];let Z=X.split(",").map((z)=>z.trim().replace(/-/g,"_")).filter((z)=>z!==""),Y=Z.filter((z)=>!x6.includes(z));if(Y.length>0)return M$("usage.caveat",`unknown caveat: ${Y.join(", ")}; allowed: ${x6.join(", ")}`);return Z}function IE($,X){let Z=X.replace(/^\.\//,"");if(Z===""||Z.startsWith("/")||Z===".."||Z.startsWith("../"))return null;let Y=A$($.attrs).repo??"";if(Y===""||Z===Y||Z.startsWith(`${Y}/`))return Z;return H8(Y,Z)}function vB($,X,Z){let Y=[],z=$.attrs.anchors;if(Array.isArray(z)){for(let U of z)if(U!==null&&typeof U==="object"&&typeof U.path==="string"){let K=IE($,U.path);if(K!==null)Y.push(K)}}let J=X.query(`SELECT a.repo_id AS repo_id, a.path AS path
|
|
3346
|
+
`)}var Q9;var OB=v(()=>{$B();ZB();zB();UB();WB();GB();QB();LB();TB();FB();$B();ZB();zB();UB();WB();GB();QB();LB();TB();FB();Q9=[eL,XB,YB,JB,KB,VB,HB,NB,BB,qB]});import{createHash as Re}from"crypto";function CB($){return Re("sha256").update($).digest("hex")}function _e($,X){if($.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1").get(h6)===null)return!1;let Y=new Map($.query(`SELECT version, checksum FROM ${h6}`).all().map((z)=>[z.version,z.checksum]));if(Y.size!==X.length)return!1;return X.every((z)=>Y.get(z.version)===CB(H9(z)))}function N9($,X=Q9){let Z=[...X].sort((z,J)=>z.version-J.version),Y=Z.reduce((z,J)=>Math.max(z,J.version),0);if(_e($,Z))return;$.exec("BEGIN IMMEDIATE");try{$.exec(jB);let z=new Map($.query(`SELECT version, checksum FROM ${h6}`).all().map((U)=>[U.version,U.checksum]));for(let U of z.keys())if(U>Y)throw new bY("schema.newer",`database is newer than the swarm schema version this binary knows: ${U} > ${Y}`);let J=Date.now();for(let U of Z){let K=z.get(U.version);if(K!==void 0){if(K!==CB(H9(U)))throw new bY("schema.checksum",`migration ${U.version} (${U.name}) changed after it was applied`);continue}for(let G of tU(U))$.exec(G);let W=new Set($.query("SELECT name FROM sqlite_master").all().map((G)=>G.name)),V=U.objects.filter((G)=>!W.has(G));if(V.length>0)throw new bY("schema.objects",`objects not created after applying ${U.name}: ${V.join(", ")}`);$.query(`INSERT INTO ${h6} (version, name, checksum, applied_at)
|
|
3347
|
+
VALUES (?1, ?2, ?3, ?4)`).run(U.version,U.name,CB(H9(U)),J)}$.exec("COMMIT")}catch(z){throw $.exec("ROLLBACK"),z}}var bY;var tk=v(()=>{OB();bY=class bY extends Error{code;constructor($,X){super(X);this.name="SwarmSchemaError",this.code=$}}});import{existsSync as wY,readdirSync as Ie,readFileSync as $E,statSync as _Q0}from"fs";import{homedir as ke}from"os";import{join as T9}from"path";function B9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Ee($,X,Z){let Y=$+X;if(!Number.isSafeInteger(Y))throw new e0("transcript.overflow",`sum of ${Z} exceeded exact integers (${Y}); the number read cannot be trusted`);return Y}function ve($,X,Z,Y){if(typeof $!=="number"||!Number.isSafeInteger($)||$<0)throw new e0("transcript.bad_field",`${Y}:${Z}: usage.${X} = ${JSON.stringify($)} \u2014 not an integer \u2265 0; `+"unexpected transcript format, usage not read","check the format or fill in usage with --tokens-in/--tokens-out");return $}function ye($){let X=$.timestamp;if(typeof X!=="string")return;let Z=Date.parse(X);return Number.isFinite(Z)?Z:void 0}function q9($,X={}){if(!wY($))throw new e0("transcript.missing",`no transcript: ${$}`,"myc attempt finish \u2026 --from-session <uuid> or manual usage flags");let Z;try{Z=$E($,"utf8")}catch(q){throw new e0("transcript.unreadable",`transcript ${$} is unreadable: ${q.message}`)}let Y=new Map,z=new Set,J=new Set,U=0,K=0,W=0,V=0,G=null,H=null,N=Z.split(`
|
|
3348
|
+
`);for(let q=0;q<N.length;q+=1){let j=N[q];if(j.trim()==="")continue;let O;try{O=JSON.parse(j)}catch{continue}if(!B9(O))continue;if(X.until!==void 0||X.since!==void 0){let k=ye(O);if(k!==void 0){let y=X.until!==void 0&&k>X.until,g=X.since!==void 0&&k<X.since;if(y||g){K+=1;continue}}}U+=1;let A=O.timestamp;if(typeof A==="string"){if(G===null)G=A;H=A}let R=O.message;if(!B9(R))continue;let D=R.usage;if(!B9(D))continue;W+=1;let F=R.id,P=O.requestId,_=typeof F==="string"&&F!==""?F:typeof P==="string"&&P!==""?P:void 0;if(_===void 0)throw new e0("transcript.no_key",`${$}:${q+1}: a record with usage has neither message.id nor requestId; there is nothing to merge copies of one response by, the sum would be inflated`,"the transcript format changed \u2014 fill in usage with manual flags");let M=R.model;if(typeof M==="string"&&M!=="")J.add(M);let E=Y.get(_)??{},b=!1;for(let[k,y]of L9){if(!(k in D))continue;z.add(k),b=!0;let g=ve(D[k],k,q+1,$),S=E[y];if(S===void 0||g>S)E[y]=g}if(b)V+=1;Y.set(_,E)}if(U===0)throw new e0("transcript.empty",`not a single record parsed in transcript ${$}`);if(W===0)throw new e0("transcript.no_usage",`none of the ${U} messages in ${$} has message.usage; `+"usage not read \u2014 this is a refusal, not zero","the transcript format changed; fill in usage with --tokens-in/--tokens-out");if(V===0)throw new e0("transcript.no_fields",`usage present in ${W} messages of ${$}, but not a single known field (${L9.map(([q])=>q).join(", ")}); usage not read`,"the transcript format changed; fill in usage with manual flags");let Q=L9.filter(([q])=>!z.has(q)).map(([q])=>q);if(Q.length>0)throw new e0("transcript.missing_field",`field ${Q.join(", ")} never appears in transcript ${$}; silently recording zero for it would understate the cost`,"the transcript format changed; fill in usage with manual flags");let L={tokensIn:0,tokensOut:0,tokensCacheRead:0,tokensCacheWrite:0};for(let q of Y.values())for(let[,j]of L9)L[j]=Ee(L[j],q[j]??0,j);if(L.tokensIn+L.tokensOut+L.tokensCacheRead+L.tokensCacheWrite===0)throw new e0("transcript.no_tokens",`${$}: ${Y.size} model responses parsed, but total usage is 0; `+"a real session never looks like this \u2014 nothing to read","the transcript format changed; fill in usage with manual flags");let T=$.split("/").pop()??$;return{path:$,sessionId:T.endsWith(".jsonl")?T.slice(0,-6):null,...L,responses:Y.size,usageRecords:W,records:U,outsideWindow:K,startedAt:G,endedAt:H,models:[...J].sort()}}function PB($,X){let Z;try{Z=$E($,"utf8")}catch{return null}let Y=(K)=>K.tokensIn===X.tokensIn&&K.tokensOut===X.tokensOut&&K.tokensCacheRead===X.tokensCacheRead&&K.tokensCacheWrite===X.tokensCacheWrite,z={tokensIn:0,tokensOut:0,tokensCacheRead:0,tokensCacheWrite:0};if(Y(z))return{records:0,at:null};let J=new Map,U=0;for(let K of Z.split(`
|
|
3349
|
+
`)){if(K.trim()==="")continue;let W;try{W=JSON.parse(K)}catch{continue}if(!B9(W))continue;U+=1;let V=W.message;if(!B9(V))continue;let G=V.usage;if(!B9(G))continue;let H=V.id,N=W.requestId,Q=typeof H==="string"&&H!==""?H:typeof N==="string"&&N!==""?N:void 0;if(Q===void 0)continue;let L=J.get(Q)??{};for(let[B,T]of L9){let q=G[B];if(typeof q!=="number"||!Number.isSafeInteger(q)||q<0)continue;let j=L[T]??0;if(q>j)z[T]+=q-j,L[T]=q}if(J.set(Q,L),Y(z)){let B=W.timestamp;return{records:U,at:typeof B==="string"?B:null}}}return null}function DB($=process.env){let X=$.CLAUDE_CONFIG_DIR;return T9(X!==void 0&&X.trim()!==""?X:T9(ke(),".claude"),"projects")}function XE($,X=process.env){let Z=X.MYC_TRANSCRIPT_DIR;if(Z!==void 0&&Z.trim()!=="")return Z;return T9(DB(X),$.replace(/[^A-Za-z0-9]/g,"-"))}function F9($,X,Z=process.env){let Y=Z.MYC_TRANSCRIPT_DIR;if(Y!==void 0&&Y.trim()!=="")return YE(Y,$);let z=$.endsWith(".jsonl")?$.slice(0,-6):$,J=T9(XE(X,Z),`${z}.jsonl`);if(wY(J))return J;let U=DB(Z);ZE(U);let K;try{K=Ie(U)}catch(W){throw new e0("transcript.unreadable",`transcript directory ${U} is unreadable: ${W.message}`)}for(let W of K.sort()){let V=T9(U,W,`${z}.jsonl`);if(wY(V))return V}throw new e0("notfound.session",`session "${z}" not found in any project directory under ${U}`,"myc attempt finish \u2026 --from-transcript <file>")}function AB($){return $.toLowerCase().split(/[^a-z0-9]+/).filter((X)=>X!=="")}function ek($,X){return $.length>0&&$.every((Z)=>X.has(Z))}function j9($,X){let Z=$.filter((U)=>!U.startsWith("<")),Y=AB(X.family),z=AB(X.modelId.split("/").pop()??X.modelId),J=Z.filter((U)=>{let K=new Set(AB(U));return!ek(Y,K)&&!ek(z,K)});return{ok:Z.length>0&&J.length===0,seen:Z,foreign:J}}function ZE($){if(!wY($))throw new e0("transcript.dir_missing",`no transcript directory: ${$}`,"give a file with --from-transcript or a directory with $MYC_TRANSCRIPT_DIR")}function YE($,X){ZE($);let Z=X.endsWith(".jsonl")?X.slice(0,-6):X,Y=T9($,`${Z}.jsonl`);if(!wY(Y))throw new e0("notfound.session",`session "${Z}" not found in ${$}`,"myc attempt finish \u2026 --from-transcript <file>");return Y}var e0,L9;var zE=v(()=>{e0=class e0 extends Error{code;hint;constructor($,X,Z){super(X);this.name="TranscriptError",this.code=$,this.hint=Z}};L9=[["input_tokens","tokensIn"],["output_tokens","tokensOut"],["cache_read_input_tokens","tokensCacheRead"],["cache_creation_input_tokens","tokensCacheWrite"]]});var B4=v(()=>{wL();sL();mL();rk();oU();dL();tk();OB();zE()});var LE={};s(LE,{modelCommand:()=>ce,createModelCommand:()=>NE,CACHE_PRICE_SHARES:()=>eU});import{existsSync as fe}from"fs";import{resolve as Se}from"path";import{Database as ge}from"bun:sqlite";function be($){let X=Se($.globals.directory??process.cwd()),Z;if($.globals.db!==void 0){if(Z=$.globals.db,!fe(Z))return{ok:!1,code:"ws.not_initialized",msg:`workspace not initialized: no ${Z}`,exit:7,hint:"myc init"}}else{let J=K$(X);if(!("dbPath"in J))return h2(J);Z=J.dbPath}let Y=w2($);if(Y!==void 0)return Y;let z=new ge(Z);for(let J of j6)z.exec(J);return N9(z),{roster:new L4(z),close:()=>z.close()}}function xY($){if($ instanceof F$){let X=$.code==="notfound.model"?3:$.code==="conflict.model"?4:2;return{ok:!1,code:$.code,msg:$.message,exit:X}}throw $}function f8($,X){return{ok:!1,code:$,msg:X,exit:2}}function hY($){return{modelId:$.model.modelId,family:$.model.family,version:$.model.version,parentModelId:$.model.parentModelId,harness:$.model.harness,effort:$.model.effort,tokensPerSec:$.model.tokensPerSec,strengths:$.model.strengths,active:$.model.active,price:$.price===null?null:{usdPerMIn:$.price.usdPerMIn,usdPerMOut:$.price.usdPerMOut,usdPerMCacheRead:$.price.usdPerMCacheRead,usdPerMCacheWrite:$.price.usdPerMCacheWrite,validFrom:new Date($.price.validFrom).toISOString()},priceAgeDays:$.priceAgeDays,priceStale:$.priceStale,cacheUnpriced:$.cacheUnpriced,createdAt:new Date($.model.createdAt).toISOString(),updatedAt:new Date($.model.updatedAt).toISOString()}}function WE($){let X=f($,"price-date");if(X===void 0)return Date.now();let Z=f8("usage.date",`--price-date must be YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS[.mmm]Z, got "${X}"`);if(!JE.test(X)&&!xe.test(X))return Z;let Y=Date.parse(JE.test(X)?`${X}T00:00:00Z`:X);if(!Number.isFinite(Y))return Z;return Y}function UE($,X){return Math.round($*X*1e6)/1e6}function VE($,X,Z){let Y=t($,"price-cache-read"),z=t($,"price-cache-write");for(let[V,G]of[["--price-cache-read",Y],["--price-cache-write",z]])if(G!==void 0&&(!Number.isFinite(G)||G<0))return f8("usage.price",`${V} must be a number \u2265 0, got "${G}"`);let J=[],U=(V,G,H)=>{if(V!==void 0)return{value:V,source:"flag"};let N=eU[G];if(Z!==void 0&&H!==void 0&&H!==UE(Z.usdPerMIn,N))return{value:H,source:"kept"};return J.push(`${G}=${N*100}%`),{value:UE(X,N),source:"default"}},K=U(Y,"read",Z?.usdPerMCacheRead),W=U(z,"write",Z?.usdPerMCacheWrite);return{usdPerMCacheRead:K.value,usdPerMCacheWrite:W.value,defaulted:J,sources:{read:K.source,write:W.source}}}function GE($,X,Z){if(X.defaulted.length===0)return;$.warn("price.cache_defaulted",`cache rates not set: applied the default ${X.defaulted.join(", ")} of --price-in ${Z} \u2192 read ${X.usdPerMCacheRead}, write ${X.usdPerMCacheWrite} $/1M. This is an assumption, not the provider's price list: set --price-cache-read/--price-cache-write`)}function HE($){let X=f($,"strengths");if(X===void 0)return;return X.split(",").map((Z)=>Z.trim()).filter((Z)=>Z!=="")}function me($){return{name:"add",summary:"add a model to the roster",help:"A price is required and stored with a date (--price-date, default today): a fact, not a constant.",flags:QE,handler:(X)=>{let Z=X.args[0];if(Z===void 0)return f8("usage.input","model id required: myc model add <id> \u2026");let Y=f(X,"family");if(Y===void 0)return f8("usage.input","--family required");let z=f(X,"harness");if(z===void 0)return f8("usage.input","--harness required");let J=t(X,"price-in"),U=t(X,"price-out");if(J===void 0||U===void 0)return f8("usage.price","--price-in and --price-out required (USD per 1M tokens)");let K=WE(X);if(typeof K!=="number")return K;let W=VE(X,J);if(!("usdPerMCacheRead"in W))return W;let V=$.openRoster(X);if(!("roster"in V))return V;try{let G={modelId:Z,family:Y,harness:z,effort:f(X,"effort"),version:f(X,"version"),parentModelId:f(X,"parent"),tokensPerSec:t(X,"tps"),strengths:HE(X),price:{usdPerMIn:J,usdPerMOut:U,usdPerMCacheRead:W.usdPerMCacheRead,usdPerMCacheWrite:W.usdPerMCacheWrite,validFrom:K}};GE(X,W,J);let H=V.roster.addModel(G),N=V.roster.getModel(H.modelId);return{ok:!0,data:hY(N)}}catch(G){return xY(G)}finally{V.close()}}}}function ue($){return{name:"update",summary:"change roster fields; a new price is a new dated fact",flags:QE,handler:(X)=>{let Z=X.args[0];if(Z===void 0)return f8("usage.input","model id required: myc model update <id> \u2026");let Y={},z=f(X,"family");if(z!==void 0)Y.family=z;let J=f(X,"harness");if(J!==void 0)Y.harness=J;let U=f(X,"effort");if(U!==void 0)Y.effort=U;let K=f(X,"version");if(K!==void 0)Y.version=K;let W=f(X,"parent");if(W!==void 0)Y.parentModelId=W;let V=t(X,"tps");if(V!==void 0)Y.tokensPerSec=V;let G=HE(X);if(G!==void 0)Y.strengths=G;let H=t(X,"price-in"),N=t(X,"price-out"),Q=t(X,"price-cache-read")!==void 0||t(X,"price-cache-write")!==void 0,L=H!==void 0||N!==void 0||Q,B=0;if(L){if(H===void 0!==(N===void 0))return f8("usage.price","a price changes as a pair: --price-in and --price-out together");let q=WE(X);if(typeof q!=="number")return q;B=q}if(Object.keys(Y).length===0&&!L)return f8("usage.input","nothing to change: pass at least one flag");let T=$.openRoster(X);if(!("roster"in T))return T;try{let q;if(L){let O=T.roster.getModel(Z,B);if(O===void 0)return{ok:!1,code:"notfound.model",msg:`model "${Z}" not found in the roster`,exit:3};let A;if(H===void 0){if(O.price===null)return f8("usage.price","the model has no price to build on: set --price-in and --price-out");A={in:O.price.usdPerMIn,out:O.price.usdPerMOut}}else A={in:H,out:N};let R=VE(X,A.in,O.price??void 0);if(!("usdPerMCacheRead"in R))return R;GE(X,R,A.in),q=R.sources,Y.price={usdPerMIn:A.in,usdPerMOut:A.out,usdPerMCacheRead:R.usdPerMCacheRead,usdPerMCacheWrite:R.usdPerMCacheWrite,validFrom:B}}T.roster.updateModel(Z,Y);let j=T.roster.getModel(Z);return{ok:!0,data:hY(j),...q!==void 0?{meta:{cacheRates:q}}:{}}}catch(q){return xY(q)}finally{T.close()}}}}function le($){return{name:"list",summary:"roster entries with current prices; stale prices are flagged",flags:[{name:"all",description:"include disabled models"}],handler:(X)=>{let Z=$.openRoster(X);if(!("roster"in Z))return Z;try{let Y=Z.roster.listModels({includeInactive:K0(X,"all")});return{ok:!0,data:Y.map(hY),meta:{count:Y.length}}}catch(Y){return xY(Y)}finally{Z.close()}}}}function pe($){return{name:"show",summary:"one roster entry with full price history",handler:(X)=>{let Z=X.args[0];if(Z===void 0)return f8("usage.input","model id required: myc model show <id>");let Y=$.openRoster(X);if(!("roster"in Y))return Y;try{let z=Y.roster.getModel(Z);if(z===void 0)return{ok:!1,code:"notfound.model",msg:`model "${Z}" not found in the roster`,exit:3};let J=Y.roster.priceHistory(Z).map((U)=>({validFrom:new Date(U.validFrom).toISOString(),usdPerMIn:U.usdPerMIn,usdPerMOut:U.usdPerMOut,usdPerMCacheRead:U.usdPerMCacheRead,usdPerMCacheWrite:U.usdPerMCacheWrite}));return{ok:!0,data:{...hY(z),priceHistory:J}}}catch(z){return xY(z)}finally{Y.close()}}}}function KE($,X){let Z=X?"enable":"disable";return{name:Z,summary:X?"return a model to the roster":"soft-delete: hide from list, keep record and price history",handler:(Y)=>{let z=Y.args[0];if(z===void 0)return f8("usage.input",`model id required: myc model ${Z} <id>`);let J=$.openRoster(Y);if(!("roster"in J))return J;try{if(X)J.roster.enableModel(z);else J.roster.disableModel(z);let U=J.roster.getModel(z);return{ok:!0,data:hY(U)}}catch(U){return xY(U)}finally{J.close()}}}}function NE($=we){return{name:"model",summary:"model roster: harness, effort, dated prices (swarm routing data)",subcommands:[me($),ue($),le($),pe($),KE($,!1),KE($,!0)]}}var we,eU,JE,xe,he,QE,ce;var BE=v(()=>{n0();B4();V0();j0();R8();we={openRoster:be};eU={read:0.1,write:1.25},JE=/^\d{4}-\d{2}-\d{2}$/,xe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;he=[{name:"price-in",value:"number",description:"USD per 1M input tokens"},{name:"price-out",value:"number",description:"USD per 1M output tokens"},{name:"price-cache-read",value:"number",description:`USD per 1M cache-read tokens (default: ${eU.read*100}% of --price-in)`},{name:"price-cache-write",value:"number",description:`USD per 1M cache-write tokens (default: ${eU.write*100}% of --price-in)`},{name:"price-date",value:"string",description:"price valid from YYYY-MM-DD or full ISO timestamp (default: now)"}],QE=[{name:"family",value:"string",description:"model family for prior inheritance, e.g. claude-sonnet"},{name:"harness",value:"string",description:`launch harness: ${o0.join("|")}`},{name:"effort",value:"string",description:`reasoning effort: ${f5.join("|")} (default medium)`},{name:"version",value:"string",description:"model version, e.g. 5.4"},{name:"parent",value:"string",description:"previous version's model id"},{name:"tps",value:"number",description:"tokens per second (cold-start latency estimate)"},{name:"strengths",value:"string",list:!0,description:"comma-separated task classes the model is good at"},...he];ce=NE()});import{readFileSync as ie}from"fs";import{dirname as ne,join as de}from"path";function oe($){return $.endsWith("/")?$.slice(0,-1):$}function ae($=process.cwd()){let X=$;for(;;){try{let Y=/^slug\s*=\s*"([a-z][a-z0-9]{1,7})"/m.exec(ie(de(X,".myc","workspace.toml"),"utf8"));if(Y!==null)return Y[1]}catch{}let Z=ne(X);if(Z===X)return;X=Z}}function se($){let X;try{X=new URL($)}catch{return}if(X.protocol!=="http:"&&X.protocol!=="https:")return;let Z=X.pathname.replace(/^\/+|\/+$/g,"");return{url:oe(`${X.origin}`),ws:Z}}function re($,X=process.env){let Z=typeof $.flags.server==="string"?String($.flags.server):X.MYC_SERVER;if(Z===void 0||Z.trim()==="")return{kind:"none"};let Y=se(Z.trim());if(Y===void 0)return{kind:"bad",failure:{ok:!1,code:"usage.server",msg:`'${Z}' is not an http(s) address of a myc server`,exit:2,hint:"example: --server https://myc.example/cherry"}};let z=X.MYC_TOKEN??"";if(z!==""&&!/^[\x21-\x7e]+$/.test(z))return{kind:"bad",failure:{ok:!1,code:"usage.token",msg:"MYC_TOKEN has characters that cannot go into an HTTP header \u2014 it looks mangled, not wrong",exit:2,hint:"a myc token is myc_ followed by base32; copy it whole, without spaces or line breaks"}};if(z==="")return{kind:"bad",failure:{ok:!1,code:"precond.no_token",msg:"the server needs an access token, and MYC_TOKEN is empty",exit:5,hint:"ask the server owner for one: myc serve --pg <url> --add-token <tenant>:<name>"}};let J=typeof $.flags.ws==="string"?String($.flags.ws):void 0,U=X.MYC_WS?.trim()||void 0,K=J??(Y.ws!==""?Y.ws:U)??ae($.globals.directory??process.cwd())??"";if(K==="")return{kind:"bad",failure:{ok:!1,code:"usage.ws",msg:"the workspace is not set: it defaults to the slug of the local workspace (.myc/workspace.toml), and this directory has none",exit:2,hint:"run inside a workspace, or pass --ws / set MYC_WS / put the workspace in the server address"}};return{kind:"remote",target:{url:Y.url,token:z,ws:K}}}function te($){if($.startsWith("usage."))return 2;if($.startsWith("notfound."))return 3;if($.startsWith("conflict."))return 4;if($.startsWith("precond."))return 5;if($.startsWith("denied."))return 8;if($.startsWith("degraded."))return 6;if($.startsWith("timeout."))return 9;return 1}class TE{target;fetchImpl;constructor($,X=fetch){this.target=$;this.fetchImpl=X}get ws(){return this.target.ws}async call($,X,Z){let Y;try{Y=await this.fetchImpl(`${this.target.url}${X}`,{method:$,headers:{authorization:`Bearer ${this.target.token}`,...Z===void 0?{}:{"content-type":"application/json"}},...Z===void 0?{}:{body:JSON.stringify(Z)}})}catch(U){throw new mY({ok:!1,code:"degraded.unreachable",msg:`the server at ${this.target.url} did not answer: ${U instanceof Error?U.message:String(U)}`,exit:6},"unreachable")}let z=await Y.text(),J;try{J=JSON.parse(z)}catch{throw new mY({ok:!1,code:"internal.bad_answer",msg:`the server answered ${Y.status} with something that is not a myc envelope`,exit:1},"bad answer")}if(J.ok!==!0){let U=J.error?.code??`internal.http_${Y.status}`;throw new mY({ok:!1,code:U,msg:J.error?.msg??`the server answered ${Y.status}`,exit:te(U),...J.error?.hint===void 0?{}:{hint:J.error.hint}},U)}return{data:J.data,meta:J.meta??{}}}async workspaces(){return this.call("GET","/v1/ws")}async listNodes($){let X=new URLSearchParams;for(let[Y,z]of Object.entries($))if(z!==void 0&&z!=="")X.set(Y,String(z));let Z=X.toString();return this.call("GET",`/v1/ws/${encodeURIComponent(this.target.ws)}/nodes${Z===""?"":`?${Z}`}`)}async getNode($){return this.call("GET",`/v1/ws/${encodeURIComponent(this.target.ws)}/nodes/${encodeURIComponent($)}`)}async createNode($){return this.call("POST",`/v1/ws/${encodeURIComponent(this.target.ws)}/nodes`,$)}async patchNode($,X){return this.call("PATCH",`/v1/ws/${encodeURIComponent(this.target.ws)}/nodes/${encodeURIComponent($)}`,X)}async addEdge($){return this.call("POST",`/v1/ws/${encodeURIComponent(this.target.ws)}/edges`,$)}async removeEdge($){return this.call("DELETE",`/v1/ws/${encodeURIComponent(this.target.ws)}/edges`,$)}async ready($){let X=new URLSearchParams;for(let[Y,z]of Object.entries($))if(z!==void 0&&z!=="")X.set(Y,String(z));let Z=X.toString();return this.call("GET",`/v1/ws/${encodeURIComponent(this.target.ws)}/ready${Z===""?"":`?${Z}`}`)}async prime($){let X=new URLSearchParams;for(let[Y,z]of Object.entries($))if(z!==void 0&&z!=="")X.set(Y,String(z));let Z=X.toString();return this.call("GET",`/v1/ws/${encodeURIComponent(this.target.ws)}/prime${Z===""?"":`?${Z}`}`)}async sync($){return this.call("POST",`/v1/ws/${encodeURIComponent(this.target.ws)}/sync`,$)}async claim($,X){return this.call("POST",`/v1/ws/${encodeURIComponent(this.target.ws)}/ready/claim`,{id:$,...X===void 0?{}:{lease_minutes:X}})}}async function $8($,X,Z=process.env,Y=fetch){let z=re($,Z);if(z.kind==="none")return;if(z.kind==="bad")return z.failure;try{return await X(new TE(z.target,Y))}catch(J){if(J instanceof mY)return J.failure;throw J}}var mY;var w5=v(()=>{V0();mY=class mY extends Error{failure;constructor($,X){super(X);this.failure=$;this.name="RemoteError"}}});var gB={};s(gB,{wsPathsOfTouched:()=>vE,withTranscript:()=>gE,transcriptFailure:()=>RE,tokenSource:()=>_E,tokenArgs:()=>pY,textPathsOf:()=>kE,taskClassOf:()=>U00,swarmOn:()=>C7,settleAttemptClass:()=>yB,scopeDistribution:()=>zK,runView:()=>M9,resolveModelId:()=>lY,resolveLaunch:()=>fB,reportCommand:()=>O00,renderLiveHuman:()=>SE,recordedSpend:()=>mE,realProbe:()=>ZK,realAttemptDeps:()=>EB,predictionAgreement:()=>yE,predictFromTask:()=>cY,openSwarmAt:()=>AE,observe:()=>fE,modelArg:()=>PE,keyFromTask:()=>P9,inertProbe:()=>Y00,finishWithFact:()=>JK,dbPathOf:()=>XK,createReportCommand:()=>pE,createAttemptCommand:()=>lE,classDistribution:()=>C9,caveatArgs:()=>YK,attemptView:()=>D9,attemptFailure:()=>$6,attemptCommand:()=>j00,anchorPathsOf:()=>vB,RECOST_ACTIONS:()=>uE});import{existsSync as CE,statSync as ee}from"fs";import{homedir as $00}from"os";import{join as kB,resolve as A9}from"path";import{Database as X00}from"bun:sqlite";function XK($){if($.globals.db!==void 0)return $.globals.db;let X=A9($.globals.directory??process.cwd()),Z=K$(X);return"dbPath"in Z?Z.dbPath:kB(X,".myc","myc.db")}function AE($,X=Date.now){if(!CE($))return{ok:!1,code:"ws.not_initialized",msg:`workspace not initialized: no ${$}`,exit:7,hint:"myc init"};try{I$()}catch(Y){let z=N5(Y);if(z!==void 0)return z;throw Y}let Z=new X00($);for(let Y of j6)Z.exec(Y);return N9(Z),{db:Z,roster:new L4(Z,X),attribution:new SY(Z,X),close:()=>Z.close()}}function Z00($,X,Z){try{let Y=Bun.spawnSync($,{cwd:X,stdout:"pipe",stderr:"ignore",timeout:Z});if(Y.exitCode!==0)return null;let z=Y.stdout.toString().trim();return z===""?null:z}catch{return null}}function M$($,X,Z){return{ok:!1,code:$,msg:X,exit:2,hint:Z}}function $6($){if($ instanceof F$)return{ok:!1,code:$.code,msg:$.message,exit:$.code==="notfound.model"?3:2,hint:$.code==="notfound.model"?"myc model list --all":void 0};if($ instanceof z$){let X=$.code==="notfound.attempt"?3:$.code==="conflict.finished"?4:2;return{ok:!1,code:$.code,msg:$.message,exit:X}}throw $}function lY($,X){if($.getModel(X)!==void 0)return{ok:!0,modelId:X};let Z=X.toLowerCase(),Y=$.listModels({includeInactive:!0}).filter((z)=>z.model.modelId.toLowerCase().includes(Z)||z.model.family.toLowerCase()===Z).map((z)=>z.model.modelId);if(Y.length===1)return{ok:!0,modelId:Y[0]};if(Y.length===0)return{ok:!1,failure:{ok:!1,code:"notfound.model",msg:`model "${X}" not found in the roster; an outcome cannot be recorded without a roster model`,exit:3,hint:"myc model list --all | myc model add <id> \u2026"}};return{ok:!1,failure:{ok:!1,code:"conflict.model",msg:`"${X}" matches several models: ${Y.join(", ")}`,exit:4,hint:"narrow down the model id"}}}function PE($,X){let Z=f($,"model")??process.env.MYC_MODEL;if(Z===void 0||Z.trim()==="")return{ok:!1,failure:M$("usage.model","no model given: which model ran the task?","--model <id> or the MYC_MODEL environment variable")};return lY(X,Z)}function z00($){let X=process.env[$];if(X===void 0)return;let Z=Number(X);return Number.isInteger(Z)&&Z>=0?Z:void 0}function pY($){let X=(z,J)=>t($,z)??z00(J),Z={},Y=[["tokens-in","MYC_TOKENS_IN","tokensIn"],["tokens-out","MYC_TOKENS_OUT","tokensOut"],["cache-read","MYC_TOKENS_CACHE_READ","tokensCacheRead"],["cache-write","MYC_TOKENS_CACHE_WRITE","tokensCacheWrite"]];for(let[z,J,U]of Y){let K=X(z,J);if(K!==void 0)Z[U]=K}return Z}function ME($){return $.startsWith("~/")?kB($00(),$.slice(2)):$}function RE($){let X=$.code==="transcript.missing"||$.code==="transcript.dir_missing"||$.code==="notfound.session"||$.code==="notfound.task_session"?3:$.code==="conflict.session"?4:$.code==="transcript.unreadable"?1:5;return{ok:!1,code:$.code,msg:$.message,exit:X,hint:$.hint}}function _E($){let X=f($,"from-transcript"),Z=f($,"from-session");if(X!==void 0&&Z!==void 0)return M$("usage.token_source","--from-transcript and --from-session together: usage has exactly one source");if(X===void 0&&Z===void 0)return{tokens:pY($)};let Y=J00.filter((z)=>t($,z)!==void 0);if(Y.length>0)return M$("usage.token_source",`usage given both by a transcript and by flags (${Y.map((z)=>`--${z}`).join(", ")}); there must be exactly one source`);try{let z=X!==void 0?ME(X):F9(Z,A9($.globals.directory??process.cwd())),J=q9(z);return{tokens:{tokensIn:J.tokensIn,tokensOut:J.tokensOut,tokensCacheRead:J.tokensCacheRead,tokensCacheWrite:J.tokensCacheWrite},transcript:J}}catch(z){if(z instanceof e0)return RE(z);throw z}}function YK($){let X=f($,"caveat");if(X===void 0)return[];let Z=X.split(",").map((z)=>z.trim().replace(/-/g,"_")).filter((z)=>z!==""),Y=Z.filter((z)=>!x6.includes(z));if(Y.length>0)return M$("usage.caveat",`unknown caveat: ${Y.join(", ")}; allowed: ${x6.join(", ")}`);return Z}function IE($,X){let Z=X.replace(/^\.\//,"");if(Z===""||Z.startsWith("/")||Z===".."||Z.startsWith("../"))return null;let Y=A$($.attrs).repo??"";if(Y===""||Z===Y||Z.startsWith(`${Y}/`))return Z;return H8(Y,Z)}function vB($,X,Z){let Y=[],z=$.attrs.anchors;if(Array.isArray(z)){for(let U of z)if(U!==null&&typeof U==="object"&&typeof U.path==="string"){let K=IE($,U.path);if(K!==null)Y.push(K)}}let J=X.query(`SELECT a.repo_id AS repo_id, a.path AS path
|
|
3350
3350
|
FROM edges e JOIN anchors a ON a.node_id = e.dst
|
|
3351
3351
|
WHERE e.src = ?1 AND e.type = 'touches' AND e.deleted_at IS NULL`).all(Z);for(let U of J)Y.push(H8(U.repo_id,U.path));return Y}function kE($,X){if(X===void 0)return[];let Z=[];for(let Y of uL(`${$.title}
|
|
3352
|
-
${$.body??""}`)){let z=IE($,Y);if(z===null)continue;try{if(
|
|
3352
|
+
${$.body??""}`)){let z=IE($,Y);if(z===null)continue;try{if(ee(kB(X,z)).isFile())Z.push(z)}catch{}}return Z}function EE($){let X=$.attrs.type;return typeof X==="string"?{type:X}:{}}function P9($,X,Z,Y=null){return dU({title:$.title,...EE($),sources:{touched:Y,anchors:vB($,X,Z)}})}function cY($,X,Z,Y){return dU({title:$.title,...EE($),sources:{anchors:vB($,X,Z),text:kE($,Y)}})}function U00($,X,Z){return P9($,X,Z).taskClass}function K00($,X){try{let Z=$.query("SELECT title, body, attrs FROM nodes WHERE id = ?1").get(X);if(Z===null)return;let Y={};try{let z=JSON.parse(Z.attrs??"{}");if(z!==null&&typeof z==="object"&&!Array.isArray(z))Y=z}catch{}return{title:Z.title,body:Z.body,attrs:Y}}catch{return}}function vE($){return[...new Set($.map((X)=>H8(X.prefix,X.path)))].sort()}function yB($,X,Z,Y,z,J={}){let U={attemptId:Z.attemptId,from:Z.taskClass},K=K00($,Z.taskId);if(K===void 0)return{...U,to:Z.taskClass,scopeSource:Z.classSource==="declared"?"declared":Z.scopeSource??"\u2014",predicted:Z.predictedClass,changed:!1,predictionFilled:!1,skipped:"task not in this database"};let W=Z.predictedClass??cY(K,$,Z.taskId,z).taskClass,V=Z.predictedClass===null;if(Z.classSource==="declared"){if(V&&J.dryRun!==!0)X.fillPrediction(Z.attemptId,W);return{...U,to:Z.taskClass,scopeSource:"declared",predicted:W,changed:!1,predictionFilled:V,skipped:"declared by hand"}}let G=P9(K,$,Z.taskId,Y);if(J.dryRun===!0){let Q=G.taskClass!==Z.taskClass||G.scopeSource!==Z.scopeSource;return{...U,to:G.taskClass,scopeSource:G.scopeSource,predicted:W,changed:Q,predictionFilled:V}}let H=Z.taskClass!==G.taskClass||Z.scopeSource!==G.scopeSource,N=X.settleClass(Z.attemptId,{taskClass:G.taskClass,scopeSource:G.scopeSource,predictedClass:W});return{...U,to:N.record.taskClass,scopeSource:G.scopeSource,predicted:N.record.predictedClass,changed:H,predictionFilled:V}}function yE($){let X=0,Z=0,Y=0;for(let z of $){if(z.predicted===null)continue;let J=z.taskClass.split(":")[1],U=z.predicted.split(":")[1];if(J==="unknown"||U==="unknown")continue;if(X++,J===U)Y++;if(z.taskClass===z.predicted)Z++}return{compared:X,sameClass:Z,sameScope:Y}}function C9($){let X=new Map;for(let Z of $)X.set(Z.taskClass,(X.get(Z.taskClass)??0)+1);return Object.fromEntries([...X.entries()].sort(([Z,Y],[z,J])=>J-Y||(Z<z?-1:Z>z?1:0)))}function zK($){let X=new Map;for(let Z of $){let Y=Z.classSource==="declared"?"declared":Z.scopeSource??"unrecorded";X.set(Y,(X.get(Y)??0)+1)}return Object.fromEntries([...X.entries()].sort(([,Z],[,Y])=>Y-Z))}function O9($,X){let Z=Object.entries(X).map(([Y,z])=>`${Y} ${z}`);return`${$.padEnd(8)} ${Z.length===0?"\u2014":Z.join(" \xB7 ")}`}function D9($){return{attemptId:$.attemptId,taskId:$.taskId,modelId:$.modelId,effort:$.effort,harness:$.harness,actor:$.actor,taskClass:$.taskClass,classSource:$.classSource,scopeSource:$.scopeSource,predictedClass:$.predictedClass,startedAt:new Date($.startedAt).toISOString(),finishedAt:$.finishedAt===null?null:new Date($.finishedAt).toISOString(),wallMs:$.wallMs,verdict:$.verdict,caveats:$.caveats,quality:$.quality,retries:$.retries,tokensIn:$.tokensIn,tokensOut:$.tokensOut,tokensCacheRead:$.tokensCacheRead,tokensCacheWrite:$.tokensCacheWrite,costUsd:$.costUsd,costBasis:$.costBasis,priceValidFrom:$.priceValidFrom===null?null:new Date($.priceValidFrom).toISOString(),source:$.source,note:$.note}}function fB($,X){let Z=uU(X.env()),Y=f($,"session"),z=f($,"dispatch"),J=t($,"pid");if(Z=yY(Z,{...Y!==void 0?{sessionId:Y}:{},...z!==void 0?{dispatchId:z}:{},...J!==void 0?{agentPid:J}:{}}),Z.dispatchId!==null||Z.terminal===null||K0($,"no-orca"))return{launch:Z,lookupFailed:!1};let U=X.dispatchOf(Z.terminal);if(U===null)return{launch:Z,lookupFailed:!0};return{launch:yY(Z,{dispatchId:U.dispatchId,dispatchSource:"lookup",...U.runId!==null?{runId:U.runId}:{}}),lookupFailed:!1}}function M9($){if($===void 0)return null;return{sessionId:$.sessionId,sessionSource:$.sessionSource,transcriptPath:$.transcriptPath,dispatchId:$.dispatchId,dispatchSource:$.dispatchSource,runId:$.runId,terminal:$.terminal,paneKey:$.paneKey,agentPid:$.agentPid,pidSource:$.pidSource,harnessBuild:$.harnessBuild,procState:$.procState,procCheckedAt:$.procCheckedAt===null?null:new Date($.procCheckedAt).toISOString(),procExitedAt:$.procExitedAt===null?null:new Date($.procExitedAt).toISOString(),gitHead:$.gitHead,gitBase:$.gitBase===null?null:$.gitBase.checkouts.map((X)=>({root:X.root,prefix:X.prefix,head:X.head,dirtyAtStart:Object.keys(X.dirty).length})),filesTouched:$.filesTouched,recordedAt:new Date($.recordedAt).toISOString()}}function fE($,X,Z){let Y=uU(X.env()).agentPid;return $.map(({attempt:z,run:J})=>{let U=J===void 0?void 0:{dispatchSource:J.dispatchSource,agentPid:J.agentPid,selfPid:Y},K=cU(z,X.alive(J?.agentPid??null),U);return{attempt:D9(z),run:M9(J),liveState:K,meaning:lU[K],ageMs:Z-z.startedAt,afterFinishMs:z.finishedAt===null||!fY(K)?null:Z-z.finishedAt}})}function qE($){let X=Math.max(0,Math.round($/1000)),Z=Math.floor(X/3600),Y=Math.floor(X%3600/60);return Z>0?`${Z}h ${String(Y).padStart(2,"0")}m`:`${Y}m ${String(X%60).padStart(2,"0")}s`}function SE($){let X=$;if(X.length===0)return`no live processes on record
|
|
3353
3353
|
`;let Z=X.map((z)=>{let J=z.run,U=J?.agentPid,K=J?.sessionId,W=J?.dispatchId;return[String(z.attempt.attemptId).padEnd(16),String(z.attempt.taskId).padEnd(20),`${z.liveState}`.padEnd(8),`pid ${U??"\u2014"}`.padEnd(11),qE(z.ageMs).padEnd(9),z.afterFinishMs===null?"".padEnd(16):`hanging ${qE(z.afterFinishMs)}`.padEnd(16),`session ${K===null||K===void 0?"\u2014":String(K).slice(0,8)}`.padEnd(16),`${W??"\u2014"}`].join(" ").trimEnd()}),Y=X.filter((z)=>z.liveState==="orphan");if(Y.length>0)Z.push("",`ORPHANED ${Y.length}: work accepted, process still alive. worker-release drops the terminal's registration, not the process.`,` kill ${Y.map((z)=>z.run.agentPid).join(" ")}`," (whoever launched it kills it: myc keeps records, not processes)");return`${Z.join(`
|
|
3354
3354
|
`)}
|
|
3355
|
-
`}function uY($){return $===null?"\u2014":`$${$<0.01?$.toFixed(5):$.toFixed(3)}`}function
|
|
3355
|
+
`}function uY($){return $===null?"\u2014":`$${$<0.01?$.toFixed(5):$.toFixed(3)}`}function W00($){let X=$;if(X.length===0)return`no attempts
|
|
3356
3356
|
`;let Z=X.map((z)=>{let{caveats:J,quality:U}=z,K=z.verdict===null?"open":`${z.verdict}${J.length>0?`(${J.join(",")})`:""}`,W=z.wallMs;return[String(z.attemptId).padEnd(16),String(z.taskId).padEnd(20),`${z.modelId}@${z.effort}`.padEnd(30),String(z.taskClass).padEnd(17),K.padEnd(28),(U===null?"q=\u2014":`q=${U.toFixed(2)}`).padEnd(8),uY(z.costUsd).padEnd(9),W===null?"":`${(W/1000).toFixed(1)}s`].join(" ").trimEnd()}),Y=X;return Z.push("",O9("classes",C9(Y)),O9("from",zK(Y))),`${Z.join(`
|
|
3357
3357
|
`)}
|
|
3358
3358
|
`}function gE($,X){if(X===void 0)return $;return{...$,transcript:{path:X.path,sessionId:X.sessionId,responses:X.responses,usageRecords:X.usageRecords,records:X.records,startedAt:X.startedAt,endedAt:X.endedAt,models:X.models}}}function SB($){let X=$,Z=`${X.attemptId} ${X.taskId} ${X.modelId}@${X.effort} (${X.harness})`,Y=X.classSource==="declared"?"declared":`from ${X.scopeSource??"unrecorded"}`,z=X.predictedClass!==null&&X.predictedClass!==void 0&&X.predictedClass!==X.taskClass?` \xB7 predicted ${X.predictedClass}`:"",J=`class ${X.taskClass} (${Y})${z}`;if(X.finishedAt===null)return`${[Z,J,`open started ${X.startedAt}`,...FE(X)].join(`
|
|
3359
3359
|
`)}
|
|
3360
3360
|
`;let U=X.caveats,K=`verdict ${X.verdict}${U.length>0?` \xB7 caveats: ${U.join(", ")}`:""}`,W=`quality ${X.quality.toFixed(2)} cost ${uY(X.costUsd)} (${X.costBasis})`,V=[Z,J,K,W],G=X.transcript;if(G!==void 0)V.push(`usage in ${X.tokensIn} out ${X.tokensOut} \xB7 `+`session ${G.sessionId??"?"}, responses ${G.responses} of ${G.usageRecords} records`);return V.push(...FE(X)),`${V.join(`
|
|
3361
3361
|
`)}
|
|
3362
|
-
`}function FE($){let X=$.run;if(X===null||X===void 0)return[];let Z=[`launch session ${X.sessionId??"\u2014"} (${X.sessionSource}) \xB7 `+`dispatch ${X.dispatchId??"\u2014"} (${X.dispatchSource})`,`process pid ${X.agentPid??"\u2014"} (${X.pidSource}) \xB7 ${X.procState}`+($.liveState===void 0?"":` \xB7 ${$.liveState}: ${$.meaning}`)],Y=X.filesTouched;if(Y!==null&&Y!==void 0){let z=X.gitBase===null||X.gitBase===void 0?" (no start snapshot: not used as fact)":"";Z.push(`touched ${Y.length} ${Y.length===1?"file":"files"}${Y.length>0?`: ${Y.slice(0,3).join(", ")}${Y.length>3?" \u2026":""}`:""}${z}`)}return Z}function
|
|
3363
|
-
`}}}function
|
|
3362
|
+
`}function FE($){let X=$.run;if(X===null||X===void 0)return[];let Z=[`launch session ${X.sessionId??"\u2014"} (${X.sessionSource}) \xB7 `+`dispatch ${X.dispatchId??"\u2014"} (${X.dispatchSource})`,`process pid ${X.agentPid??"\u2014"} (${X.pidSource}) \xB7 ${X.procState}`+($.liveState===void 0?"":` \xB7 ${$.liveState}: ${$.meaning}`)],Y=X.filesTouched;if(Y!==null&&Y!==void 0){let z=X.gitBase===null||X.gitBase===void 0?" (no start snapshot: not used as fact)":"";Z.push(`touched ${Y.length} ${Y.length===1?"file":"files"}${Y.length>0?`: ${Y.slice(0,3).join(", ")}${Y.length>3?" \u2026":""}`:""}${z}`)}return Z}function V00($){return{name:"start",summary:"open an attempt: who takes the task and with what model",help:"The model comes from --model or $MYC_MODEL and must be in the roster. Harness and reasoning effort are inherited from the roster; the task class is derived from the task itself.",flags:[{name:"model",value:"string",description:"roster model id or unambiguous part"},{name:"effort",value:"string",description:`override roster effort: ${f5.join("|")}`},{name:"harness",value:"string",description:`override roster harness: ${o0.join("|")}`},{name:"class",value:"string",description:"override task class, e.g. fix:module"},{name:"note",value:"string",description:"free-form note"},{name:"as",value:"string",description:"actor (default $MYC_ACTOR/$USER)"},...bE,...wE],handler:async(X)=>{let Z=X.args[0];if(Z===void 0)return M$("usage.invalid","task id required: myc attempt start <id>");let Y=f(X,"class");if(Y!==void 0&&!y8(Y))return M$("usage.class",`--class must be intent:scope, got "${Y}"`);let z=await $.store.openStore(X);if(!z.ok)return z.failure;let J=z.handle,U=C7(J.driver.database,$.probe.now);try{let K=R0(J,Z);if(!K.ok)return K.failure;let W=K.node,V=PE(X,U.roster);if(!V.ok)return V.failure;let G=Y===void 0?P9(W,J.driver.database,W.id):void 0,H=cY(W,J.driver.database,W.id,J.wsDir),N=A9(X.globals.directory??process.cwd()),{launch:Q,lookupFailed:L}=fB(X,$.probe),B=await $.probe.gitBase(N,J.wsDir),T=Q.sessionId===null?null:xE(Q.sessionId,N),q=U.attribution.startAttempt({taskId:W.id,modelId:V.modelId,taskClass:Y??G.taskClass,classSource:Y===void 0?"derived":"declared",...G!==void 0?{scopeSource:G.scopeSource}:{},predictedClass:H.taskClass,effort:f(X,"effort"),harness:f(X,"harness"),actor:gH(X),note:f(X,"note"),run:{launch:Q,transcriptPath:T,gitHead:B?.checkouts[0]?.head??null,gitBase:B},...pY(X)});if(Q.sessionId===null)X.warn("launch.no_session",`${q.attemptId}: session not recorded \u2014 usage will have to be found by scanning `+"(myc attempt start \u2026 --session <uuid> or $MYC_SESSION_ID)");if(L)X.warn("launch.no_dispatch",`${q.attemptId}: terminal ${Q.terminal} is known but the dispatch is not \u2014 `+"the orchestrator did not answer (myc attempt start \u2026 --dispatch ctx_\u2026)");return{ok:!0,data:{...D9(q),run:M9(U.attribution.getRun(q.attemptId))}}}catch(K){return $6(K)}finally{J.close()}},renderHuman:SB}}function C7($,X=Date.now){return N9($),{roster:new L4($,X),attribution:new SY($,X)}}function xE($,X){try{return F9($,X)}catch(Z){if(Z instanceof e0)return null;throw Z}}function RB($,X,Z){if($.transcriptPath!==null&&CE($.transcriptPath))return $.transcriptPath;return F9(X,Z)}function _B($,X){return{modelId:X,family:new L4($).getModel(X)?.model.family??""}}function $K($,X,Z,Y){let z=Z.seen.length>0?Z.seen.join(", "):"no model at all";return`${$}: transcript ${X} was written by ${z}, but the attempt ran ${Y.modelId} (family ${Y.family||"unknown"})`}function hE($){return{tokensIn:$.tokensIn,tokensOut:$.tokensOut,tokensCacheRead:$.tokensCacheRead,tokensCacheWrite:$.tokensCacheWrite}}function mE($,X,Z,Y){let z=X.attribution.getAttempt(Z);if(Y.transcript!==void 0){if(z!==void 0){let K=_B(X.db,z.modelId),W=j9(Y.transcript.models,K);if(!W.ok)$.warn("spend.model_mismatch",`${$K(Z,Y.transcript.path,W,K)}; taken anyway because the transcript was named explicitly`)}return{...Y,via:"transcript"}}if(Object.keys(Y.tokens).length>0)return{...Y,via:"flags"};let J=X.attribution.getRun(Z),U=pU(J);if(!U.confirmed){if(U.reason==="no_session")return{...Y,via:"none"};return $.warn("spend.not_executor",`${Z}: usage not taken \u2014 recorded session ${U.sessionId} is not confirmed as the executor's: attempt start ran without an orchestrator dispatch, as when the coordinator records the attempt from its own session (add the executor's usage: myc attempt recost ${Z} --from-session <executor session uuid> --apply)`),{...Y,via:"none"}}try{let K=RB(J,U.sessionId,A9($.globals.directory??process.cwd())),W=X.attribution.previousAttemptEnd(U.sessionId,Z),V=q9(K,W===void 0?{}:{since:W}),G=_B(X.db,z?.modelId??""),H=j9(V.models,G);if(!H.ok)return $.warn("spend.model_mismatch",`${$K(Z,K,H,G)} \u2014 usage not taken `+`(myc attempt recost ${Z} --from-session <uuid> --apply)`),{...Y,via:"none"};let N=hE(V);if(V.outsideWindow>0&&Object.values(N).every((Q)=>Q===0))return $.warn("spend.outside_window",`${Z}: usage not taken \u2014 all ${V.outsideWindow} records of ${K} are outside the attempt window (the previous attempt of this session ended ${new Date(W).toISOString()}); if the executor began before the attempt was recorded, name the transcript: myc attempt recost ${Z} --from-session ${U.sessionId} --apply`),{...Y,via:"none"};return{tokens:N,transcript:V,via:"recorded"}}catch(K){let W=K instanceof e0?K.code:"transcript.unreadable";return $.warn(W,`usage of recorded session ${U.sessionId} not read: ${K.message}`),{...Y,via:"none"}}}async function JK($,X,Z,Y,z,J,U){let K=mE($,X,Y,z),W=X.attribution.finishAttempt(Y,{verdict:J.verdict,caveats:J.caveats,retries:J.retries,note:J.note,...K.tokens}),V=X.attribution.getRun(Y),G=null;if(V?.gitBase!=null){let N=await Z.touchedSince(V.gitBase);if(N===null)$.warn("attempt.touched_unknown",`${Y}: files touched not measured \u2014 the checkout recorded at start `+`(${V.gitBase.checkouts[0]?.root??"?"}) is gone or git did not answer; the class falls back to anchors, then to paths named in the task`);else G=vE(N),X.attribution.recordFilesTouched(Y,G)}let H;try{H=yB(X.db,X.attribution,W,G,U)}catch(N){let Q=N instanceof Error?N.message:String(N);$.warn("attempt.class_not_settled",`${Y}: class kept as at start \u2014 ${Q}`),H={skipped:Q}}return{record:X.attribution.getAttempt(Y)??W,spend:K,settled:H}}function G00($){return{name:"finish",summary:"record the outcome of an attempt",help:"Usage comes from the session transcript (--from-transcript/--from-session) or "+"from manual flags \u2014 one or the other, not both. The transcript is a foreign format: "+"any mismatch with the expected shape is a refusal, not zero usage.",flags:[{name:"task",value:"string",description:"finish the open attempt of this task"},{name:"verdict",value:"string",description:w6.join("|")},{name:"caveat",value:"string",list:!0,description:`comma-separated: ${x6.join(", ")}`},{name:"retries",value:"number",description:"rework rounds before acceptance"},{name:"note",value:"string",description:"free-form note"},...DE,...wE],handler:async(X)=>{let Z=f(X,"verdict");if(Z===void 0)return M$("usage.verdict",`--verdict required: ${w6.join("|")}`);let Y=YK(X);if(!Array.isArray(Y))return Y;let z=_E(X);if(!("tokens"in z))return z;let J=$.openSwarm(X,$.probe.now);if(!("db"in J))return J;try{let U=X.args[0],K=f(X,"task");if(U===void 0){if(K===void 0)return M$("usage.invalid","attempt id or --task <id> required: myc attempt finish <attempt-id> --verdict \u2026");let V=J.attribution.openAttemptForTask(K);if(V===void 0)return{ok:!1,code:"notfound.attempt",msg:`task "${K}" has no open attempt`,exit:3,hint:`myc attempt start ${K} --model <id>`};U=V.attemptId}let W=await JK(X,J,$.probe,U,z,{verdict:Z,caveats:Y,retries:t(X,"retries"),note:f(X,"note")},V7(XK(X)));return{ok:!0,data:{...gE(D9(W.record),W.spend.transcript),run:M9(J.attribution.getRun(U)),spendVia:W.spend.via,classSettled:W.settled}}}catch(U){return $6(U)}finally{J.close()}},renderHuman:SB}}function H00($){return{name:"link",summary:"attach session / dispatch / pid to an existing attempt",help:"Fallback path: normally the link is written at `attempt start`. --found marks "+"the source as 'search' \u2014 found by scanning transcripts, not recorded by the process itself.",flags:[{name:"task",value:"string",description:"link the open attempt of this task"},{name:"found",description:"mark the session as found by search, not recorded"},{name:"transcript",value:"string",description:"exact transcript file"},...bE],handler:(X)=>{let Z=$.openSwarm(X,$.probe.now);if(!("db"in Z))return Z;try{let Y=X.args[0],z=f(X,"task");if(Y===void 0){if(z===void 0)return M$("usage.invalid","attempt id or --task <id> required: myc attempt link <attempt-id> --session <uuid>");let N=Z.attribution.openAttemptForTask(z);if(N===void 0)return{ok:!1,code:"notfound.attempt",msg:`task "${z}" has no open attempt`,exit:3};Y=N.attemptId}let J=Z.attribution.getRun(Y),{launch:U}=fB(X,$.probe),K=yY(U,{...U.sessionId===null&&J?.sessionId!=null?{sessionId:J.sessionId,sessionSource:J.sessionSource}:{},...U.dispatchId===null&&J?.dispatchId!=null?{dispatchId:J.dispatchId,dispatchSource:J.dispatchSource}:{},...U.agentPid===null&&J?.agentPid!=null?{agentPid:J.agentPid}:{}}),W=K0(X,"found"),V=K.sessionId===(J?.sessionId??null),G=f(X,"transcript")??(V?J?.transcriptPath??null:K.sessionId===null?null:xE(K.sessionId,A9(X.globals.directory??process.cwd()))),H=Z.attribution.attachRun(Y,{launch:W&&K.sessionId!==null?{...K,sessionSource:"search"}:K,transcriptPath:G,gitHead:J?.gitHead??null,gitBase:J?.gitBase??null,procState:J?.procState});return{ok:!0,data:{attemptId:Y,run:M9(H)}}}catch(Y){return $6(Y)}finally{Z.close()}},renderHuman:(X)=>{let Z=X,Y=Z.run;return`${Z.attemptId} session ${Y?.sessionId??"\u2014"} (${Y?.sessionSource??"\u2014"}) \xB7 `+`dispatch ${Y?.dispatchId??"\u2014"} \xB7 pid ${Y?.agentPid??"\u2014"}
|
|
3363
|
+
`}}}function Q00($){return{name:"list",summary:"recorded attempts, newest first",help:"--live answers 'what is running now and for how long': it probes the recorded pids with signal 0 and shows LIVE processes, telling working ones from those whose work is already accepted. Killing them is not its job: myc keeps records.",flags:[{name:"task",value:"string",description:"filter by task id"},{name:"model",value:"string",description:"filter by model id"},{name:"open",description:"only unfinished attempts"},{name:"live",description:"only attempts whose recorded pid is still alive"},{name:"since",value:"string",description:"window, e.g. 7d"},{name:"limit",value:"number",description:"max rows (default 50)"}],handler:(X)=>{let Z=$.openSwarm(X,$.probe.now);if(!("db"in Z))return Z;try{let Y,z=f(X,"since");if(z!==void 0){let G=P$(z);if(G===void 0)return M$("usage.invalid",`invalid --since "${z}"; format: 30m, 2h, 1d`);Y=Date.now()-G}let J={taskId:f(X,"task"),modelId:f(X,"model"),open:K0(X,"open"),since:Y,limit:t(X,"limit")??50};if(!K0(X,"live")){let G=Z.attribution.listAttempts(J);return{ok:!0,data:G.map(D9),meta:{count:G.length,classes:C9(G),classFrom:zK(G)}}}let U=$.probe.now(),K=fE(Z.attribution.listWithRuns({...J,withRun:!0}),$.probe,U);for(let G of K){let H=String(G.attempt.attemptId),N=G.run?.procState;if(fY(G.liveState)){if(N==="running")Z.attribution.markSeen(H,U)}else if(G.liveState!=="unknown"&&N!=="exited")Z.attribution.markExited(H,U)}let W=K.filter((G)=>fY(G.liveState)),V=W.filter((G)=>G.liveState==="orphan").length;return{ok:!0,data:W,meta:{count:W.length,orphans:V,scanned:K.length}}}catch(Y){return $6(Y)}finally{Z.close()}},renderHuman:(X,Z)=>K0(Z,"live")?SE(X):W00(X)}}function N00($){return{name:"show",summary:"one attempt in full",handler:(X)=>{let Z=X.args[0];if(Z===void 0)return M$("usage.invalid","attempt id required: myc attempt show <attempt-id>");let Y=$.openSwarm(X,$.probe.now);if(!("db"in Y))return Y;try{let z=Y.attribution.getAttempt(Z);if(z===void 0)return{ok:!1,code:"notfound.attempt",msg:`attempt "${Z}" not found`,exit:3};let J=Y.attribution.getRun(Z),U=cU(z,$.probe.alive(J?.agentPid??null));return{ok:!0,data:{...D9(z),run:M9(J),liveState:U,meaning:lU[U]}}}catch(z){return $6(z)}finally{Y.close()}},renderHuman:SB}}function L00($){return{name:"reclass",summary:"recompute the task class of recorded attempts from the best source",help:"The key (task_class) comes from files touched during the attempt (only when measured by the start snapshot), else from task anchors, else it stays unknown. The prediction (predicted_class: anchors, else file paths named in the task) is filled only where it is missing. Verdicts, caveats, tokens and frozen cost stay as they are; a class declared with --class is kept.",flags:[{name:"task",value:"string",description:"only attempts of this task"},{name:"dry-run",description:"show what would change, write nothing"}],handler:(X)=>{let Z=$.openSwarm(X,$.probe.now);if(!("db"in Z))return Z;try{let Y=K0(X,"dry-run"),z=V7(XK(X)),J=Z.attribution.listWithRuns({...f(X,"task")!==void 0?{taskId:f(X,"task")}:{},limit:Number.MAX_SAFE_INTEGER}),U=J.map((V)=>V.attempt),K=J.map(({attempt:V,run:G})=>yB(Z.db,Z.attribution,V,G?.gitBase!=null?G.filesTouched??null:null,z,{dryRun:Y})),W=J.map(({attempt:V},G)=>({taskClass:K[G].to,classSource:V.classSource,scopeSource:K[G].skipped===void 0?K[G].scopeSource:V.scopeSource,predicted:K[G].predicted}));return{ok:!0,data:{dryRun:Y,scanned:J.length,changed:K.filter((V)=>V.changed).length,predictionsFilled:K.filter((V)=>V.predictionFilled).length,declared:J.filter((V)=>V.attempt.classSource==="declared").length,skipped:K.filter((V)=>V.skipped!==void 0&&V.skipped!=="declared by hand").length,before:C9(U),after:C9(W),classFrom:zK(W),predicted:C9(W.flatMap((V)=>V.predicted===null?[]:[{taskClass:V.predicted}])),agreement:yE(W),changes:K.filter((V)=>V.changed)}}}catch(Y){return $6(Y)}finally{Z.close()}},renderHuman:(X)=>{let Z=X,Y=Z.changes.map((J)=>`${J.attemptId.padEnd(16)} ${J.from.padEnd(17)} \u2192 ${J.to.padEnd(17)} (${J.scopeSource})`);if(Y.length>0)Y.push("");let z=Z.dryRun?"would change":"changed";return Y.push(`${z} ${Z.changed} of ${Z.scanned} \xB7 predictions ${Z.dryRun?"to fill":"filled"} ${Z.predictionsFilled} \xB7 declared by hand ${Z.declared} (key kept)`+(Z.skipped>0?` \xB7 task not found ${Z.skipped}`:""),O9("before",Z.before),O9("after",Z.after),O9("from",Z.classFrom),O9("predict",Z.predicted),`agree scope ${Z.agreement.sameScope} of ${Z.agreement.compared}, class ${Z.agreement.sameClass} of ${Z.agreement.compared} (prediction vs key, both scopes known)`),`${Y.join(`
|
|
3364
3364
|
`)}
|
|
3365
|
-
`}}}function IB($){return{tokensIn:$.tokensIn,tokensOut:$.tokensOut,tokensCacheRead:$.tokensCacheRead,tokensCacheWrite:$.tokensCacheWrite,costUsd:$.costUsd,costBasis:$.costBasis}}function jE($,X){return $.tokensIn===X.tokensIn&&$.tokensOut===X.tokensOut&&$.tokensCacheRead===X.tokensCacheRead&&$.tokensCacheWrite===X.tokensCacheWrite}function MB($,X,Z){if(!($ instanceof e0))throw $;return{action:"refused",code:$.code,reason:`${X}: ${$.message}`,sessionId:Z,transcript:null}}function
|
|
3365
|
+
`}}}function IB($){return{tokensIn:$.tokensIn,tokensOut:$.tokensOut,tokensCacheRead:$.tokensCacheRead,tokensCacheWrite:$.tokensCacheWrite,costUsd:$.costUsd,costBasis:$.costBasis}}function jE($,X){return $.tokensIn===X.tokensIn&&$.tokensOut===X.tokensOut&&$.tokensCacheRead===X.tokensCacheRead&&$.tokensCacheWrite===X.tokensCacheWrite}function MB($,X,Z){if(!($ instanceof e0))throw $;return{action:"refused",code:$.code,reason:`${X}: ${$.message}`,sessionId:Z,transcript:null}}function B00($,X,Z,Y,z,J){let U=X.finishedAt??void 0,K=_B($.db,X.modelId),W=(Q,L,B)=>{let T=hE(Q),q=jE(X,T);return{action:q?"unchanged":"recost",reason:q?`${B}: recorded usage matches`:`${B}: usage differs from the recorded one`,tokens:T,sessionId:L,transcript:Q.path}};if(z!==void 0){let Q;try{let B=z.file!==void 0?ME(z.file):F9(z.session,Y);Q=q9(B,{...U!==void 0?{until:U}:{}})}catch(B){return MB(B,"named transcript not read",z.session??null)}let L=j9(Q.models,K);if(!L.ok)J("spend.model_mismatch",`${$K(X.attemptId,Q.path,L,K)}; taken anyway because the transcript was named explicitly`);return W(Q,Q.sessionId,"named transcript")}let V=pU(Z);if(!V.confirmed&&V.reason==="no_session")return{action:"skipped",code:null,reason:"no session recorded: the usage came from flags or nowhere, there is nothing to recompute",sessionId:null,transcript:null};if(!V.confirmed){if(jE(X,OE))return{action:"skipped",code:null,reason:`no usage recorded, and session ${V.sessionId} is not confirmed as the executor's `+"\u2014 nothing to drop (--from-session <uuid> adds the executor's usage)",sessionId:V.sessionId,transcript:null};let Q;try{Q=RB(Z,V.sessionId,Y)}catch(B){return MB(B,"cannot tell whose usage is recorded",V.sessionId)}let L=PB(Q,IB(X));if(L===null)return{action:"skipped",code:null,reason:`recorded usage does not come from session ${V.sessionId} (flags or a named transcript): kept as recorded`,sessionId:V.sessionId,transcript:Q};return{action:"foreign",reason:`recorded usage is session ${V.sessionId}'s (its transcript up to ${L.at??"the start"}), which is not confirmed as the executor's (no orchestrator dispatch); the executor's transcript `+"is unknown \u2014 --clear-foreign drops it, --from-session <uuid> replaces it",tokens:OE,sessionId:V.sessionId,transcript:Q}}let G,H;try{G=RB(Z,V.sessionId,Y);let Q=$.attribution.previousAttemptEnd(V.sessionId,X.attemptId);H=q9(G,{...U!==void 0?{until:U}:{},...Q===void 0?{}:{since:Q}})}catch(Q){return MB(Q,"executor transcript not found",V.sessionId)}let N=j9(H.models,K);if(!N.ok)return{action:"refused",code:"spend.model_mismatch",reason:$K(X.attemptId,G,N,K),sessionId:V.sessionId,transcript:G};return W(H,V.sessionId,`executor session (${V.by})`)}function T00($){return{name:"recost",summary:"recompute the usage of finished attempts from the executor's transcript",help:"Dry run by default: shows what would change and writes nothing; --apply writes. Usage is taken by the same rules as at finish: only from a session confirmed as the executor's (an orchestrator dispatch, or a session linked explicitly), only when the transcript models belong to the attempt's model, and the transcript is cut at the moment the attempt finished. The price stays the one valid at the attempt's start. An executor transcript that cannot be found is a refusal, not zero. Usage proven to be another session's is dropped only with --clear-foreign.",flags:[{name:"task",value:"string",description:"only finished attempts of this task"},{name:"apply",description:"write the changes (default: dry run)"},{name:"clear-foreign",description:"with --apply: drop usage proven to be a non-executor session's"},...DE],handler:(X)=>{let Z=f(X,"from-transcript"),Y=f(X,"from-session"),z=X.args[0];if(Z!==void 0&&Y!==void 0)return M$("usage.token_source","--from-transcript and --from-session together: usage has exactly one source");let J=Z!==void 0||Y!==void 0?{...Z!==void 0?{file:Z}:{},...Y!==void 0?{session:Y}:{}}:void 0;if(J!==void 0&&z===void 0)return M$("usage.invalid","--from-transcript/--from-session name ONE attempt's usage: myc attempt recost <attempt-id> --from-session <uuid>");let U=K0(X,"apply"),K=K0(X,"clear-foreign");if(K&&!U)return M$("usage.invalid","--clear-foreign writes: use it together with --apply");let W=$.openSwarm(X,$.probe.now);if(!("db"in W))return W;try{let V=A9(X.globals.directory??process.cwd()),G;if(z!==void 0){let L=W.attribution.getAttempt(z);if(L===void 0)return{ok:!1,code:"notfound.attempt",msg:`attempt "${z}" not found`,exit:3};if(L.finishedAt===null)return M$("usage.invalid",`attempt "${z}" is still open: its usage is taken at finish (myc attempt finish ${z} --verdict \u2026)`);G=[{attempt:L,run:W.attribution.getRun(z)}]}else{let L=f(X,"task");G=W.attribution.listWithRuns({...L!==void 0?{taskId:L}:{},limit:Number.MAX_SAFE_INTEGER}).filter((B)=>B.attempt.finishedAt!==null)}let H=G.map(({attempt:L,run:B})=>{let T=B00(W,L,B,V,J,X.warn),q={attemptId:L.attemptId,taskId:L.taskId,modelId:L.modelId,action:T.action,reason:T.reason,sessionId:T.sessionId,transcript:T.transcript,before:IB(L)};if(!("tokens"in T))return{...q,code:T.code,after:null,written:!1};let j=U&&(T.action==="recost"||T.action==="foreign"&&K),{after:O}=W.attribution.recostAttempt(L.attemptId,T.tokens,j);return{...q,code:null,after:T.action==="unchanged"?null:IB(O),written:j}}),N=H.filter((L)=>L.action==="refused");if(z!==void 0&&N.length===1){let L=N[0];return{ok:!1,code:L.code??"recost.refused",msg:`${L.attemptId}: ${L.reason}`,exit:L.code==="notfound.session"||L.code==="transcript.missing"||L.code==="transcript.dir_missing"?3:5,hint:`myc attempt recost ${L.attemptId} --from-session <executor session uuid>`}}if(N.length>0)X.warn("recost.refused",`${N.length} attempt(s) not recomputed \u2014 executor transcript not found or of another model: `+`${N.map((L)=>L.attemptId).join(", ")} (myc attempt recost <attempt-id> --from-session <uuid>)`);let Q=Object.fromEntries(uE.map((L)=>[L,H.filter((B)=>B.action===L).length]));return{ok:!0,data:{applied:U,clearForeign:K,rows:H},meta:{...Q,written:H.filter((L)=>L.written).length}}}catch(V){return $6(V)}finally{W.close()}},renderHuman:(X)=>{let Z=X;if(Z.rows.length===0)return`no finished attempts
|
|
3366
3366
|
`;let Y=Z.rows.map((U)=>{let K=U.after===null?"":` \u2192 ${uY(U.after.costUsd)}`;return[U.attemptId.padEnd(16),U.modelId.padEnd(12),U.action.padEnd(9),`${uY(U.before.costUsd)}${K}`.padEnd(22),`${U.written?"written \xB7 ":""}${U.reason}`].join(" ")}),z=(U)=>Z.rows.filter((K)=>K.action===U).length,J=Z.rows.filter((U)=>U.written).length;if(Y.push("",`recost ${z("recost")} \xB7 unchanged ${z("unchanged")} \xB7 foreign ${z("foreign")} \xB7 `+`refused ${z("refused")} \xB7 skipped ${z("skipped")} \xB7 written ${J}`),!Z.applied)Y.push("dry run: nothing written \u2014 --apply writes, --apply --clear-foreign also drops foreign usage");return`${Y.join(`
|
|
3367
3367
|
`)}
|
|
3368
|
-
`}}}function lE($=EB){return{name:"attempt",summary:"execution attribution: who ran the task, with what, to what result",subcommands:[
|
|
3368
|
+
`}}}function lE($=EB){return{name:"attempt",summary:"execution attribution: who ran the task, with what, to what result",subcommands:[V00($),G00($),H00($),Q00($),N00($),L00($),T00($)]}}function q00($){let X=[`${$.taskClass}`];for(let Z of $.arms){let Y=$.cheapest===Z.arm?"\u2192":$.equalGroup.includes(Z.arm)?"=":" ";X.push(` ${Y} ${Z.arm.padEnd(34)} n=${String(Z.attempts).padStart(3)} q=${Z.qualityMean.toFixed(2)} [${Z.quality.lo.toFixed(2)}\u2013${Z.quality.hi.toFixed(2)}] cost=${uY(Z.costUsdMean)}/attempt (${Z.costedAttempts}/${Z.attempts}) clean ${Math.round(Z.cleanRate*100)}%`)}return X.push(` ${$.answer}${$.separationPending?" (not separated yet)":""}: ${$.why}`),X}function F00($){let X=$,Z=[];if(X.classes.length===0)Z.push("no attribution: not a single closed attempt");for(let Y of X.classes)Z.push(...q00(Y));if(Z.push(`coverage tasks closed ${X.tasksClosed}, attributed ${X.tasksAttributed}; attempts ${X.coverage.attempts} (closed ${X.coverage.finished}, with cost ${X.coverage.withCost})`),X.coverage.costStale>0)Z.push(`WARNING ${X.coverage.costStale} of ${X.coverage.withCost} attempts are frozen at a figure their own price row no longer gives (the price was corrected after freezing): `+"recompute \u2014 bun run scripts/recost-attempts.ts --apply");if(X.coverage.costCacheUnpriced>0)Z.push(`WARNING ${X.coverage.costCacheUnpriced} of ${X.coverage.withCost} attempts were costed at a ZERO cache price despite nonzero cache tokens: the cost is understated, and unevenly. Set the rates: myc model update <id> --price-cache-read/--price-cache-write`);return Z.push(`formula outcome v${X.outcomeVersion}, interval ${Math.round(X.credibleMass*100)}%, observation threshold ${X.minAttempts}`),`${Z.join(`
|
|
3369
3369
|
`)}
|
|
3370
3370
|
`}function pE($=EB){return{name:"report",summary:"swarm reports over recorded attribution",subcommands:[{name:"models",summary:"which model is cheaper at equal result, per task class",help:"'Equal result' means overlapping quality credible intervals, not equal means. Cost is taken as frozen at the time of the attempt.",flags:[{name:"class",value:"string",description:"one task class, e.g. fix:module"},{name:"since",value:"string",description:"window, e.g. 30d"},{name:"min",value:"number",description:"min attempts per arm (default 3)"}],handler:(Z)=>{let Y=f(Z,"class");if(Y!==void 0&&!y8(Y))return M$("usage.class",`--class must be intent:scope, got "${Y}"`);let z=$.openSwarm(Z,$.probe.now);if(!("db"in z))return z;try{let J,U=f(Z,"since");if(U!==void 0){let H=P$(U);if(H===void 0)return M$("usage.invalid",`invalid --since "${U}"; format: 30m, 2h, 1d`);J=Date.now()-H}let K=gY(z.db,{taskClass:Y,since:J,minAttempts:t(Z,"min")}),W=z.db.query(`SELECT count(*) AS n FROM nodes
|
|
3371
|
-
WHERE kind = 'task' AND status = 'closed' AND deleted_at IS NULL`).get(),V=z.db.query("SELECT count(DISTINCT task_id) AS n FROM swarm_attempt WHERE finished_at IS NOT NULL").get();return{ok:!0,data:{...K,tasksClosed:W?.n??0,tasksAttributed:V.n},meta:{classes:K.classes.length}}}catch(J){return $6(J)}finally{z.close()}},renderHuman:
|
|
3371
|
+
WHERE kind = 'task' AND status = 'closed' AND deleted_at IS NULL`).get(),V=z.db.query("SELECT count(DISTINCT task_id) AS n FROM swarm_attempt WHERE finished_at IS NOT NULL").get();return{ok:!0,data:{...K,tasksClosed:W?.n??0,tasksAttributed:V.n},meta:{classes:K.classes.length}}}catch(J){return $6(J)}finally{z.close()}},renderHuman:F00}]}}var ZK,EB,Y00,DE,J00,bE,wE,uE,OE,j00,O00;var UK=v(()=>{o();n0();B4();V0();j0();k6();R8();ZK={env:()=>process.env,alive:($)=>hL($),dispatchOf:($)=>{let X=Z00(["orca","orchestration","worker-list","--json"],process.cwd(),5000);if(X===null)return null;try{let Y=(JSON.parse(X).result?.workers??[]).find((U)=>U.agentTerminalHandle===$);if(Y===void 0)return null;let z=Y.dispatchId;if(typeof z!=="string")return null;let J=Y.runId;return{dispatchId:z,runId:typeof J==="string"?J:null}}catch{return null}},gitBase:($,X)=>cL($,X),touchedSince:($)=>iL($),now:()=>Date.now()},EB={openSwarm:($,X)=>AE(XK($),X),store:$0,probe:ZK},Y00={env:()=>({}),alive:()=>null,dispatchOf:()=>null,gitBase:async()=>null,touchedSince:async()=>null,now:()=>Date.now()};DE=[{name:"from-transcript",value:"string",description:"read token spend from a session transcript file"},{name:"from-session",value:"string",description:"same, by session uuid in ~/.claude/projects/<project>"}],J00=["tokens-in","tokens-out","cache-read","cache-write"];bE=[{name:"session",value:"string",description:"session/transcript uuid (default $CLAUDE_CODE_SESSION_ID)"},{name:"dispatch",value:"string",description:"orchestrator dispatch id (ctx_\u2026)"},{name:"pid",value:"number",description:"agent process pid (default $CLAUDE_PID)"},{name:"no-orca",description:"do not ask the orchestrator for the dispatch id"}],wE=[{name:"tokens-in",value:"number",description:"input tokens spent ($MYC_TOKENS_IN)"},{name:"tokens-out",value:"number",description:"output tokens spent ($MYC_TOKENS_OUT)"},{name:"cache-read",value:"number",description:"cache-read tokens"},{name:"cache-write",value:"number",description:"cache-write tokens"}];uE=["recost","unchanged","foreign","refused","skipped"];OE={tokensIn:0,tokensOut:0,tokensCacheRead:0,tokensCacheWrite:0};j00=lE(),O00=pE()});var X6={};s(X6,{nodeType:()=>m6,createUpdateCommand:()=>v00,createTaskCommand:()=>P00,createReleaseCommand:()=>S00,createMsgCommand:()=>R00,createEpicCommand:()=>M00,createCreateCommand:()=>A00,createCommentCommand:()=>I00,createCloseCommand:()=>x00,createClaimCommand:()=>g00,createBugCommand:()=>D00});function m6($){if($.kind==="task"){let X=$.attrs.type;if(typeof X==="string"&&X.length>0)return X}return $.kind}function J0($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function iY($){if($===void 0)return[];return $.split(",").map((X)=>X.trim()).filter((X)=>X.length>0)}function S8($){return Math.round(performance.now()-$)}function C00($){let X=$,Z=[X.id,X.type];if(X.kind==="task")Z.push(g0(X.priority));Z.push(X.status),Z.push(X.blocked_by.length>0?`blocked-by ${X.blocked_by.join(", ")}`:"free");let Y=[Z.join(" ")];for(let z of X.anchors)Y.push(z9(z));if(X.repo===null)Y.push(`repo undetermined \u2014 ${X.repo_reason}`);else if(X.repo.length>0)Y.push(`repo ${X.repo}`);if(X.body_stdin_chars!==void 0)Y.push(`body ${X.body_stdin_chars} chars from stdin`);return Y.push(`${X.took_ms} ms`),`${Y.join(`
|
|
3372
3372
|
`)}
|
|
3373
|
-
`}function nY($,X,Z,Y){let z=Z===void 0?cE:cE.filter((J)=>J.name!=="kind");return{name:$,summary:X,flags:z,remote:!0,help:"Create a node. Title is the positional argument; body via -b or stdin (-b -). CLI kinds map onto core kinds: bug/epic are tasks with attrs.type, memory/decision are notes.",handler:async(J)=>{let U=performance.now(),K=J.args.join(" ").trim();if(K.length===0)return J0("usage.invalid","title required: myc create <title>",2);let W=Z;if(W===void 0){let A=f(J,"kind")??"task";if(W=R9[A],W===void 0)return J0("usage.invalid",`unknown --kind '${A}'; allowed: ${Object.keys(R9).join(", ")}`,2)}let V,G=f(J,"priority");if(G!==void 0){if(V=L7(G),V===void 0)return J0("usage.invalid",`invalid priority '${G}'; allowed: P0..P3 or 0..3`,2)}else if(W.defaultPriority!==void 0)V=W.defaultPriority;let H,N=f(J,"body");if(N==="-")H=await new Response(Bun.stdin.stream()).text();else if(N!==void 0)H=N;let Q,L=f(J,"estimate");if(L!==void 0){let A=P$(L);if(A===void 0)return J0("usage.invalid",`invalid estimate '${L}'; format: 30m, 2h, 1d`,2);Q=Math.round(A/60000)}let B,T=f(J,"anchor");if(T!==void 0){if(B=E8(T),B===void 0||B.path.length===0)return J0("usage.invalid",`invalid anchor '${T}'; format: file[:a-b]`,2)}let q=await $8(J,async(A)=>{let R=[B!==void 0?"--anchor":"",f(J,"parent")!==void 0?"--parent":"",iY(f(J,"dep")).length>0?"--dep":"",f(J,"reply-to")!==void 0?"--reply-to":"",f(J,"as")!==void 0?"--as":""].filter((k)=>k!=="");if(R.length>0)return J0("precond.no_remote",`the server does not accept ${R.join(", ")} yet`,5);let D=iY(f(J,"tag")),F=f(J,"repo"),P=await A.createNode({kind:W.kind,title:K,...H===void 0?{}:{body:H},...V===void 0?{}:{priority:V},...f(J,"assign")!==void 0?{assignee:f(J,"assign")}:{},...f(J,"acl")!==void 0?{acl:f(J,"acl")}:{},...W.type!==void 0||D.length>0||Q!==void 0||F!==void 0?{attrs:{...W.type===void 0?{}:{type:W.type},...D.length>0?{tags:D}:{},...Q===void 0?{}:{estimate_min:Q},...F===void 0?{}:{[qX]:F.trim()}}}:{}}),_=P.data,M=_.attrs??{},E=typeof M.type==="string"?M.type:W.kind;return{ok:!0,data:{id:String(_.id??""),kind:String(_.kind??W.kind),type:E,title:String(_.title??K),status:String(_.status??"open"),priority:Number(_.priority??V??2),blocked_by:[],anchors:[],...F===void 0?{repo:null,repo_reason:"the server does not determine repository scope"}:{repo:F.trim(),repo_reason:""},...N==="-"?{body_stdin_chars:H.length}:{},took_ms:S8(U)},meta:{...P.meta,remote:A.ws}}});if(q!==void 0)return q;let j=await Y.openStore(J);if(!j.ok)return j.failure;let O=j.handle;try{if(B!==void 0){let y=await qY(O,B,J.globals.directory??process.cwd());if(y!==void 0)return y}let A={};if(W.type!==void 0)A.type=W.type;let R=f(J,"repo");if(R!==void 0)A[qX]=R.trim();let D=iY(f(J,"tag"));if(D.length>0)A.tags=D;if(Q!==void 0)A.estimate_min=Q;let F;try{F=O.store.createNode({kind:W.kind,scope:O.scope,title:K,...H!==void 0?{body:H}:{},...V!==void 0?{priority:V}:{},...f(J,"assign")!==void 0?{assignee:f(J,"assign")}:{},...f(J,"acl")!==void 0?{acl:f(J,"acl")}:{},actor:O.actor,attrs:A})}catch(y){return C0(y)}let P=B===void 0?[]:[await jY(O,F.id,B,J.globals.directory??process.cwd(),(y,g)=>J.warn(y,g))],_=[];for(let y of iY(f(J,"dep"))){let g=R0(O,y);if(!g.ok)return g.failure;try{O.store.addEdge(g.node.id,"blocks",F.id)}catch(S){return C0(S)}_.push(g.node.id)}let M,E=f(J,"reply-to");if(E!==void 0){let y=R0(O,E);if(!y.ok)return y.failure;try{O.store.addEdge(F.id,"replies_to",y.node.id)}catch(g){return C0(g)}if(M=y.node.id,W.kind==="message"&&y.node.kind!=="message"&&y.node.kind!=="session")J.warn("comment.kind_wrong",`reply to ${y.node.kind} written as kind='message' \u2014 that is layer L0, raw session `+`dialogue: by design its body moves to bodies_cold after 14 days, and L0 never reaches the vector index. A comment is \`myc comment ${y.node.id} <text>\`: kind=note, attrs.type='comment' (S64)`)}let b=f(J,"parent");if(b!==void 0){let y=R0(O,b);if(!y.ok)return y.failure;try{O.store.addEdge(F.id,"parent",y.node.id)}catch(g){return C0(g)}}let k={id:F.id,...M!==void 0?{replies_to:M}:{},kind:F.kind,type:W.type??F.kind,title:F.title,status:F.status,priority:F.priority,blocked_by:_,anchors:P,repo:A$(F.attrs).by==="absent"?null:A$(F.attrs).repo,repo_reason:c4(O.repo),...N==="-"?{body_stdin_chars:H.length}:{},took_ms:S8(U)};return{ok:!0,data:k,meta:{took_ms:k.took_ms}}}finally{O.close()}},renderHuman:
|
|
3373
|
+
`}function nY($,X,Z,Y){let z=Z===void 0?cE:cE.filter((J)=>J.name!=="kind");return{name:$,summary:X,flags:z,remote:!0,help:"Create a node. Title is the positional argument; body via -b or stdin (-b -). CLI kinds map onto core kinds: bug/epic are tasks with attrs.type, memory/decision are notes.",handler:async(J)=>{let U=performance.now(),K=J.args.join(" ").trim();if(K.length===0)return J0("usage.invalid","title required: myc create <title>",2);let W=Z;if(W===void 0){let A=f(J,"kind")??"task";if(W=R9[A],W===void 0)return J0("usage.invalid",`unknown --kind '${A}'; allowed: ${Object.keys(R9).join(", ")}`,2)}let V,G=f(J,"priority");if(G!==void 0){if(V=L7(G),V===void 0)return J0("usage.invalid",`invalid priority '${G}'; allowed: P0..P3 or 0..3`,2)}else if(W.defaultPriority!==void 0)V=W.defaultPriority;let H,N=f(J,"body");if(N==="-")H=await new Response(Bun.stdin.stream()).text();else if(N!==void 0)H=N;let Q,L=f(J,"estimate");if(L!==void 0){let A=P$(L);if(A===void 0)return J0("usage.invalid",`invalid estimate '${L}'; format: 30m, 2h, 1d`,2);Q=Math.round(A/60000)}let B,T=f(J,"anchor");if(T!==void 0){if(B=E8(T),B===void 0||B.path.length===0)return J0("usage.invalid",`invalid anchor '${T}'; format: file[:a-b]`,2)}let q=await $8(J,async(A)=>{let R=[B!==void 0?"--anchor":"",f(J,"parent")!==void 0?"--parent":"",iY(f(J,"dep")).length>0?"--dep":"",f(J,"reply-to")!==void 0?"--reply-to":"",f(J,"as")!==void 0?"--as":""].filter((k)=>k!=="");if(R.length>0)return J0("precond.no_remote",`the server does not accept ${R.join(", ")} yet`,5);let D=iY(f(J,"tag")),F=f(J,"repo"),P=await A.createNode({kind:W.kind,title:K,...H===void 0?{}:{body:H},...V===void 0?{}:{priority:V},...f(J,"assign")!==void 0?{assignee:f(J,"assign")}:{},...f(J,"acl")!==void 0?{acl:f(J,"acl")}:{},...W.type!==void 0||D.length>0||Q!==void 0||F!==void 0?{attrs:{...W.type===void 0?{}:{type:W.type},...D.length>0?{tags:D}:{},...Q===void 0?{}:{estimate_min:Q},...F===void 0?{}:{[qX]:F.trim()}}}:{}}),_=P.data,M=_.attrs??{},E=typeof M.type==="string"?M.type:W.kind;return{ok:!0,data:{id:String(_.id??""),kind:String(_.kind??W.kind),type:E,title:String(_.title??K),status:String(_.status??"open"),priority:Number(_.priority??V??2),blocked_by:[],anchors:[],...F===void 0?{repo:null,repo_reason:"the server does not determine repository scope"}:{repo:F.trim(),repo_reason:""},...N==="-"?{body_stdin_chars:H.length}:{},took_ms:S8(U)},meta:{...P.meta,remote:A.ws}}});if(q!==void 0)return q;let j=await Y.openStore(J);if(!j.ok)return j.failure;let O=j.handle;try{if(B!==void 0){let y=await qY(O,B,J.globals.directory??process.cwd());if(y!==void 0)return y}let A={};if(W.type!==void 0)A.type=W.type;let R=f(J,"repo");if(R!==void 0)A[qX]=R.trim();let D=iY(f(J,"tag"));if(D.length>0)A.tags=D;if(Q!==void 0)A.estimate_min=Q;let F;try{F=O.store.createNode({kind:W.kind,scope:O.scope,title:K,...H!==void 0?{body:H}:{},...V!==void 0?{priority:V}:{},...f(J,"assign")!==void 0?{assignee:f(J,"assign")}:{},...f(J,"acl")!==void 0?{acl:f(J,"acl")}:{},actor:O.actor,attrs:A})}catch(y){return C0(y)}let P=B===void 0?[]:[await jY(O,F.id,B,J.globals.directory??process.cwd(),(y,g)=>J.warn(y,g))],_=[];for(let y of iY(f(J,"dep"))){let g=R0(O,y);if(!g.ok)return g.failure;try{O.store.addEdge(g.node.id,"blocks",F.id)}catch(S){return C0(S)}_.push(g.node.id)}let M,E=f(J,"reply-to");if(E!==void 0){let y=R0(O,E);if(!y.ok)return y.failure;try{O.store.addEdge(F.id,"replies_to",y.node.id)}catch(g){return C0(g)}if(M=y.node.id,W.kind==="message"&&y.node.kind!=="message"&&y.node.kind!=="session")J.warn("comment.kind_wrong",`reply to ${y.node.kind} written as kind='message' \u2014 that is layer L0, raw session `+`dialogue: by design its body moves to bodies_cold after 14 days, and L0 never reaches the vector index. A comment is \`myc comment ${y.node.id} <text>\`: kind=note, attrs.type='comment' (S64)`)}let b=f(J,"parent");if(b!==void 0){let y=R0(O,b);if(!y.ok)return y.failure;try{O.store.addEdge(F.id,"parent",y.node.id)}catch(g){return C0(g)}}let k={id:F.id,...M!==void 0?{replies_to:M}:{},kind:F.kind,type:W.type??F.kind,title:F.title,status:F.status,priority:F.priority,blocked_by:_,anchors:P,repo:A$(F.attrs).by==="absent"?null:A$(F.attrs).repo,repo_reason:c4(O.repo),...N==="-"?{body_stdin_chars:H.length}:{},took_ms:S8(U)};return{ok:!0,data:k,meta:{took_ms:k.took_ms}}}finally{O.close()}},renderHuman:C00}}function A00($=$0){return nY("create","create a node (task, memory, decision, \u2026)",void 0,$)}function P00($=$0){return nY("task","create a task (alias of create --kind task)",R9.task,$)}function D00($=$0){return nY("bug","create a bug (task, default P1)",R9.bug,$)}function M00($=$0){return nY("epic","create an epic",R9.epic,$)}function R00($=$0){return nY("msg","create a message node (inter-agent threads)",R9.message,$)}function _00($){let X=$,Z=[`${X.id} comment ${X.actor}`,`to ${X.replies_to} ${X.target_title}`,`text ${X.title}`];if(X.body_stdin_chars!==void 0)Z.push(`body ${X.body_stdin_chars} chars from stdin`);return Z.push(`${X.took_ms} ms`),`${Z.join(`
|
|
3374
3374
|
`)}
|
|
3375
|
-
`}function
|
|
3375
|
+
`}function I00($=$0,X=()=>new Response(Bun.stdin.stream()).text()){return{name:"comment",summary:"comment on a node: a note joined to it by a replies_to edge",flags:[{name:"body",short:"b",value:"string",description:"comment text; '-' reads stdin"},{name:"acl",value:"string",description:"private|team|restricted|agent"},_9],help:"myc comment <target> [text] \u2014 the one way to write a comment. Creates kind=note, layer=1, "+"attrs.type='comment' and a replies_to edge to the target; the same shape mcp addNote writes and import-beads imports. Threads are read by the EDGE, never by node kind. Text is the positional argument or -b; '-' reads stdin.",handler:async(Z)=>{let Y=performance.now(),z=Z.args[0];if(z===void 0||z.trim().length===0)return J0("usage.invalid","target required: myc comment <target> <text>",2);let J=Z.args.slice(1).join(" ").trim(),U=f(Z,"body"),K=!1;if(U==="-"||U===void 0&&J==="-")J=(await X()).trim(),K=!0;else if(U!==void 0)J=U;if(J.length===0)return J0("usage.invalid","comment text required: myc comment <target> <text> or -b -",2);let W=await $.openStore(Z);if(!W.ok)return W.failure;let V=W.handle;try{let G=R0(V,z);if(!G.ok)return G.failure;let H;try{H=V.store.createNode(c7({text:J,scope:V.scope,actor:V.actor,...f(Z,"acl")!==void 0?{acl:f(Z,"acl")}:{}}))}catch(Q){return C0(Q)}try{V.store.addEdge(H.id,"replies_to",G.node.id)}catch(Q){return C0(Q)}let N={id:H.id,replies_to:G.node.id,target_title:G.node.title,kind:H.kind,type:"comment",title:H.title,actor:H.actor,...K?{body_stdin_chars:J.length}:{},took_ms:S8(Y)};return{ok:!0,data:N,meta:{took_ms:N.took_ms}}}finally{V.close()}},renderHuman:_00}}function k00($){let X=$,Z=[X.id,X.type];if(X.kind==="task")Z.push(g0(X.priority));Z.push(X.status,`updated: ${X.changed.join(", ")}`);let Y=[Z.join(" ")];if(X.parent_to!==void 0||X.parent_from!==void 0){let z=X.parent_from??"no epic",J=X.parent_to??"no epic";Y.push(`epic: ${z} \u2192 ${J}`)}if(X.unblocked!==void 0&&X.unblocked.length>0)Y.push(`unblocked ${X.unblocked.join(", ")} (now ready)`);for(let z of X.anchors??[])Y.push(z9(z));return Y.push(`${X.took_ms} ms`),`${Y.join(`
|
|
3376
3376
|
`)}
|
|
3377
|
-
`}function
|
|
3378
|
-
`;if(Z=`claimed ${X.id} by ${X.holder}`,X.stolen_from!==void 0)Z+=` (taken over from ${X.stolen_from}, lease expired ${T$(X.expired_ago_ms??0)} ago)`;else{let Y=
|
|
3377
|
+
`}function E00($,X,Z){if(X.kind!=="task")return;if(Z===X.status)return;if(Z==="in_progress")return J0("precond.use_claim",`${X.id}: "in progress" is taken with a lease, not by writing the status \u2014 otherwise two agents both count the task as theirs`,5,`myc claim ${X.id}`);if(Z==="blocked")return J0("precond.derived",`${X.id}: "blocked" is derived from open blockers (currently ${X.open_blockers}), not set by hand`,5,`myc dep add ${X.id} blocked-by <id>`);if(Z==="closed")return J0("precond.use_close",`${X.id}: closing requires ownership and a reason, and reports what it unblocked`,5,`myc close ${X.id} --reason "\u2026"`);if(Z==="open"){let Y=$.store.leaseOf(X.id);if(Y!==void 0&&Y.holder.length>0&&Y.expires>Date.now())return J0("conflict.claimed",`${X.id} is claimed by ${Y.holder} (lease until ${new Date(Y.expires).toISOString().slice(11,19)}Z); status open under a live lease makes the task unclaimable: it shows in ready, but claim refuses`,4,`myc release ${X.id}${Y.holder!==$.actor?" --force":""}`)}return}function v00($=$0){return{name:"update",summary:"update fields of a node",remote:!0,flags:[{name:"title",value:"string",description:"new title"},{name:"body",short:"b",value:"string",description:"new body; '-' reads stdin"},{name:"status",value:"string",description:"new status (validated per kind)"},{name:"priority",short:"p",value:"string",description:"P0|P1|P2|P3 or 0|1|2|3"},{name:"tag",value:"string",list:!0,description:"replace tags (comma-separated)"},{name:"assign",value:"string",description:"assignee; empty string unassigns"},{name:"estimate",value:"string",description:"estimate, e.g. 30m, 2h"},{name:"acl",value:"string",description:"private|team|restricted|agent"},{name:"parent",value:"string",description:"move under this epic"},{name:"no-parent",description:"detach from the current epic"},{name:"anchor",value:"string",description:"bind an anchor file[:<a>-<b>]; a missing file, a directory, a binary or secret-named file, or a path outside the root is refused, and nothing is written"},_9],handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0)return J0("usage.invalid","id required: myc update <id> [flags]",2);let z=f(X,"anchor"),J;if(z!==void 0){if(J=E8(z),J===void 0||J.path.trim().length===0)return J0("usage.invalid",`invalid anchor '${z}'; format: file[:a-b]`,2)}let U=f(X,"priority"),K;if(U!==void 0){if(K=L7(U),K===void 0)return J0("usage.invalid",`invalid priority '${U}'; allowed: P0..P3 or 0..3`,2)}let W=f(X,"estimate"),V;if(W!==void 0){let Q=P$(W);if(Q===void 0)return J0("usage.invalid",`invalid estimate '${W}'; format: 30m, 2h, 1d`,2);V=Math.round(Q/60000)}let G=await $8(X,async(Q)=>{let L=[J!==void 0?"--anchor":"",f(X,"parent")!==void 0?"--parent":"",X.flags["no-parent"]===!0?"--no-parent":"",f(X,"tag")!==void 0?"--tag":"",f(X,"acl")!==void 0?"--acl":"",V!==void 0?"--estimate":""].filter((_)=>_!=="");if(L.length>0)return J0("precond.no_remote",`the server does not accept ${L.join(", ")} yet`,5);let B=f(X,"body"),T={},q=f(X,"title");if(q!==void 0)T.title=q;if(B==="-")T.body=await new Response(Bun.stdin.stream()).text();else if(B!==void 0)T.body=B;let j=f(X,"status");if(j!==void 0)T.status=j;if(K!==void 0)T.priority=K;let O=f(X,"assign");if(O!==void 0)T.assignee=O;let A=await Q.patchNode(Y,T),R=A.data,D=R.attrs??{},F=A.meta.changed;return{ok:!0,data:{id:String(R.id??Y),kind:String(R.kind??""),type:typeof D.type==="string"?D.type:String(R.kind??""),status:String(R.status??""),priority:Number(R.priority??K??2),changed:Array.isArray(F)?F.map(String):Object.keys(T),took_ms:S8(Z)},meta:{...A.meta,remote:Q.ws}}});if(G!==void 0)return G;let H=await $.openStore(X);if(!H.ok)return H.failure;let N=H.handle;try{let Q=R0(N,Y);if(!Q.ok)return Q.failure;let L=Q.node,B={},T=[],q=f(X,"title");if(q!==void 0)B.title=q,T.push("title");let j=f(X,"body"),O;if(j==="-")O=await new Response(Bun.stdin.stream()).text();else if(j!==void 0)O=j;if(O!==void 0)B.body=O,T.push("body");let A=f(X,"status");if(A!==void 0){let w=E00(N,L,A);if(w!==void 0)return w;B.status=A,T.push("status")}if(K!==void 0)B.priority=K,T.push("priority");let R=f(X,"assign");if(R!==void 0)B.assignee=R,T.push("assignee");let D=f(X,"acl");if(D!==void 0)B.acl=D,T.push("acl");let F={},P=f(X,"tag");if(P!==void 0)F.tags=iY(P),T.push("tags");if(V!==void 0)F.estimate_min=V,T.push("estimate");if(Object.keys(F).length>0)B.attrs=F;let _=[];if(J!==void 0){let w=await FY(N,L.id,J,X.globals.directory??process.cwd(),...f(X,"as")!==void 0?[{actor:f(X,"as")}]:[]);if(!w.ok)return TY(w)??C0(w.cause);let h=w.anchor;if(h.deferred)X.warn("anchor.deferred",`crux deferred to the background: ${h.sizeBytes} bytes is over the inline threshold \u2014 `+"the background check (myc anchor check) catches up on precision");_.push(YU(h)),T.push("anchor")}let M=f(X,"parent"),E=K0(X,"no-parent");if(M!==void 0&&E)return J0("usage.invalid","--parent and --no-parent are mutually exclusive",2);let b,k;if(M!==void 0||E){let w=N.store.edgesFrom(L.id,"parent")[0]?.dst??null;if(E){if(w===null)return J0("precond.no_parent",`${L.id} is not in any epic to begin with`,5);try{N.store.removeEdge(L.id,"parent",w)}catch(h){return C0(h)}b=w,k=null,T.push("parent")}else{let h=R0(N,M);if(!h.ok)return h.failure;if(h.node.id===L.id)return J0("precond.self_parent",`${L.id} cannot be its own parent`,5);if(w===h.node.id)return J0("precond.same_parent",`${L.id} is already in ${h.node.id}`,5);try{N.store.addEdge(L.id,"parent",h.node.id)}catch(u){return C0(u)}b=w,k=h.node.id,T.push("parent")}}if(T.length===0)return J0("usage.invalid","nothing to update: no change flags given",2);let y;try{y=Object.keys(B).length===0?N.store.getNode(L.id)??L:N.store.updateNode(L.id,B)}catch(w){return C0(w)}let g=[];if(y.status==="cancelled"&&y.kind==="task")for(let w of N.store.edgesFrom(y.id,"blocks")){let h=N.store.getNode(w.dst);if(h!==void 0&&h.status==="open"&&h.open_blockers===0&&h.anc_blockers===0)g.push(h.id)}let S={id:y.id,kind:y.kind,type:m6(y),status:y.status,priority:y.priority,changed:T,...g.length>0?{unblocked:g}:{},...k!==void 0?{parent_from:b??null,parent_to:k}:{},..._.length>0?{anchors:_}:{},took_ms:S8(Z)};return{ok:!0,data:S,meta:{took_ms:S.took_ms}}}finally{N.close()}},renderHuman:k00}}function f00($){let X=$,Z;if(X.renewed===!0)return Z=`renewed ${X.id} by ${X.holder} \xB7 lease ${T$(X.lease_ttl_ms)} until ${M6(X.lease_expires)}`,`${Z}
|
|
3378
|
+
`;if(Z=`claimed ${X.id} by ${X.holder}`,X.stolen_from!==void 0)Z+=` (taken over from ${X.stolen_from}, lease expired ${T$(X.expired_ago_ms??0)} ago)`;else{let Y=y00[X.lease_source];Z+=` \xB7 lease ${T$(X.lease_ttl_ms)}${Y} until ${M6(X.lease_expires)}`}return`${Z}
|
|
3379
3379
|
${X.id} ${g0(X.priority)} ${X.type} ${X.prev_status}\u2192in_progress
|
|
3380
|
-
`}function
|
|
3381
|
-
`}}}function
|
|
3380
|
+
`}function S00($=$0){return{name:"release",summary:"give up a claimed task: lease cleared, status back to open",flags:[{name:"force",description:"take away a LIVE lease held by someone else (WARNs)"},_9],handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0)return J0("usage.invalid","id required: myc release <id>",2);let z=X.flags.force===!0,J=await $.openStore(X);if(!J.ok)return J.failure;let U=J.handle;try{let K=R0(U,Y);if(!K.ok)return K.failure;let W=K.node,V=U.store.leaseOf(W.id);if(V===void 0||V.holder.length===0)return J0("precond.not_claimed",`${W.id} is not claimed by anyone \u2014 nothing to release`,5);if(V.holder!==U.actor&&!z)return J0("conflict.claimed",`${W.id} is claimed by ${V.holder}, ${Z4(V.holder,V.expires,Date.now())}; releasing someone else's claim must be explicit`,4,`myc release ${W.id} --force`);if(V.holder!==U.actor)X.warn("release.forced",`lease taken from ${V.holder}; their edits may still be in the working tree`);if(!U.store.releaseLease(W.id,V.holder,V.epoch))return J0("conflict.claimed",`${W.id}: ownership has already moved on (stale epoch) \u2014 nothing to release`,4);let G={id:W.id,status:"open",released_from:V.holder,forced:V.holder!==U.actor,took_ms:S8(Z)};return{ok:!0,data:G,meta:{took_ms:G.took_ms}}}finally{U.close()}},renderHuman:(X)=>{let Z=X;return`${Z.id} released (was held by ${Z.released_from})${Z.forced?" \u2014 forced":""} \u2192 open
|
|
3381
|
+
`}}}function g00($=$0){return{name:"claim",summary:"atomically take a task (CAS lease, \xA79.4)",remote:!0,flags:[{name:"lease",value:"string",description:"lease TTL, e.g. 30m (default), 2h"},{name:"steal",description:"take over an expired lease (WARNs about the previous owner)"},_9],handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0)return J0("usage.invalid","id required: myc claim <id>",2);let z,J=f(X,"lease");if(J!==void 0){let V=P$(J);if(V===void 0)return J0("usage.invalid",`invalid lease '${J}'; format: 30m, 2h`,2);z=V}let U=await $8(X,async(V)=>{if(X.flags.steal===!0)return J0("precond.no_remote","--steal is not supported on a server yet: it needs the previous holder, and the server does not report it",5);let G=await V.claim(Y,z===void 0?void 0:Math.round(z/60000)),H=G.data,N=Number(H.expiresAt??0);return{ok:!0,data:{id:String(H.id??Y),holder:String(H.holder??""),epoch:Number(H.epoch??0),lease_expires:N,lease_ttl_ms:Math.max(0,N-Date.now()),lease_source:z===void 0?"default":"flag",status:"in_progress",prev_status:String(H.prev_status??"open"),type:String(H.type??"task"),priority:Number(H.priority??2),took_ms:S8(Z)},meta:{...G.meta,remote:V.ws}}});if(U!==void 0)return U;let K=await $.openStore(X);if(!K.ok)return K.failure;let W=K.handle;try{let V=R0(W,Y);if(!V.ok)return V.failure;let G=V.node;if(G.status==="closed"||G.status==="cancelled")return J0("precond.closed",`${G.id} already ${G.status}`,5);if(G.open_blockers>0)return J0("precond.blocked",`${G.id} is blocked by ${G.open_blockers} open ${G.open_blockers===1?"dependency":"dependencies"}`,5,`myc dep why ${G.id}`);if(G.anc_blockers>0){let j=W.store.blockingAncestors(G.id).map((O)=>`${O.id} (${O.open_blockers})`).join(", ");X.warn("task.blocked_via_parent",`${G.id} is not in ready: blocker on ancestor ${j} \u2014 the work would rest on an unready foundation`)}let H=N7(G),N="flag";if(z===void 0)if(H===void 0)N="default",z=B5;else{let j=H*60000;if(j>aJ)N="capped",z=aJ;else if(j<B5)N="floor",z=B5;else N="estimate",z=j}let Q=Date.now(),L=W.store.leaseOf(G.id),B=L!==void 0&&L.holder.length>0&&L.holder!==W.actor&&L.expires>0&&L.expires<=Q?L:void 0,T=W.claims.claim(G.id,z);if(T!==void 0){if(B!==void 0)X.warn("claim.stolen","the previous owner did not close the task; their edits may still be in the working tree");let j={id:G.id,holder:W.actor,epoch:T.epoch,lease_expires:T.expiresAt,lease_ttl_ms:z,lease_source:N,status:"in_progress",prev_status:G.status,type:m6(G),priority:G.priority,...B!==void 0?{stolen_from:B.holder,expired_ago_ms:Q-B.expires}:{},took_ms:S8(Z)};return{ok:!0,data:j,meta:{took_ms:j.took_ms}}}let q=W.store.leaseOf(G.id);if(q!==void 0&&q.holder===W.actor&&q.epoch>0&&(q.expires===0||q.expires>Q)){let j=W.store.renewLease(G.id,W.actor,q.epoch,z);if(j!==void 0){let O={id:G.id,holder:W.actor,epoch:q.epoch,lease_expires:j,lease_ttl_ms:z,lease_source:N,status:"in_progress",prev_status:"in_progress",type:m6(G),priority:G.priority,renewed:!0,took_ms:S8(Z)};return{ok:!0,data:O,meta:{took_ms:O.took_ms}}}}if(q!==void 0&&q.holder.length>0)return J0("conflict.claimed",`${G.id} already claimed by ${q.holder} (lease until ${M6(q.expires)})`,4,`wait for the lease to expire or myc claim ${G.id} --steal`);return J0("conflict.claimed",`${G.id} cannot be claimed`,4)}finally{W.close()}},renderHuman:f00}}function dE($){if($>=1000){let X=$/1000;return`${Number.isInteger(X)?X:X.toFixed(1)}k`}return String($)}function b00($){let X=$;if(X.already===!0&&X.attribution===void 0)return`${X.id} already ${X.status}
|
|
3382
3382
|
`;let Z=[X.already===!0?`${X.id} already ${X.status}`:`closed ${X.id}`];if(X.in_progress_ms!==void 0)Z.push(`in_progress ${T$(X.in_progress_ms)}`);Z.push(`@${X.closed_by}`);let Y=[Z.join(" \xB7 ")];if(X.unblocked.length>0)Y.push(`unblocked ${X.unblocked.join(", ")} (now ready)`);let z=X.outcome;if(z!==void 0){let U=[];if(typeof z.verify==="string")U.push(`verify=${z.verify}`);if(typeof z.model==="string")U.push(`model=${z.model}`);if(typeof z.cost_in==="number"||typeof z.cost_out==="number"){let K=typeof z.cost_in==="number"?z.cost_in:0,W=typeof z.cost_out==="number"?z.cost_out:0;U.push(`in ${dE(K)} / out ${dE(W)}`)}if(U.length>0)Y.push(`outcome recorded (${U.join(", ")})`)}let J=X.attribution;if(J!==void 0){if(J.recorded){let U=J.caveats??[];Y.push(`attribution ${J.model_id} \xB7 ${J.task_class} \xB7 ${J.verdict}${U.length>0?` (caveats: ${U.join(", ")})`:""}`+` \xB7 q=${(J.quality??0).toFixed(2)}`)}else if(J.skipped!==void 0)Y.push(`attribution NOT recorded: ${J.skipped}`)}return Y.push(`${X.took_ms} ms`),`${Y.join(`
|
|
3383
3383
|
`)}
|
|
3384
|
-
`}function bB($){return $.driver.database.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'swarm_attempt'").get()!==null}function oE($,X,Z,Y){let z=f($,"model"),J=Z.assignee!==void 0&&Z.assignee.length>0?Z.assignee:X.actor,U=Y===void 0?void 0:process.env.MYC_MODEL,K=U!==void 0&&J!==sJ(),V=z??(K?void 0:U),G=f($,"attempt");if(G!==void 0){if(Y===void 0)return J0("usage.attempt","--attempt without --verdict: it names where the verdict goes",2);let T=bB(X)?C7(X.driver.database).attribution.getAttempt(G):void 0;if(T===void 0||T.taskId!==Z.id)return J0("usage.attempt",T===void 0?`attempt ${G} not found`:`attempt ${G} belongs to ${T.taskId}, not to ${Z.id}`,2,`myc attempt list --task ${Z.id}`);if(T.finishedAt!==null)return J0("conflict.finished",`attempt ${T.attemptId} already has an outcome (${T.verdict}); it cannot be rewritten`,4);let q;if(z!==void 0){let j=lY(C7(X.driver.database).roster,z);if(!j.ok)return j.failure;q=j.modelId}return{plan:{kind:"finish",attempt:T},canonicalModel:q??T.modelId}}if(Y===void 0&&V===void 0){if(!bB(X))return{plan:{kind:"none"}};let T=C7(X.driver.database).attribution.openAttemptForTask(Z.id);if(T===void 0)return{plan:{kind:"none"}};return{plan:{kind:"none",skipped:`open attempt ${T.attemptId} left without an outcome`,warn:["attribution.open",`${Z.id} has open attempt ${T.attemptId}; closing without --verdict leaves it without an outcome`]}}}let H=C7(X.driver.database),N,Q;if(V!==void 0){let T=lY(H.roster,V);if(!T.ok){if(z!==void 0)return T.failure;Q=V,$.warn("attribution.env_model",`$MYC_MODEL="${V}" is not in the roster: ${T.failure.msg}`)}else N=T.modelId}if(Y===void 0)return{plan:{kind:"none"},canonicalModel:N};let L=H.attribution.openAttemptForTask(Z.id);if(L!==void 0)return{plan:{kind:"finish",attempt:L},canonicalModel:N??L.modelId};if(N===void 0){let T=Q!==void 0?`model "${Q}" is not in the roster`:K?`the outcome belongs to ${J} and $MYC_MODEL describes this process (${sJ()})`:"a verdict was given but no model";return{plan:{kind:"none",skipped:`no open attempt, and ${T}`,warn:["attribution.no_model",`${Z.id}: the outcome did not reach swarm stats \u2014 ${T} `+"(myc attempt start <id> --model \u2026 or --model on close)"]}}}let B=X.driver.database;return{plan:{kind:"retro",modelId:N,key:P9(Z,B,Z.id),predictedClass:cY(Z,B,Z.id,X.wsDir).taskClass},canonicalModel:N}}async function aE($,X,Z,Y,z,J,U){let K=C7(X.driver.database),W=pY($),V=$.flags["cost-in"],G=$.flags["cost-out"];if(W.tokensIn===void 0&&typeof V==="number")W.tokensIn=V;if(W.tokensOut===void 0&&typeof G==="number")W.tokensOut=G;let H=$.flags.retries;try{let N=Y.kind==="finish"?Y.attempt.attemptId:K.attribution.startAttempt({taskId:Z.id,modelId:Y.modelId,taskClass:Y.key.taskClass,scopeSource:Y.key.scopeSource,predictedClass:Y.predictedClass,actor:X.actor,source:"close",...W}).attemptId,Q=await JK($,{db:X.driver.database,attribution:K.attribution},U,N,{tokens:W},{verdict:z,caveats:J,retries:typeof H==="number"?H:void 0},X.wsDir),L=Q.record;return{recorded:!0,attempt_id:L.attemptId,model_id:L.modelId,task_class:L.taskClass,...L.scopeSource!==null?{scope_source:L.scopeSource}:{},verdict:L.verdict??z,caveats:[...L.caveats],quality:L.quality??0,cost_usd:L.costUsd,cost_basis:L.costBasis,spend_via:Q.spend.via}}catch(N){return $6(N)}}async function y00($,X,Z,Y,z,J,U){let K=oE($,X,Z,Y);if("ok"in K)return K;let W=K.plan;if(W.kind!=="finish"){let H=bB(X)?C7(X.driver.database).attribution.listAttempts({taskId:Z.id}).filter((N)=>N.finishedAt!==null):[];if(H.length>0){let N=H[0];return J0("conflict.finished",`${Z.id} is already ${Z.status} and its outcome is already recorded (${N.attemptId}: ${N.verdict}); a second verdict would record the same work twice`,4,`myc attempt list --task ${Z.id}; another attempt: myc attempt start ${Z.id} --model <id>`)}if(W.kind==="none")return J0("attribution.not_recorded",`${Z.id} is already ${Z.status}: the verdict was not recorded \u2014 `+`${W.skipped??"there is no attempt to record it in"}`,5,`myc close ${Z.id} --verdict ${Y} --model <roster model id>`)}let V=await aE($,X,Z,W,Y,z,J);if("ok"in V)return V;let G={id:Z.id,status:Z.status,closed_by:Z.assignee||X.actor,already:!0,unblocked:[],attribution:V,took_ms:S8(U)};return{ok:!0,data:G,meta:{took_ms:G.took_ms}}}function f00($=$0,X=ZK){return{name:"close",summary:"close a task",flags:[{name:"reason",value:"string",description:"why / how it was resolved"},{name:"verify",value:"string",description:"tests|review|human|none"},{name:"outcome",value:"string",description:"done|wontfix|duplicate|superseded"},{name:"dup",value:"string",description:"canonical node id when --outcome duplicate"},{name:"cost-in",value:"number",description:"input tokens spent (synonym of --tokens-in)"},{name:"cost-out",value:"number",description:"output tokens spent (synonym of --tokens-out)"},{name:"tokens-in",value:"number",description:"input tokens spent ($MYC_TOKENS_IN)"},{name:"tokens-out",value:"number",description:"output tokens spent ($MYC_TOKENS_OUT)"},{name:"cache-read",value:"number",description:"cache-read tokens"},{name:"cache-write",value:"number",description:"cache-write tokens"},{name:"model",value:"string",description:"roster model that did the work (L4)"},{name:"verdict",value:"string",description:`acceptance verdict: ${w6.join("|")} (L4 attribution)`},{name:"caveat",value:"string",description:`accepted-but: ${x6.join(", ")}`},{name:"retries",value:"number",description:"rework rounds before acceptance (L4)"},{name:"attempt",value:"string",description:"attempt that gets the verdict (default: the task's latest open attempt)"},_9],handler:async(Z)=>{let Y=performance.now(),z=Z.args[0];if(z===void 0)return J0("usage.invalid","id required: myc close <id>",2);let J=f(Z,"verify");if(J!==void 0&&!iE.includes(J))return J0("usage.invalid",`invalid --verify '${J}'; allowed: ${iE.join(", ")}`,2);let U=f(Z,"outcome");if(U!==void 0&&!nE.includes(U))return J0("usage.invalid",`invalid --outcome '${U}'; allowed: ${nE.join(", ")}`,2);let K=f(Z,"dup");if(U==="duplicate"&&K===void 0)return J0("usage.invalid","--outcome duplicate requires --dup <id>",2);let W=f(Z,"verdict");if(W!==void 0&&!w6.includes(W))return J0("usage.verdict",`invalid --verdict '${W}'; allowed: ${w6.join(", ")}`,2);let V=YK(Z);if(!Array.isArray(V))return V;if(W===void 0&&V.length>0)return J0("usage.verdict","--caveat without --verdict: a caveat only qualifies a verdict",2);let G=await $.openStore(Z);if(!G.ok)return G.failure;let H=G.handle;try{let N=R0(H,z);if(!N.ok)return N.failure;let Q=N.node;if(Q.status==="closed"||Q.status==="cancelled"){if(W!==void 0)return await y00(Z,H,Q,W,V,X,Y);let E={id:Q.id,status:Q.status,closed_by:Q.assignee||H.actor,already:!0,unblocked:[],took_ms:S8(Y)};return{ok:!0,data:E,meta:{took_ms:E.took_ms}}}if(Q.status==="blocked")return J0("precond.blocked",`${Q.id} is blocked; close its dependencies first`,5,`myc dep why ${Q.id}`);let L=oE(Z,H,Q,W);if("ok"in L)return L;let B=Date.now(),T=Q.status==="in_progress",q=H.store.leaseOf(Q.id);if(T&&q!==void 0&&q.holder.length>0){if(q.holder!==H.actor)return J0("conflict.claimed",`${Q.id} is claimed by ${q.holder}; only the owner can close it`,4,`myc close ${Q.id} --as ${q.holder}`);if(!H.store.closeClaimed(Q.id,q.holder,q.epoch))return J0("conflict.claimed",`${Q.id}: ownership lost (stale epoch)`,4)}else try{H.store.updateNode(Q.id,{status:"closed",closed_at:B})}catch(E){return C0(E)}let j={},O=f(Z,"reason");if(O!==void 0)j.reason=O;if(J!==void 0)j.verify=J;if(U!==void 0)j.outcome=U;if(L.canonicalModel!==void 0)j.model=L.canonicalModel;let A=Z.flags["cost-in"],R=Z.flags["cost-out"],D=Z.flags.retries;if(typeof A==="number")j.cost_in=A;if(typeof R==="number")j.cost_out=R;if(typeof D==="number")j.retries=D;if(Object.keys(j).length>0)try{H.store.updateNode(Q.id,{attrs:{outcome:j}})}catch(E){return C0(E)}if(K!==void 0){let E=R0(H,K);if(!E.ok)return E.failure;try{H.store.addEdge(Q.id,"duplicates",E.node.id)}catch(b){return C0(b)}}let F=[];for(let E of H.store.edgesFrom(Q.id,"blocks")){let b=H.store.getNode(E.dst);if(b!==void 0&&b.status==="open"&&b.open_blockers===0&&b.anc_blockers===0)F.push(b.id)}let P;if(W!==void 0&&L.plan.kind!=="none"){let E=await aE(Z,H,Q,L.plan,W,V,X);if("ok"in E)Z.warn("attribution.failed",`outcome not recorded: ${E.msg}`),P={recorded:!1,skipped:E.msg};else P=E}else if(L.plan.kind==="none"){let E=L.plan.skipped??(W!==void 0?"could not record the outcome":void 0);if(L.plan.warn!==void 0)Z.warn(...L.plan.warn);if(E!==void 0)P={recorded:!1,skipped:E}}let _=q!==void 0&&q.holder.length>0?q.holder:H.actor,M={id:Q.id,status:"closed",closed_by:_,...T?{in_progress_ms:B-Q.updated_at}:{},unblocked:F,...Object.keys(j).length>0?{outcome:j}:{},...P!==void 0?{attribution:P}:{},took_ms:S8(Y)};return{ok:!0,data:M,meta:{took_ms:M.took_ms}}}finally{H.close()}},renderHuman:v00}}var R9,_9,cE,_00,iE,nE;var L8=v(()=>{o();B4();V0();w5();k6();UK();j0();R9={task:{kind:"task",type:"task"},bug:{kind:"task",type:"bug",defaultPriority:1},epic:{kind:"task",type:"epic"},chore:{kind:"task",type:"chore"},memory:{kind:"note"},decision:{kind:"note",type:"decision"},document:{kind:"doc"},skill:{kind:"skill"},message:{kind:"message"}};_9={name:"as",value:"string",description:"actor for the record and claim (default $MYC_ACTOR/$USER)"},cE=[{name:"kind",value:"string",description:"task|bug|epic|memory|decision|document|skill|message"},{name:"priority",short:"p",value:"string",description:"P0|P1|P2|P3 or 0|1|2|3"},{name:"body",short:"b",value:"string",description:"node body; '-' reads stdin"},{name:"tag",value:"string",list:!0,description:"comma-separated tags"},{name:"parent",value:"string",description:"parent node id"},{name:"dep",value:"string",list:!0,description:"comma-separated blocker ids"},{name:"anchor",value:"string",description:"bind an anchor file[:<a>-<b>]; a directory, a binary or secret-named file is refused before anything is written; a missing file or a path outside the root stays an intent (WARN)"},{name:"reply-to",value:"string",description:"reply to this node: adds a replies_to edge"},{name:"assign",value:"string",description:"assignee"},{name:"estimate",value:"string",description:"estimate, e.g. 30m, 2h, 1d"},{name:"acl",value:"string",description:"private|team|restricted|agent"},{name:"repo",value:"string",description:"repository scope (S59); default is derived from the current directory"},_9];_00={flag:"",estimate:" (estimate)",capped:" (1-day cap)",floor:" (minimum)",default:""};iE=["tests","review","human","none"],nE=["done","wontfix","duplicate","superseded"]});var sE={};s(sE,{createMoveCommand:()=>w00});import{resolve as S00}from"path";function A7($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function g00($){if($.code==="notfound")return A7("notfound.node",$.msg,3);if($.code==="same_workspace")return A7("usage.same_workspace",$.msg,2);if($.code==="chain_truncated")return A7("precond.chain_truncated",$.msg,5);if($.code==="cross_boundary_parent")return A7("precond.cross_boundary_parent",$.msg,5,"unblock the epic, or move the whole subtree, or remove the parent edge");if($.code==="leased")return A7("precond.leased",$.msg,5,"wait for the lease to end, or myc release");let X=$.crossing.slice(0,5).map((Z)=>`${Z.src} blocks ${Z.dst}`).join("; ");return A7("precond.cross_boundary",`${$.msg}: ${X}${$.crossing.length>5?"\u2026":""}`,5,"--with-blockers moves the whole connected piece, --dry-run shows its size")}function b00($){let X=$,Z=[],Y=X.dry_run?"dry-run: ":"";if(Z.push(`${Y}${X.id}: ${X.from===""?"(no slug)":X.from} \u2192 ${X.to===""?"(no slug)":X.to} (${X.to_dir})`),Z.push(` moving ${X.members.length} ${X.members.length===1?"node":"nodes"}, ${X.edges.length} ${X.edges.length===1?"edge":"edges"}, ${X.ops} history ${X.ops===1?"operation":"operations"}`+(X.expanded?" (set expanded along blocks)":"")),X.members.length>1)Z.push(` nodes: ${X.members.join(", ")}`);if(X.staying.length>0)Z.push(` staying in the source: ${X.staying.length} ${X.staying.length===1?"edge":"edges"} \u2014 `+"the other end is not moving, the tombstone holds them");if(!X.dry_run)Z.push(` applied ${X.applied??0}, duplicates ${X.duplicate??0}, moves minted ${X.minted??0}`+(X.resumed===!0?" (resumed an interrupted move)":""));return Z.push(`done in ${X.took_ms} ms`),`${Z.join(`
|
|
3384
|
+
`}function bB($){return $.driver.database.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'swarm_attempt'").get()!==null}function oE($,X,Z,Y){let z=f($,"model"),J=Z.assignee!==void 0&&Z.assignee.length>0?Z.assignee:X.actor,U=Y===void 0?void 0:process.env.MYC_MODEL,K=U!==void 0&&J!==sJ(),V=z??(K?void 0:U),G=f($,"attempt");if(G!==void 0){if(Y===void 0)return J0("usage.attempt","--attempt without --verdict: it names where the verdict goes",2);let T=bB(X)?C7(X.driver.database).attribution.getAttempt(G):void 0;if(T===void 0||T.taskId!==Z.id)return J0("usage.attempt",T===void 0?`attempt ${G} not found`:`attempt ${G} belongs to ${T.taskId}, not to ${Z.id}`,2,`myc attempt list --task ${Z.id}`);if(T.finishedAt!==null)return J0("conflict.finished",`attempt ${T.attemptId} already has an outcome (${T.verdict}); it cannot be rewritten`,4);let q;if(z!==void 0){let j=lY(C7(X.driver.database).roster,z);if(!j.ok)return j.failure;q=j.modelId}return{plan:{kind:"finish",attempt:T},canonicalModel:q??T.modelId}}if(Y===void 0&&V===void 0){if(!bB(X))return{plan:{kind:"none"}};let T=C7(X.driver.database).attribution.openAttemptForTask(Z.id);if(T===void 0)return{plan:{kind:"none"}};return{plan:{kind:"none",skipped:`open attempt ${T.attemptId} left without an outcome`,warn:["attribution.open",`${Z.id} has open attempt ${T.attemptId}; closing without --verdict leaves it without an outcome`]}}}let H=C7(X.driver.database),N,Q;if(V!==void 0){let T=lY(H.roster,V);if(!T.ok){if(z!==void 0)return T.failure;Q=V,$.warn("attribution.env_model",`$MYC_MODEL="${V}" is not in the roster: ${T.failure.msg}`)}else N=T.modelId}if(Y===void 0)return{plan:{kind:"none"},canonicalModel:N};let L=H.attribution.openAttemptForTask(Z.id);if(L!==void 0)return{plan:{kind:"finish",attempt:L},canonicalModel:N??L.modelId};if(N===void 0){let T=Q!==void 0?`model "${Q}" is not in the roster`:K?`the outcome belongs to ${J} and $MYC_MODEL describes this process (${sJ()})`:"a verdict was given but no model";return{plan:{kind:"none",skipped:`no open attempt, and ${T}`,warn:["attribution.no_model",`${Z.id}: the outcome did not reach swarm stats \u2014 ${T} `+"(myc attempt start <id> --model \u2026 or --model on close)"]}}}let B=X.driver.database;return{plan:{kind:"retro",modelId:N,key:P9(Z,B,Z.id),predictedClass:cY(Z,B,Z.id,X.wsDir).taskClass},canonicalModel:N}}async function aE($,X,Z,Y,z,J,U){let K=C7(X.driver.database),W=pY($),V=$.flags["cost-in"],G=$.flags["cost-out"];if(W.tokensIn===void 0&&typeof V==="number")W.tokensIn=V;if(W.tokensOut===void 0&&typeof G==="number")W.tokensOut=G;let H=$.flags.retries;try{let N=Y.kind==="finish"?Y.attempt.attemptId:K.attribution.startAttempt({taskId:Z.id,modelId:Y.modelId,taskClass:Y.key.taskClass,scopeSource:Y.key.scopeSource,predictedClass:Y.predictedClass,actor:X.actor,source:"close",...W}).attemptId,Q=await JK($,{db:X.driver.database,attribution:K.attribution},U,N,{tokens:W},{verdict:z,caveats:J,retries:typeof H==="number"?H:void 0},X.wsDir),L=Q.record;return{recorded:!0,attempt_id:L.attemptId,model_id:L.modelId,task_class:L.taskClass,...L.scopeSource!==null?{scope_source:L.scopeSource}:{},verdict:L.verdict??z,caveats:[...L.caveats],quality:L.quality??0,cost_usd:L.costUsd,cost_basis:L.costBasis,spend_via:Q.spend.via}}catch(N){return $6(N)}}async function w00($,X,Z,Y,z,J,U){let K=oE($,X,Z,Y);if("ok"in K)return K;let W=K.plan;if(W.kind!=="finish"){let H=bB(X)?C7(X.driver.database).attribution.listAttempts({taskId:Z.id}).filter((N)=>N.finishedAt!==null):[];if(H.length>0){let N=H[0];return J0("conflict.finished",`${Z.id} is already ${Z.status} and its outcome is already recorded (${N.attemptId}: ${N.verdict}); a second verdict would record the same work twice`,4,`myc attempt list --task ${Z.id}; another attempt: myc attempt start ${Z.id} --model <id>`)}if(W.kind==="none")return J0("attribution.not_recorded",`${Z.id} is already ${Z.status}: the verdict was not recorded \u2014 `+`${W.skipped??"there is no attempt to record it in"}`,5,`myc close ${Z.id} --verdict ${Y} --model <roster model id>`)}let V=await aE($,X,Z,W,Y,z,J);if("ok"in V)return V;let G={id:Z.id,status:Z.status,closed_by:Z.assignee||X.actor,already:!0,unblocked:[],attribution:V,took_ms:S8(U)};return{ok:!0,data:G,meta:{took_ms:G.took_ms}}}function x00($=$0,X=ZK){return{name:"close",summary:"close a task",flags:[{name:"reason",value:"string",description:"why / how it was resolved"},{name:"verify",value:"string",description:"tests|review|human|none"},{name:"outcome",value:"string",description:"done|wontfix|duplicate|superseded"},{name:"dup",value:"string",description:"canonical node id when --outcome duplicate"},{name:"cost-in",value:"number",description:"input tokens spent (synonym of --tokens-in)"},{name:"cost-out",value:"number",description:"output tokens spent (synonym of --tokens-out)"},{name:"tokens-in",value:"number",description:"input tokens spent ($MYC_TOKENS_IN)"},{name:"tokens-out",value:"number",description:"output tokens spent ($MYC_TOKENS_OUT)"},{name:"cache-read",value:"number",description:"cache-read tokens"},{name:"cache-write",value:"number",description:"cache-write tokens"},{name:"model",value:"string",description:"roster model that did the work (L4)"},{name:"verdict",value:"string",description:`acceptance verdict: ${w6.join("|")} (L4 attribution)`},{name:"caveat",value:"string",description:`accepted-but: ${x6.join(", ")}`},{name:"retries",value:"number",description:"rework rounds before acceptance (L4)"},{name:"attempt",value:"string",description:"attempt that gets the verdict (default: the task's latest open attempt)"},_9],handler:async(Z)=>{let Y=performance.now(),z=Z.args[0];if(z===void 0)return J0("usage.invalid","id required: myc close <id>",2);let J=f(Z,"verify");if(J!==void 0&&!iE.includes(J))return J0("usage.invalid",`invalid --verify '${J}'; allowed: ${iE.join(", ")}`,2);let U=f(Z,"outcome");if(U!==void 0&&!nE.includes(U))return J0("usage.invalid",`invalid --outcome '${U}'; allowed: ${nE.join(", ")}`,2);let K=f(Z,"dup");if(U==="duplicate"&&K===void 0)return J0("usage.invalid","--outcome duplicate requires --dup <id>",2);let W=f(Z,"verdict");if(W!==void 0&&!w6.includes(W))return J0("usage.verdict",`invalid --verdict '${W}'; allowed: ${w6.join(", ")}`,2);let V=YK(Z);if(!Array.isArray(V))return V;if(W===void 0&&V.length>0)return J0("usage.verdict","--caveat without --verdict: a caveat only qualifies a verdict",2);let G=await $.openStore(Z);if(!G.ok)return G.failure;let H=G.handle;try{let N=R0(H,z);if(!N.ok)return N.failure;let Q=N.node;if(Q.status==="closed"||Q.status==="cancelled"){if(W!==void 0)return await w00(Z,H,Q,W,V,X,Y);let E={id:Q.id,status:Q.status,closed_by:Q.assignee||H.actor,already:!0,unblocked:[],took_ms:S8(Y)};return{ok:!0,data:E,meta:{took_ms:E.took_ms}}}if(Q.status==="blocked")return J0("precond.blocked",`${Q.id} is blocked; close its dependencies first`,5,`myc dep why ${Q.id}`);let L=oE(Z,H,Q,W);if("ok"in L)return L;let B=Date.now(),T=Q.status==="in_progress",q=H.store.leaseOf(Q.id);if(T&&q!==void 0&&q.holder.length>0){if(q.holder!==H.actor)return J0("conflict.claimed",`${Q.id} is claimed by ${q.holder}; only the owner can close it`,4,`myc close ${Q.id} --as ${q.holder}`);if(!H.store.closeClaimed(Q.id,q.holder,q.epoch))return J0("conflict.claimed",`${Q.id}: ownership lost (stale epoch)`,4)}else try{H.store.updateNode(Q.id,{status:"closed",closed_at:B})}catch(E){return C0(E)}let j={},O=f(Z,"reason");if(O!==void 0)j.reason=O;if(J!==void 0)j.verify=J;if(U!==void 0)j.outcome=U;if(L.canonicalModel!==void 0)j.model=L.canonicalModel;let A=Z.flags["cost-in"],R=Z.flags["cost-out"],D=Z.flags.retries;if(typeof A==="number")j.cost_in=A;if(typeof R==="number")j.cost_out=R;if(typeof D==="number")j.retries=D;if(Object.keys(j).length>0)try{H.store.updateNode(Q.id,{attrs:{outcome:j}})}catch(E){return C0(E)}if(K!==void 0){let E=R0(H,K);if(!E.ok)return E.failure;try{H.store.addEdge(Q.id,"duplicates",E.node.id)}catch(b){return C0(b)}}let F=[];for(let E of H.store.edgesFrom(Q.id,"blocks")){let b=H.store.getNode(E.dst);if(b!==void 0&&b.status==="open"&&b.open_blockers===0&&b.anc_blockers===0)F.push(b.id)}let P;if(W!==void 0&&L.plan.kind!=="none"){let E=await aE(Z,H,Q,L.plan,W,V,X);if("ok"in E)Z.warn("attribution.failed",`outcome not recorded: ${E.msg}`),P={recorded:!1,skipped:E.msg};else P=E}else if(L.plan.kind==="none"){let E=L.plan.skipped??(W!==void 0?"could not record the outcome":void 0);if(L.plan.warn!==void 0)Z.warn(...L.plan.warn);if(E!==void 0)P={recorded:!1,skipped:E}}let _=q!==void 0&&q.holder.length>0?q.holder:H.actor,M={id:Q.id,status:"closed",closed_by:_,...T?{in_progress_ms:B-Q.updated_at}:{},unblocked:F,...Object.keys(j).length>0?{outcome:j}:{},...P!==void 0?{attribution:P}:{},took_ms:S8(Y)};return{ok:!0,data:M,meta:{took_ms:M.took_ms}}}finally{H.close()}},renderHuman:b00}}var R9,_9,cE,y00,iE,nE;var L8=v(()=>{o();B4();V0();w5();k6();UK();j0();R9={task:{kind:"task",type:"task"},bug:{kind:"task",type:"bug",defaultPriority:1},epic:{kind:"task",type:"epic"},chore:{kind:"task",type:"chore"},memory:{kind:"note"},decision:{kind:"note",type:"decision"},document:{kind:"doc"},skill:{kind:"skill"},message:{kind:"message"}};_9={name:"as",value:"string",description:"actor for the record and claim (default $MYC_ACTOR/$USER)"},cE=[{name:"kind",value:"string",description:"task|bug|epic|memory|decision|document|skill|message"},{name:"priority",short:"p",value:"string",description:"P0|P1|P2|P3 or 0|1|2|3"},{name:"body",short:"b",value:"string",description:"node body; '-' reads stdin"},{name:"tag",value:"string",list:!0,description:"comma-separated tags"},{name:"parent",value:"string",description:"parent node id"},{name:"dep",value:"string",list:!0,description:"comma-separated blocker ids"},{name:"anchor",value:"string",description:"bind an anchor file[:<a>-<b>]; a directory, a binary or secret-named file is refused before anything is written; a missing file or a path outside the root stays an intent (WARN)"},{name:"reply-to",value:"string",description:"reply to this node: adds a replies_to edge"},{name:"assign",value:"string",description:"assignee"},{name:"estimate",value:"string",description:"estimate, e.g. 30m, 2h, 1d"},{name:"acl",value:"string",description:"private|team|restricted|agent"},{name:"repo",value:"string",description:"repository scope (S59); default is derived from the current directory"},_9];y00={flag:"",estimate:" (estimate)",capped:" (1-day cap)",floor:" (minimum)",default:""};iE=["tests","review","human","none"],nE=["done","wontfix","duplicate","superseded"]});var sE={};s(sE,{createMoveCommand:()=>l00});import{resolve as h00}from"path";function A7($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function m00($){if($.code==="notfound")return A7("notfound.node",$.msg,3);if($.code==="same_workspace")return A7("usage.same_workspace",$.msg,2);if($.code==="chain_truncated")return A7("precond.chain_truncated",$.msg,5);if($.code==="cross_boundary_parent")return A7("precond.cross_boundary_parent",$.msg,5,"unblock the epic, or move the whole subtree, or remove the parent edge");if($.code==="leased")return A7("precond.leased",$.msg,5,"wait for the lease to end, or myc release");let X=$.crossing.slice(0,5).map((Z)=>`${Z.src} blocks ${Z.dst}`).join("; ");return A7("precond.cross_boundary",`${$.msg}: ${X}${$.crossing.length>5?"\u2026":""}`,5,"--with-blockers moves the whole connected piece, --dry-run shows its size")}function u00($){let X=$,Z=[],Y=X.dry_run?"dry-run: ":"";if(Z.push(`${Y}${X.id}: ${X.from===""?"(no slug)":X.from} \u2192 ${X.to===""?"(no slug)":X.to} (${X.to_dir})`),Z.push(` moving ${X.members.length} ${X.members.length===1?"node":"nodes"}, ${X.edges.length} ${X.edges.length===1?"edge":"edges"}, ${X.ops} history ${X.ops===1?"operation":"operations"}`+(X.expanded?" (set expanded along blocks)":"")),X.members.length>1)Z.push(` nodes: ${X.members.join(", ")}`);if(X.staying.length>0)Z.push(` staying in the source: ${X.staying.length} ${X.staying.length===1?"edge":"edges"} \u2014 `+"the other end is not moving, the tombstone holds them");if(!X.dry_run)Z.push(` applied ${X.applied??0}, duplicates ${X.duplicate??0}, moves minted ${X.minted??0}`+(X.resumed===!0?" (resumed an interrupted move)":""));return Z.push(`done in ${X.took_ms} ms`),`${Z.join(`
|
|
3385
3385
|
`)}
|
|
3386
|
-
`}function
|
|
3386
|
+
`}function l00($=$0){return{name:"move",summary:"move a task to another workspace, keeping its identity and oplog",flags:[{name:"to",value:"string",description:"target workspace directory"},{name:"dry-run",description:"print the move set, change nothing"},{name:"with-blockers",description:"also move every task connected by live blocks edges"},{name:"pending",description:"list arrivals whose move never finished here"}],help:"The node keeps its id and its whole oplog: operations are copied verbatim (same op_id, site_id and hlc), so a second run is a no-op and a third party replicating both workspaces converges through ordinary per-field LWW. The move itself is two plain set "+"operations \u2014 scope and attrs.moved_from \u2014 and no new operation kind. The source keeps a "+"tombstone row: edges that stayed behind still point at it, and hard deletion would cascade them away silently. Refuses while a live blocks edge would cross the boundary (open_blockers is materialised by triggers inside one database), while the node would leave a blocked ancestor behind (anc_blockers is materialised the same way), or while the node is under a live lease (leases do not replicate).",handler:async(X)=>{let Z=performance.now(),Y=await $.openStore(X);if(!Y.ok)return Y.failure;let z=Y.handle,J;try{if(K0(X,"pending")){let L=LJ(z.driver,z.scope);return{ok:!0,data:{scope:z.scope,stranded:L,took_ms:Math.round(performance.now()-Z)}}}let U=X.args[0];if(U===void 0)return A7("usage.id","task id required: myc move <id> --to <dir>",2);let K=f(X,"to");if(K===void 0)return A7("usage.to","target directory required: --to <dir>",2);let W=R0(z,U);if(!W.ok)return W.failure;let V=await wH(h00(K),z.actor);if(!V.ok)return V.failure;J=V.handle;let G=QJ(z,W.node.id,z.scope,J.scope,{withBlockers:K0(X,"with-blockers")});if(!G.ok)return m00(G);let H=K0(X,"dry-run"),N={id:W.node.id,from:G.from,to:G.to,to_dir:J.wsDir,dry_run:H,members:G.members,edges:G.edges,staying:G.staying,expanded:G.expanded};if(H)return{ok:!0,data:{...N,ops:G.ops.length,took_ms:Math.round(performance.now()-Z)}};let Q;try{Q=NJ(z,J,G)}catch(L){let B=L instanceof Error?L.message:String(L);return A7("precond.move_ingest",B,5,"re-running myc move ... finishes it")}if(Q.staying.length>0)X.warn("move.edges_stayed",`${Q.staying.length} ${Q.staying.length===1?"edge":"edges"} stayed in the source: the other end did not move`);return{ok:!0,data:{...N,ops:Q.ops,applied:Q.applied,duplicate:Q.duplicate,minted:Q.minted,resumed:Q.resumed,took_ms:Math.round(performance.now()-Z)}}}finally{J?.close(),z.close()}},renderHuman:(X)=>{let Z=X;if(Array.isArray(Z.stranded)){let Y=Z.stranded;if(Y.length===0)return`no unfinished moves
|
|
3387
3387
|
`;return`${Y.map((z)=>`${z.id} arrived with scope '${z.scope}' \u2014 move not finished`).join(`
|
|
3388
3388
|
`)}
|
|
3389
|
-
`}return
|
|
3389
|
+
`}return u00(X)}}}var rE=v(()=>{n0();V0();j0()});var Yv={};s(Yv,{createShowCommand:()=>t00});import{existsSync as Xv,readFileSync as p00}from"fs";import{join as c00}from"path";function i00($,X){return e6(g4($.driver,$.store),{id:X.id,head_id:X.head_id,hlc:X.hlc,site_id:X.site_id},GX+1)}function n00($,X,Z){let Y=$.store.getNode(X,!0),z=Y?.attrs.absorb,J=typeof z==="object"&&z!==null&&!Array.isArray(z)?z:void 0,U=J?.class,K=J?.reason;return{id:X,status:Y?.status??"unknown",created_at:Y?.created_at??0,current:X===Z,...typeof U==="string"?{absorb_class:U}:{},...typeof K==="string"&&K.length>0?{reason:K}:{}}}function dY($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function eE($){if($.status==="closed"&&$.closed_at!==null)return`closed ${d0($.closed_at)}`;return $.status}function $v($,X){let Z=$.store.getNode(X);if(Z===void 0)return`${X} (deleted)`;let Y=[Z.id];if(Z.kind==="task")Y.push(g0(Z.priority));if(Y.push(m6(Z),Z.status),A8(Z.attrs))Y.push(u7(Z.status)?"reviewed":"unconfirmed");if(Z.assignee.length>0)Y.push(`@${Z.assignee}`);return Y.push(Z.title),Y.join(" ")}function a00($,X){let Z=X.attrs.moved,Y=typeof Z==="object"&&Z!==null&&!Array.isArray(Z)?Z.from:void 0,z;if(typeof Y==="string"&&Y.length>0){let W=E8(Y);z=W===void 0?Y:`${BY($,W.path)}${W.whole?"":`:${W.start===W.end?W.start:`${W.start}-${W.end}`}`}`}let J;try{J=$.driver.database.query(o00).get(X.id)??void 0}catch{J=void 0}let U=z!==void 0?{moved_from:z}:{};if(J!==void 0){let W=H8(J.repo_id,J.path),V=c00($.wsDir,W),G=$.worktree!==void 0?A6($.worktree,V):V;return{ref:{path:BY($,W),start:J.s,end:J.e,...J.symbol.length>0?{symbol:J.symbol}:{},state:J.state,node_id:X.id,...J.state==="drifted"?{drift:J.drift}:{},...U},file:Xv(G)?G:V}}let K=E8(X.title);return{ref:{...K!==void 0?{path:K.path,start:K.start,end:K.whole?K.start:K.end}:{},state:X.status,node_id:X.id,...U,untracked:!0}}}function s00($,X,Z,Y,z){let J=[],U=[],K=[],W=[],V=[],G=new Map,H;for(let _ of $.store.edgesFrom(X.id,"parent")){let M=$.store.getNode(_.dst);if(M!==void 0)H={id:M.id,title:M.title};break}let N=[];for(let _ of $.store.edgesTo(X.id,"parent")){let M=$.store.getNode(_.src);if(M!==void 0)N.push({id:M.id,status:M.status,priority:M.priority,title:M.title})}N.sort((_,M)=>_.priority-M.priority||_.id.localeCompare(M.id));let Q=[];for(let _ of $.store.edgesTo(X.id,"replies_to")){let M=$.store.getNode(_.src);if(M===void 0)continue;let E=M.attrs.external_created_at;Q.push({id:M.id,actor:M.actor,at:typeof E==="number"&&Number.isFinite(E)?E:M.updated_at,title:M.title,replies:$.store.edgesTo(M.id,"replies_to").length})}Q.sort((_,M)=>_.at-M.at||_.id.localeCompare(M.id));for(let _ of $.store.edgesTo(X.id,"blocks")){let M=$.store.getNode(_.src);J.push({id:_.src,status:M?.status??"unknown",closed_at:M?.closed_at??null})}for(let _ of $.store.edgesFrom(X.id))if(_.type==="blocks"){let M=$.store.getNode(_.dst);U.push({id:_.dst,status:M?.status??"unknown",closed_at:M?.closed_at??null})}else if(_.type==="touches"){let M=$.store.getNode(_.dst);if(M!==void 0){let E=a00($,M);if(V.push(E.ref),E.file!==void 0)G.set(E.ref,E.file)}}else if(_.type==="contradicts")W.push({type:"contradicts",id:_.dst});else if(_.type==="relates"||_.type==="derived_from"||_.type==="duplicates"||_.type==="supersedes")K.push({type:_.type==="relates"?"relates-to":_.type==="derived_from"?"derived-from":_.type,id:_.dst});let L=new Set(W.map((_)=>_.id));for(let _ of $.store.edgesTo(X.id,"contradicts"))if(!L.has(_.src))L.add(_.src),W.push({type:"contradicts",id:_.src});W.sort((_,M)=>_.id<M.id?-1:_.id>M.id?1:0);let B=X.attrs.anchors;if(Array.isArray(B)){for(let _ of B)if(typeof _==="object"&&_!==null){let M=_;V.push({path:String(M.path??""),start:typeof M.start==="number"?M.start:1,end:typeof M.end==="number"?M.end:1,state:String(M.state??"pending")})}}let{graph:T,truncated:q}=i00($,X),j=T.head(X.id),O=j===X.id?void 0:$.store.getNode(j,!0),A=T.heads(X.id),R=T.chain(X.id).filter((_)=>_!==j&&(T.node(_)?.head_id??null)===null),D=$.store.leaseOf(X.id),F=X.kind==="task"?$.store.blockingAncestors(X.id).map((_)=>({id:_.id,title:_.title,open_blockers:_.open_blockers})):[],P={id:X.id,kind:X.kind,type:m6(X),title:X.title,body:X.body,status:X.status,priority:X.priority,assignee:X.assignee,acl:X.acl,created_at:TX(X),updated_at:w7(X),...typeof X.attrs.external_ref==="string"?{imported_at:X.created_at}:{},...A8(X.attrs)?{review:AX}:{},...A8(X.attrs)&&typeof X.attrs[m7]==="string"?{review_reason:X.attrs[m7]}:{},blocked_by:J,blocks:U,...F.length>0?{blocked_via:F}:{},...H!==void 0?{parent:H}:{},...N.length>0?{children:N}:{},...Q.length>0?{thread:Q}:{},links:K,contradicts:W,...typeof X.attrs[i7]==="string"&&X.scope!==$.scope?{moved:{to:X.scope,from:String(X.attrs[i7])}}:{},current:j===X.id,...O!==void 0?{head:{id:O.id,title:O.title,status:O.status}}:{},...A.length>1?{forked:[...A]}:{},...R.length>0?{stale:R}:{},...z==="full_history"?{chain:T.chain(X.id).map((_)=>n00($,_,j)),...q?{chain_truncated:!0}:{}}:{},anchors:V,tags:SX(X),...N7(X)!==void 0?{estimate_min:N7(X)}:{},...D!==void 0&&D.holder.length>0?{lease:{holder:D.holder,expires:D.expires}}:{}};if(Z>=1){let _=[];for(let M of[...J,...U])_.push($v($,M.id));for(let M of K)_.push($v($,M.id));if(_.length>0)P.related=_}if(Y){let _=[];for(let M of V){let E=M.node_id!==void 0?G.get(M):M.path;if(E===void 0||M.path===void 0||M.state==="lost"||!Xv(E))continue;try{let b=p00(E,"utf8").split(`
|
|
3390
3390
|
`),k=Math.max(1,M.start??1),y=Math.min(b.length,Math.max(k,M.end??k),k+199);_.push({path:M.path,start:k,end:y,text:b.slice(k-1,y).join(`
|
|
3391
|
-
`)})}catch{}}if(_.length>0)P.sources=_}return P}function Zv($,X){let Z=[`${$.id} ${$.type}`];if($.kind==="task")Z.push(g0($.priority));if(Z.push($.status),$.assignee.length>0)Z.push(`@${$.assignee}`);if(Z.push(`created ${d0($.created_at)}`),Z.push(d0($.updated_at)===d0(X)?`updated ${M6($.updated_at).slice(0,5)}Z`:`updated ${d0($.updated_at)}`),$.imported_at!==void 0)Z.push(`imported ${d0($.imported_at)}`);Z.push(`acl ${$.acl}`);let Y=[Z.join(" "),$.title];if($.review!==void 0)Y.push(u7($.status)?`review ${$.status==="retracted"?"rejected":$.status} compaction candidate (status ${$.status})`+($.review_reason!==void 0&&$.review_reason.length>0?`: ${$.review_reason}`:""):`review unconfirmed compaction candidate (state ${$.review}) \u2014 `+`recall, search and prime do not return it \xB7 myc review confirm ${$.id} | myc review reject ${$.id} --reason`);if($.body!==null&&$.body.trim().length>0)Y.push(tE,$.body.trimEnd(),tE);let z=[];if($.blocked_by.length>0)z.push(`blocked-by ${$.blocked_by.map((U)=>`${U.id} (${eE(U)})`).join(", ")}`);if($.blocks.length>0)z.push(`blocks ${$.blocks.map((U)=>
|
|
3392
|
-
`))Y.push(` ${K}`)}return Y}function
|
|
3391
|
+
`)})}catch{}}if(_.length>0)P.sources=_}return P}function Zv($,X){let Z=[`${$.id} ${$.type}`];if($.kind==="task")Z.push(g0($.priority));if(Z.push($.status),$.assignee.length>0)Z.push(`@${$.assignee}`);if(Z.push(`created ${d0($.created_at)}`),Z.push(d0($.updated_at)===d0(X)?`updated ${M6($.updated_at).slice(0,5)}Z`:`updated ${d0($.updated_at)}`),$.imported_at!==void 0)Z.push(`imported ${d0($.imported_at)}`);Z.push(`acl ${$.acl}`);let Y=[Z.join(" "),$.title];if($.review!==void 0)Y.push(u7($.status)?`review ${$.status==="retracted"?"rejected":$.status} compaction candidate (status ${$.status})`+($.review_reason!==void 0&&$.review_reason.length>0?`: ${$.review_reason}`:""):`review unconfirmed compaction candidate (state ${$.review}) \u2014 `+`recall, search and prime do not return it \xB7 myc review confirm ${$.id} | myc review reject ${$.id} --reason`);if($.body!==null&&$.body.trim().length>0)Y.push(tE,$.body.trimEnd(),tE);let z=[];if($.blocked_by.length>0)z.push(`blocked-by ${$.blocked_by.map((U)=>`${U.id} (${eE(U)})`).join(", ")}`);if($.blocks.length>0)z.push(`blocks ${$.blocks.map((U)=>d00.has(U.status)?`${U.id} (${eE(U)})`:U.id).join(", ")}`);if($.moved!==void 0)Y.push(`moved to workspace '${$.moved.to===""?"(no slug)":$.moved.to}' \u2014 `+"a tombstone stays here, holding the edges that did not move");if(z.length>0)Y.push(`deps ${z.join(" \xB7 ")}`);if($.blocked_via!==void 0&&$.blocked_via.length>0){let U=$.blocked_via.map((K)=>`${K.id} (${K.open_blockers})`).join(", ");Y.push(`waiting blocker on ancestor: ${U} \u2014 so not in ready`)}if($.parent!==void 0)Y.push(`part of ${$.parent.id} ${$.parent.title}`);if($.children!==void 0&&$.children.length>0){let U=$.children.filter((V)=>V.status==="closed").length,K=$.children.filter((V)=>V.status==="cancelled").length,W=K>0?`, cancelled ${K}`:"";Y.push(`children ${U} of ${$.children.length} closed${W}`);for(let V of $.children){let G=V.status==="closed"?"\xD7":V.status==="cancelled"?"\u2014":"\xB7";Y.push(` ${G} ${V.id} ${g0(V.priority)} ${V.status.padEnd(11)} ${V.title}`)}}if($.thread!==void 0&&$.thread.length>0){Y.push(`thread ${$.thread.length}`);for(let U of $.thread){let K=U.replies>0?` (+${U.replies})`:"";Y.push(` \xB7 ${U.id} ${U.actor} ${U.title}${K}`)}}if($.links.length>0)Y.push(`links ${$.links.map((U)=>`${U.type} ${U.id}`).join(" \xB7 ")}`);if($.head!==void 0)Y.push(`current ${$.head.id} ${$.head.title}`);if($.forked!==void 0)Y.push(`fork ${$.forked.join(", ")} \u2014 two branches merged; chosen as current: ${$.forked[0]}`);if($.stale!==void 0)Y.push(`WARNING head_id not set on ${$.stale.join(", ")}: retrieval will return a stale version as current`);if($.contradicts.length>0)Y.push(`contradicts ${$.contradicts.map((U)=>U.id).join(", ")}`);if($.chain!==void 0){Y.push(`history ${$.chain.length} ${$.chain.length===1?"version":"versions"}${$.chain_truncated===!0?" (truncated by the read budget)":""}`);for(let U of $.chain){let K=U.current?"\u2192":"\xB7",W=U.reason!==void 0?` ${U.absorb_class??""} ${U.reason}`.trimEnd():"";Y.push(` ${K} ${U.id} ${d0(U.created_at)} ${U.status.padEnd(11)}${W}`)}}if($.anchors.length>0){let U=$.anchors.map((K)=>{let W=K.start===K.end?`${K.start}`:`${K.start}-${K.end}`;if(K.node_id===void 0)return`${K.path}:${W} @\u2014 ${K.state}`;let V=K.state==="drifted"&&K.drift!==void 0?` ${K.drift.toFixed(2)}`:"",G=K.path!==void 0?`${K.path}:${W}`:"(position unknown)",H=K.symbol!==void 0?` (${K.symbol})`:"",N=[`${G}${H} ${K.state}${V}`,K.node_id];if(K.moved_from!==void 0)N.push(`moved from ${K.moved_from}`);if(K.untracked===!0)N.push("not tracked on this machine");return N.join(" \xB7 ")});Y.push(`anchors ${U[0]}`);for(let K of U.slice(1))Y.push(` ${K}`)}let J=[];if($.tags.length>0)J.push(`tags ${$.tags.join(", ")}`);if($.estimate_min!==void 0)J.push(`est ${Q7($.estimate_min)}`);if(J.length>0)Y.push(`notes ${J.join(" \xB7 ")}`);if($.lease!==void 0)Y.push(`lease ${$.lease.holder} \xB7 ${Z4($.lease.holder,$.lease.expires,X)}`);else if($.kind==="task"&&$.status==="in_progress")Y.push(`lease ${Z4("",0,X)}`);if($.related!==void 0){Y.push("related");for(let U of $.related)Y.push(` ${U}`)}if($.sources!==void 0)for(let U of $.sources){Y.push(`source ${U.path}:${U.start}-${U.end}`);for(let K of U.text.split(`
|
|
3392
|
+
`))Y.push(` ${K}`)}return Y}function r00($){let X=$,Z=Date.now();if(X.fields!==void 0){let z=X.fields.filter((K)=>!(K in KK));if(z.length>0)return`unknown fields: ${z.join(", ")}
|
|
3393
3393
|
`;let J=X.nodes.map((K)=>X.fields.map((W)=>KK[W](K))),U=[];for(let K of J)K.forEach((W,V)=>{U[V]=Math.max(U[V]??0,W.length)});return`${J.map((K)=>K.map((W,V)=>V===K.length-1?W:W.padEnd(U[V])).join(" ").trimEnd()).join(`
|
|
3394
3394
|
`)}
|
|
3395
3395
|
`}let Y=[];for(let z of X.nodes)Y.push(...Zv(z,Z));return`${Y.join(`
|
|
3396
3396
|
`)}
|
|
3397
|
-
`}function
|
|
3397
|
+
`}function t00($=$0){return{name:"show",summary:"show a node (batch via commas, --field for projection)",remote:!0,flags:[{name:"field",value:"string",list:!0,description:"comma-separated fields for batch projection"},{name:"depth",value:"number",description:"0 (default) | 1 \u2014 one-line summaries of neighbours"},{name:"source",description:"read the code at the node's anchors, lost ones excluded (up to 200 lines each)"},{name:"chain",description:"full_history: print the whole version chain (\xA76.3)"}],handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0)return dY("usage.invalid","id required: myc show <id>[,<id>\u2026]",2);let z=X.flags.depth,J=typeof z==="number"?z:0;if(J!==0&&J!==1)return dY("usage.invalid","--depth takes 0 or 1",2);let U=f(X,"field"),K=U!==void 0?U.split(",").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):void 0;if(K!==void 0&&!K.includes("id"))K=["id",...K];if(K!==void 0){let Q=K.filter((L)=>!(L in KK));if(Q.length>0)return dY("usage.invalid",`unknown fields: ${Q.join(", ")}; allowed: ${Object.keys(KK).join(", ")}`,2)}let W=X.flags.source===!0,V=X.flags.chain===!0,G=await $8(X,async(Q)=>{let L=[W?"--source":"",V?"--chain":"",K!==void 0?"--field":"",J===1?"--depth 1":""].filter((k)=>k!=="");if(L.length>0)return dY("precond.no_remote",`the server does not answer ${L.join(", ")} yet`,5);if(Y.includes(","))return dY("precond.no_remote","batch show is not supported on a server yet",5);let B=await Q.getNode(Y.trim()),T=B.data,q=T.attrs??{},j=String(T.id??Y.trim()),O=Array.isArray(T.edges)?T.edges:[],A=(k,y)=>({id:String(y?k.src:k.dst),status:String((y?k.src_status:k.dst_status)??"open"),closed_at:(y?k.src_closed_at:k.dst_closed_at)===null?null:Number(y?k.src_closed_at:k.dst_closed_at)}),R=O.filter((k)=>String(k.type)==="blocks"&&String(k.dst)===j).map((k)=>A(k,!0)),D=O.filter((k)=>String(k.type)==="blocks"&&String(k.src)===j).map((k)=>A(k,!1)),F=O.filter((k)=>String(k.type)!=="blocks").map((k)=>({type:String(k.type),id:String(k.src)===j?String(k.dst):String(k.src)})),P=T.lease_holder===null?"":String(T.lease_holder??""),_=typeof q.type==="string"?q.type:String(T.kind??""),M=Array.isArray(q.tags)?q.tags.map(String):[],E=typeof q.estimate_min==="number"?q.estimate_min:void 0;return{ok:!0,data:{id:j,kind:String(T.kind??""),type:_,title:String(T.title??""),body:T.body===null?null:String(T.body??""),status:String(T.status??""),priority:Number(T.priority??2),assignee:String(T.assignee??""),acl:String(T.acl??"team"),created_at:Number(T.created_at??0),updated_at:Number(T.updated_at??0),blocked_by:R,blocks:D,links:F,anchors:[],tags:M,contradicts:[],current:!0,...E===void 0?{}:{estimate_min:E},...P===""?{}:{lease:{holder:P,expires:Number(T.lease_expires??0)}}},meta:{...B.meta,remote:Q.ws}}});if(G!==void 0)return G;let H=await $.openStore(X);if(!H.ok)return H.failure;let N=H.handle;try{let Q=[];for(let B of Y.split(",").map((T)=>T.trim()).filter((T)=>T.length>0)){let T=R0(N,B);if(!T.ok)return T.failure;let q=V?"full_history":zV(T.node.attrs);Q.push(s00(N,T.node,J,W,q))}let L={nodes:Q,...K!==void 0?{fields:K}:{},depth:J,source:W,history:V?"full_history":"follow",took_ms:Math.round(performance.now()-Z)};return{ok:!0,data:Q.length===1&&K===void 0?Q[0]:L,meta:{took_ms:L.took_ms,count:Q.length}}}finally{N.close()}},renderHuman:(X,Z)=>{if(typeof X==="object"&&X!==null&&"nodes"in X)return r00(X);return`${Zv(X,Date.now()).join(`
|
|
3398
3398
|
`)}
|
|
3399
|
-
`}}}var tE,
|
|
3400
|
-
FROM anchors WHERE node_id = ?1`,KK;var zv=v(()=>{o();DY();V0();w5();j0();k6();L8();tE="\u2500".repeat(72);
|
|
3399
|
+
`}}}var tE,d00,o00=`SELECT repo_id, path, span_start AS s, span_end AS e, state, drift, symbol
|
|
3400
|
+
FROM anchors WHERE node_id = ?1`,KK;var zv=v(()=>{o();DY();V0();w5();j0();k6();L8();tE="\u2500".repeat(72);d00=new Set(["closed","cancelled","superseded","retracted"]);KK={id:($)=>$.id,title:($)=>$.title,status:($)=>$.status,assignee:($)=>$.assignee.length>0?$.assignee:"\u2014",priority:($)=>g0($.priority),kind:($)=>$.type,created:($)=>d0($.created_at),updated:($)=>d0($.updated_at),acl:($)=>$.acl,tags:($)=>$.tags.join(",")}});var Jv={};s(Jv,{createListCommand:()=>Y$0});function I9($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function $$0($){return{id:$.id,priority:$.priority,kind:$.kind,type:m6($),status:$.status,assignee:$.assignee,title:$.title,updated_at:$.updated_at,created_at:$.created_at,tags:SX($)}}function X$0($){if(typeof $==="number")return`${$}
|
|
3401
3401
|
`;let X=$,Z=[],Y=[0,0,0,0,0],z=X.rows.map((J)=>{let U=J.assignee.length>0?`@${J.assignee}`:"free",K=J.kind==="task"?g0(J.priority):"";return[J.id,K,J.type,J.status,U,J.title].filter((V,G)=>G!==1||K!=="")});for(let J of z)J.forEach((U,K)=>{if(K<Y.length)Y[K]=Math.max(Y[K],U.length)});for(let J of z)Z.push(J.map((U,K)=>K===J.length-1?U:U.padEnd(Y[K]??U.length)).join(" ").trimEnd());return Z.push(`${X.shown} of ${X.total} \xB7 ${X.took_ms} ms`),`${Z.join(`
|
|
3402
3402
|
`)}
|
|
3403
|
-
`}function
|
|
3403
|
+
`}function Z$0($,X){switch(X){case"priority":$.sort((Z,Y)=>Z.priority-Y.priority||Z.updated_at-Y.updated_at||Z.id.localeCompare(Y.id));break;case"created":$.sort((Z,Y)=>Y.created_at-Z.created_at||Z.id.localeCompare(Y.id));break;case"status":$.sort((Z,Y)=>Z.status.localeCompare(Y.status)||Z.priority-Y.priority||Z.id.localeCompare(Y.id));break;default:$.sort((Z,Y)=>Y.updated_at-Z.updated_at||Z.id.localeCompare(Y.id))}}function Y$0($=$0){return{name:"list",summary:"list nodes with filters",remote:!0,flags:[{name:"kind",value:"string",list:!0,description:"comma-separated kinds (task,bug,epic,memory,\u2026)"},{name:"status",value:"string",list:!0,description:"comma-separated statuses"},{name:"priority",value:"string",list:!0,description:"P0|P1|P2|P3 or 0|1|2|3 (comma ok)"},{name:"tag",value:"string",description:"must carry this tag"},{name:"assignee",value:"string",description:"assignee, or 'free'"},{name:"acl",value:"string",description:"acl mode"},{name:"since",value:"string",description:"updated after: ISO date or age (2d, 6h)"},{name:"until",value:"string",description:"updated before: ISO date or age"},{name:"sort",value:"string",description:"priority|updated|created|status (default updated)"},{name:"fields",value:"string",list:!0,description:"comma-separated columns (json/ndjson shape)"},{name:"n",short:"n",value:"number",description:"limit (default 20)"},{name:"offset",value:"number",description:"skip first N rows"},{name:"count",description:"print only the count"}],handler:async(X)=>{let Z=performance.now(),Y=f(X,"kind")?.split(",").map((B)=>B.trim()).filter((B)=>B.length>0);if(Y!==void 0){let B=Y.filter((T)=>!(T in oY));if(B.length>0)return I9("usage.invalid",`unknown --kind '${B.join(",")}'; allowed: ${Object.keys(oY).join(", ")}`,2)}let z=[],J=f(X,"priority");if(J!==void 0)for(let B of J.split(",")){let T=L7(B);if(T===void 0)return I9("usage.invalid",`invalid priority '${B}'; allowed: P0..P3 or 0..3`,2);z.push(T)}let U=f(X,"sort")??"updated";if(!["priority","updated","created","status"].includes(U))return I9("usage.invalid",`invalid --sort '${U}'`,2);let K=(B,T)=>{let q=P$(B);if(q!==void 0)return T?Date.now()-q:Date.now()-q;let j=Date.parse(B);return Number.isNaN(j)?void 0:j},W,V,G=f(X,"since");if(G!==void 0){if(W=K(G,!0),W===void 0)return I9("usage.invalid",`invalid --since '${G}'`,2)}let H=f(X,"until");if(H!==void 0){if(V=K(H,!1),V===void 0)return I9("usage.invalid",`invalid --until '${H}'`,2)}let N=await $8(X,async(B)=>{let T=["tag","assignee","acl","until","sort","fields"].filter((D)=>f(X,D)!==void 0);if(T.length>0)return I9("precond.no_remote",`the server does not filter by ${T.join(", ")} yet`,5);let q=await B.listNodes({kind:Y?.length===1?oY[Y[0]].kind:void 0,status:f(X,"status"),since:W,limit:typeof X.flags.n==="number"?X.flags.n:void 0,offset:typeof X.flags.offset==="number"?X.flags.offset:void 0}),j=q.data;if(X.flags.count===!0)return{ok:!0,data:Number(q.meta.total??j.length),meta:{remote:B.ws}};let O=j.map((D)=>{let F=D.attrs??{},P=[];try{P=Array.isArray(F.tags)?F.tags.map(String):[]}catch{P=[]}let _=String(D.kind??"");return{id:String(D.id??""),priority:Number(D.priority??2),kind:_,type:typeof F.type==="string"?F.type:_,status:String(D.status??""),assignee:String(D.assignee??""),title:String(D.title??""),updated_at:Number(D.updated_at??0),created_at:Number(D.created_at??0),tags:P}}),A=Number(q.meta.total??O.length),R={rows:O,shown:O.length,total:A,truncated:O.length<A,took_ms:Math.round((performance.now()-Z)*100)/100};return{ok:!0,data:R,meta:{...q.meta,remote:B.ws,took_ms:R.took_ms}}});if(N!==void 0)return N;let Q=await $.openStore(X);if(!Q.ok)return Q.failure;let L=Q.handle;try{let B=Y??e00,T=new Set,q=new Map;for(let y of B){let g=oY[y];if(T.add(g.kind),g.type!==void 0){let S=q.get(g.kind)??new Set;S.add(g.type),q.set(g.kind,S)}}let j=B.every((y)=>oY[y].type!==void 0),O=f(X,"status")?.split(",").map((y)=>y.trim()).filter((y)=>y.length>0),A=f(X,"tag"),R=f(X,"assignee"),D=f(X,"acl"),F=[],P=!1;for(let y of T){let g=L.store.listNodes(L.scope,y,WK+1);if(g.length>WK)P=!0;for(let S of g.slice(0,WK)){if(j){let w=q.get(S.kind);if(w!==void 0&&!w.has(m6(S)))continue}if(O!==void 0&&!O.includes(S.status))continue;if(z.length>0&&!z.includes(S.priority))continue;if(A!==void 0&&!SX(S).includes(A))continue;if(R!==void 0){if(R==="free"){if(S.assignee.length>0)continue}else if(S.assignee!==R)continue}if(D!==void 0&&S.acl!==D)continue;if(W!==void 0&&S.updated_at<W)continue;if(V!==void 0&&S.updated_at>V)continue;F.push(S)}}if(P)X.warn("list.truncated",`results cut to ${WK} nodes per kind; narrow the filters`);let _=F.map($$0);Z$0(_,U);let M=_.length;if(X.flags.count===!0)return{ok:!0,data:M,meta:{took_ms:Math.round(performance.now()-Z),count:M}};let E=t(X,"n")??20,b=t(X,"offset")??0;_=_.slice(b,b+E);let k={rows:_,shown:_.length,total:M,truncated:P,took_ms:Math.round(performance.now()-Z)};return{ok:!0,data:k,meta:{took_ms:k.took_ms,count:_.length}}}finally{L.close()}},renderHuman:X$0}}var oY,e00,WK=1000;var Uv=v(()=>{V0();w5();j0();L8();oY={task:{kind:"task",type:"task"},bug:{kind:"task",type:"bug"},epic:{kind:"task",type:"epic"},chore:{kind:"task",type:"chore"},memory:{kind:"note"},note:{kind:"note"},decision:{kind:"note",type:"decision"},document:{kind:"doc"},doc:{kind:"doc"},fragment:{kind:"fragment"},session:{kind:"session"},message:{kind:"message"},entity:{kind:"entity"},anchor:{kind:"anchor"},skill:{kind:"skill"}},e00=["task","note","doc","fragment","session","message","entity","anchor","skill"]});var Lv={};s(Lv,{createDepCommand:()=>hB});function g8($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function z$0($){if($ instanceof p0&&$.code==="closure.cycle")return g8("conflict.dep_cycle",`dependency cycle: ${$.message}`,4);return C0($)}function Kv($,X,Z){if($==="blocks")return{src:X,dst:Z};if($==="blocked-by")return{src:Z,dst:X};return}function Wv($){let X=$;if(X.removed===!0){let Y=X.back_ready===!0?` (${X.back_ready_id} ready again)`:"";return`${X.type} ${X.src} \u2192 ${X.dst} removed${Y}
|
|
3404
3404
|
${X.took_ms} ms
|
|
3405
3405
|
`}let Z=X.left_ready===!0?` (${X.left_ready_id} left ready)`:"";return`${X.from_label} ${X.type==="blocks"?"blocks":"blocked-by"} ${X.type==="blocks"?X.dst:X.src}${Z}
|
|
3406
3406
|
${X.took_ms} ms
|
|
3407
|
-
`}function
|
|
3407
|
+
`}function J$0($){return{name:"add",summary:"add a dependency: dep add <from> <blocks|blocked-by> <to>",handler:async(X)=>{let Z=performance.now(),[Y,z,J]=X.args;if(Y===void 0||z===void 0||J===void 0)return g8("usage.invalid","usage: myc dep add <from> <blocks|blocked-by> <to>",2);if(Kv(z,Y,J)===void 0)return g8("usage.invalid",`invalid type '${z}'; allowed: blocks, blocked-by`,2);let K=await $.openStore(X);if(!K.ok)return K.failure;let W=K.handle;try{let V=R0(W,Y);if(!V.ok)return V.failure;let G=R0(W,J);if(!G.ok)return G.failure;let H=z==="blocks"?V.node:G.node,N=z==="blocks"?G.node:V.node;if(H.id===N.id)return g8("conflict.dep_cycle",`dependency cycle: ${H.id} \u2192 ${H.id}`,4);if(W.store.getEdge(H.id,"blocks",N.id)!==void 0)return g8("conflict.dep_exists",`edge ${H.id} blocks ${N.id} already exists`,4);try{W.store.addEdge(H.id,"blocks",N.id)}catch(T){return z$0(T)}let Q=W.store.getNode(N.id),L=Q.open_blockers>0&&!xB.has(Q.status),B={src:H.id,dst:N.id,type:z,from_label:V.node.id,...L?{left_ready:!0,left_ready_id:N.id}:{},took_ms:Math.round(performance.now()-Z)};return{ok:!0,data:B,meta:{took_ms:B.took_ms}}}finally{W.close()}},renderHuman:Wv}}function U$0($){return{name:"rm",summary:"remove a dependency: dep rm <from> <blocks|blocked-by> <to>",handler:async(X)=>{let Z=performance.now(),[Y,z,J]=X.args;if(Y===void 0||z===void 0||J===void 0)return g8("usage.invalid","usage: myc dep rm <from> <blocks|blocked-by> <to>",2);if(Kv(z,Y,J)===void 0)return g8("usage.invalid",`invalid type '${z}'; allowed: blocks, blocked-by`,2);let K=await $.openStore(X);if(!K.ok)return K.failure;let W=K.handle;try{let V=R0(W,Y);if(!V.ok)return V.failure;let G=R0(W,J);if(!G.ok)return G.failure;let H=z==="blocks"?V.node:G.node,N=z==="blocks"?G.node:V.node;try{if(!W.store.removeEdge(H.id,"blocks",N.id))return g8("notfound.edge",`no edge ${H.id} blocks ${N.id}`,3)}catch(T){return C0(T)}let Q=W.store.getNode(N.id),L=Q.open_blockers===0&&Q.anc_blockers===0&&Q.status==="open",B={src:H.id,dst:N.id,type:z,from_label:V.node.id,removed:!0,...L?{back_ready:!0,back_ready_id:N.id}:{},took_ms:Math.round(performance.now()-Z)};return{ok:!0,data:B,meta:{took_ms:B.took_ms}}}finally{W.close()}},renderHuman:Wv}}function Vv($,X,Z,Y,z){let J=$.store.getNode(X);if(J===void 0)return;if(!Y&&xB.has(J.status))return;let U={id:J.id,priority:J.priority,kind:J.kind,status:J.status,title:J.title,children:[]};if(Z<=0||z.has(X))return U;z.add(X);for(let K of $.store.edgesFrom(X,"blocks")){let W=Vv($,K.dst,Z-1,Y,z);if(W!==void 0)U.children.push(W)}return z.delete(X),U}function Gv($){return $.children.reduce((X,Z)=>X+1+Gv(Z),0)}function K$0($,X,Z,Y){let z=`${$.id} ${$.kind==="task"?`${g0($.priority)} `:""}${$.status} ${$.title}`;if(Z)Y.push(z);$.children.forEach((J,U)=>{let K=U===$.children.length-1,W=K?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";Y.push(`${X}${W}blocks ${J.id} ${J.kind==="task"?`${g0(J.priority)} `:""}${J.status} ${J.title}`),Hv(J,X+(K?" ":"\u2502 "),Y)})}function Hv($,X,Z){$.children.forEach((Y,z)=>{let J=z===$.children.length-1,U=J?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";Z.push(`${X}${U}blocks ${Y.id} ${Y.kind==="task"?`${g0(Y.priority)} `:""}${Y.status} ${Y.title}`),Hv(Y,X+(J?" ":"\u2502 "),Z)})}function W$0($){let X=$,Z=[];if(K$0(X.root,"",!0,Z),X.blocked_count>0)Z.push(`${aY(X.blocked_count,"node","nodes")} blocked by this task`);else Z.push("blocks nothing");return`${Z.join(`
|
|
3408
3408
|
`)}
|
|
3409
|
-
`}function
|
|
3409
|
+
`}function V$0($){return{name:"tree",summary:"who is blocked by this node: dep tree <id> [--depth n] [--closed]",flags:[{name:"depth",value:"number",description:"levels below root (default 4)"},{name:"closed",description:"include closed nodes"}],handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0)return g8("usage.invalid","usage: myc dep tree <id>",2);let z=t(X,"depth")??4;if(z<1||z>wB)return g8("usage.invalid",`--depth out of range 1..${wB}`,2);let J=X.flags.closed===!0,U=await $.openStore(X);if(!U.ok)return U.failure;let K=U.handle;try{let W=R0(K,Y);if(!W.ok)return W.failure;let V=Vv(K,W.node.id,z,J,new Set);if(V===void 0)return g8("precond.closed",`${W.node.id} is closed; to show it: --closed`,5);let G={root:V,blocked_count:Gv(V),took_ms:Math.round(performance.now()-Z)};return{ok:!0,data:G,meta:{took_ms:G.took_ms}}}finally{K.close()}},renderHuman:W$0}}function Qv($,X,Z,Y,z){if(z<=0||Y.has(X))return[];Y.add(X);let J=[];for(let U of $.store.edgesTo(X,"blocks")){let K=$.store.getNode(U.src);if(K===void 0)continue;let W={id:K.id,priority:K.priority,kind:K.kind,status:K.status,assignee:K.assignee,title:K.title,age_ms:Z-K.updated_at,closed_at:K.closed_at,...N7(K)!==void 0?{estimate_min:N7(K)}:{},children:Qv($,K.id,Z,Y,z-1)};J.push(W)}return Y.delete(X),J}function G$0($){let X=0,Z=0,Y=(z)=>{for(let J of z){if(!xB.has(J.status))X++,Z+=J.estimate_min??0;Y(J.children)}};return Y($),{open:X,estimate_min:Z}}function Nv($,X,Z){$.forEach((Y,z)=>{let J=z===$.length-1,U=J?"\u2514\u2500 ":"\u251C\u2500 ",K=[Y.id];if(Y.kind==="task")K.push(g0(Y.priority));if(K.push(H$0(Y)),Y.status==="closed"&&Y.closed_at!==null)K.push(`closed ${d0(Y.closed_at)}`);else if(K.push(Y.status),Y.assignee.length>0)K.push(`@${Y.assignee} ${T$(Y.age_ms)}`);K.push(` ${Y.title}`),Z.push(`${X}${U}${K.join(" ")}`),Nv(Y.children,X+(J?" ":"\u2502 "),Z)})}function H$0($){return $.kind}function aY($,X,Z){return`${$} ${$===1?X:Z}`}function Q$0($){let X=$,Z=[],Y=[`${X.id} ${g0(X.priority)} ${X.type} ${X.status}`];if(X.open_blockers>0)Y.push(`\u2014 blocked by ${aY(X.open_blockers,"open dependency","open dependencies")}`);else if(X.blocked_via.length>0)Y.push(`\u2014 no blockers of its own, ${aY(X.blocked_via.length,"ancestor holds","ancestors hold")} an open one`);else Y.push("\u2014 not blocked");Z.push(Y.join(" ")),Nv(X.chain,"",Z);for(let z of X.blocked_via){let J=z.open_blockers;Z.push(`ancestor ${z.id} (${aY(J,"open blocker","open blockers")}) \u2014 ${z.title}`)}if(X.critical_path.open>0){let z=X.critical_path.estimate_min>0?`, estimate ${Q7(X.critical_path.estimate_min)}`:"";Z.push(`critical path: ${aY(X.critical_path.open,"node","nodes")}${z}`)}return`${Z.join(`
|
|
3410
3410
|
`)}
|
|
3411
|
-
`}function
|
|
3411
|
+
`}function N$0($){return{name:"why",summary:"why is this node blocked: dep why <id>",handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0)return g8("usage.invalid","usage: myc dep why <id>",2);let z=await $.openStore(X);if(!z.ok)return z.failure;let J=z.handle;try{let U=R0(J,Y);if(!U.ok)return U.failure;let K=U.node,W=Qv(J,K.id,Date.now(),new Set,wB),V={id:K.id,type:K.kind==="task"?String(K.attrs.type??"task"):K.kind,priority:K.priority,status:K.status,open_blockers:K.open_blockers,blocked_via:J.store.blockingAncestors(K.id).map((G)=>({id:G.id,title:G.title,open_blockers:G.open_blockers})),chain:W,critical_path:G$0(W),took_ms:Math.round(performance.now()-Z)};return{ok:!0,data:V,meta:{took_ms:V.took_ms}}}finally{J.close()}},renderHuman:Q$0}}function hB($=$0){return{name:"dep",summary:"task dependencies (add, rm, tree, why)",subcommands:[J$0($),U$0($),V$0($),N$0($)]}}var xB,wB;var mB=v(()=>{V0();j0();n0();xB=new Set(["closed","cancelled","superseded","retracted"]),wB=x4});var qv={};s(qv,{renderLinkHuman:()=>Tv,createLinkCommand:()=>B$0,REASON_REQUIRED:()=>Bv,LINK_TYPES:()=>sY,LINK_EDGE_KINDS:()=>uB});function k9($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function Tv($){let X=$,Z=X.removed===!0?`${X.type} ${X.from} \u2192 ${X.to} removed`:`${X.from} ${X.type} ${X.to}`,Y=X.effects.length>0?`
|
|
3412
3412
|
effects ${X.effects.join(" \xB7 ")}`:"";return`${Z}${Y}
|
|
3413
3413
|
${X.took_ms} ms
|
|
3414
|
-
`}async function
|
|
3414
|
+
`}async function L$0($,X,Z,Y,z){let U=(hB($).subcommands??[]).find((H)=>H.name===(Y?"rm":"add"));if(U?.handler===void 0)return k9("internal.unexpected",`dep has no subcommand ${Y?"rm":"add"}`,1);let K=await U.handler(X);if(!K.ok)return K;let W=K.data,V=W.left_ready===!0?[`${W.left_ready_id} left ready`]:W.back_ready===!0?[`${W.back_ready_id} is ready again`]:[],G={from:W.src,type:Z,to:W.dst,...Y?{removed:!0}:{},effects:V,took_ms:Math.round(performance.now()-z)};return{ok:!0,data:G,meta:{took_ms:G.took_ms}}}function B$0($=$0){return{name:"link",summary:"link two nodes: link <from> <type> <to> [--reason ...] [--remove]",flags:[{name:"reason",value:"string",description:"why (required for supersedes and duplicates)"},{name:"remove",description:"remove the link instead of creating it"}],help:`Types: ${sY.join(", ")}. The same contract as the \`myc_link\` MCP tool: same `+"types, same required reason, same exit codes \u2014 the terminal and the tool are two doors "+"to one edge. `blocks`/`blocked-by` go through the dependency engine, so cycles and the ready queue behave exactly as with `myc dep add`. `supersedes` also marks the old node `superseded_by` and keeps it: a contradiction is recorded, not overwritten.",handler:async(X)=>{let Z=performance.now(),[Y,z,J]=X.args;if(Y===void 0||z===void 0||J===void 0)return k9("usage.invalid","usage: myc link <from> <type> <to>",2,`type is one of: ${sY.join(", ")}`);if(!sY.includes(z))return k9("usage.invalid",`invalid type '${z}'; allowed: ${sY.join(", ")}`,2);let U=X.flags.reason,K=typeof U==="string"?U:void 0;if(Bv.has(z)&&K===void 0)return k9("usage.missing",`${z} requires a reason \u2014 history is not rewritten`,2);let W=X.flags.remove===!0;if(z==="blocks"||z==="blocked-by")return L$0($,X,z,W,Z);let V=await $.openStore(X);if(!V.ok)return V.failure;let G=V.handle;try{let H=R0(G,Y);if(!H.ok)return H.failure;let N=R0(G,J);if(!N.ok)return N.failure;let Q=uB[z],L=H.node.id,B=N.node.id,T=[];if(W){if(!G.store.removeEdge(L,Q,B))return k9("notfound.edge",`no edge ${L} ${z} ${B}`,3)}else{let j=G.store.getEdge(L,Q,B);if(j!==void 0&&j.deleted_at===null)return k9("conflict.edge_exists",`edge ${L} ${z} ${B} already exists`,4);try{G.store.addEdge(L,Q,B,{...K!==void 0?{attrs:{reason:K}}:{}})}catch(O){return C0(O)}if(z==="supersedes")G.store.updateNode(B,{attrs:{superseded_by:L}}),T.push(`${B} marked superseded_by ${L}; the old node is kept`);if(K!==void 0)T.push(`reason: ${K}`)}let q={from:L,type:z,to:B,...W?{removed:!0}:{},effects:T,took_ms:Math.round(performance.now()-Z)};return{ok:!0,data:q,meta:{took_ms:q.took_ms}}}finally{G.close()}},renderHuman:Tv}}var uB,sY,Bv;var Fv=v(()=>{V0();j0();mB();uB={"relates-to":"relates",duplicates:"duplicates",supersedes:"supersedes",contradicts:"contradicts","replies-to":"replies_to","derived-from":"derived_from","part-of":"parent"},sY=["blocks","blocked-by",...Object.keys(uB)],Bv=new Set(["supersedes","duplicates"])});var pB={};s(pB,{readyStats:()=>GK,readyQueries:()=>n4,createReadyCommand:()=>k$0,collectTop:()=>VK});function rY($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function q$0($){if($<86400000)return 1;if($<259200000)return 0.7;if($<604800000)return 0.4;return 0.15}function F$0($){if($===void 0||$.length===0)return{norm:0.5,label:"none"};if($.every((X)=>X==="fresh"))return{norm:1,label:"fresh"};if($.some((X)=>X==="stale"||X==="lost"))return{norm:0.2,label:"stale"};return{norm:0.6,label:"drifted"}}function j$0($){switch($){case"bug":return 1;case"task":return 0.5;case"epic":return 0.25;default:return 0.25}}function O$0($){return"lease_holder"in $}function lB($,X,Z,Y,z,J){let U=O$0($)?{holder:$.lease_holder,expires_at:$.lease_expires}:void 0,K={};try{K=JSON.parse($.attrs)}catch{}let W=typeof K.type==="string"?K.type:"task",V=typeof K.estimate_min==="number"?K.estimate_min:void 0,G=Math.max(0,z-w7({updated_at:$.updated_at,attrs:K})),H=F$0(Z),N=x5(Y.priority*(T$0[$.priority]??0)),Q=x5(Y.unblocks*Math.min(X,jv)/jv),L=x5(Y.freshness*q$0(G)),B=x5(Y.anchors*H.norm),T=x5(Y.type*j$0(W)),q=J??x5(N+Q+L+B+T);return{id:$.id,priority:$.priority,type:W,title:$.title,status:$.status,assignee:$.assignee,unblocks:X,...V!==void 0?{estimate_min:V}:{},...U!==void 0?{expired_lease:U}:{},score:q,terms:{priority:N,unblocks:Q,freshness:L,anchors:B,type:T},why:{priority:g0($.priority),unblocks:`unblocks ${X}`,freshness:`freshness ${T$(G)}`,anchors:`anchors ${H.label}`,type:W}}}function VK($,X,Z,Y=""){let z=$.driver.one(J$.ready_touches_exist,[])!==void 0,J=Y.length>0,U=J?z?J$.ready_top_anchors_repo:J$.ready_top_noanchors_repo:z?J$.ready_top_anchors:J$.ready_top_noanchors,K=$.weights,W=[$.scope,K.priority,K.unblocks,K.freshness,K.anchors,K.type,X,Z],V=$.driver.all(U,J?[...W,Y]:W),G=V.map((T)=>{let q=$.driver.one(J$.ready_unblocks_one,[T.id])?.n??0,j=z?$.driver.all(J$.ready_anchor_states_one,[T.id]).map((O)=>O.st):void 0;return lB(T,q,j,K,Z,x5(T.score))}),N=$.driver.all(J$.ready_expired_candidates,[$.scope,Z,Y]).filter((T)=>!C$0(T)),Q=N.map((T)=>{let q=$.driver.one(J$.ready_unblocks_one,[T.id])?.n??0,j=z?$.driver.all(J$.ready_anchor_states_one,[T.id]).map((O)=>O.st):void 0;return lB(T,q,j,K,Z)}),L=[...G,...Q].sort((T,q)=>q.score-T.score||T.priority-q.priority||T.id.localeCompare(q.id)),B=(V[0]?.total_ready??0)+N.length;return{items:L.slice(0,X),total:B}}function C$0($){try{return JSON.parse($.attrs).type==="epic"}catch{return!1}}function A$0($,X,Z,Y,z){let J=$.map((U)=>lB(U,X.get(U.id)??0,Z.get(U.id),Y,z));return J.sort((U,K)=>K.score-U.score||U.priority-K.priority||U.id.localeCompare(K.id)),J}function E9($){return $.toFixed(2)}function P$0($){if($.expired_lease!==void 0){let X=T$(Math.max(0,Date.now()-$.expired_lease.expires_at));return`EXPIRED @${$.expired_lease.holder} (${X} ago)`}return $.assignee.length>0?`@${$.assignee}`:"free"}function Ov($,X){let Z=[],Y=$.map((J)=>[J.id,g0(J.priority),J.type,J.title,`unblocks ${J.unblocks}`,J.estimate_min!==void 0?Q7(J.estimate_min):"\u2014",P$0(J)]),z=[0,0,0,0,0,0];for(let J of Y)J.forEach((U,K)=>{if(K<z.length)z[K]=Math.max(z[K],U.length)});return Y.forEach((J,U)=>{if(Z.push(J.map((K,W)=>W===J.length-1?K:K.padEnd(z[W])).join(" ").trimEnd()),X){let K=$[U];Z.push(` score ${E9(K.score)} = ${K.why.priority}(${E9(K.terms.priority)}) + ${K.why.unblocks}(${E9(K.terms.unblocks)}) + ${K.why.freshness}(${E9(K.terms.freshness)}) + ${K.why.anchors}(${E9(K.terms.anchors)}) + ${K.why.type}(${E9(K.terms.type)})`)}}),Z}function Cv($){let X=[];if($.repo.length>0)X.push(`repo ${$.repo}`);if($.repo_undetermined===!0)X.push(`repo reach undetermined: ${$.repo_reason??""}`);if(($.repo_foreign??0)>0)X.push(`${$.repo_foreign} from other repos hidden`);if(($.repo_unknown??0)>0)X.push(`${$.repo_unknown} without repo reach`);return X}function Av($){let X=$,Z=[];if(X.claimed!==void 0){let Y=X.claimed;if(Z.push(`claimed ${Y.id} by ${Y.holder} \xB7 lease ${T$(Y.lease_ttl_ms)} until ${M6(Y.lease_expires)}`),Z.push(`${g0(Y.priority)} ${Y.type} \xB7 ${Y.title}`),Y.body!==null&&Y.body.trim().length>0){Z.push("description");for(let z of Y.body.trimEnd().split(`
|
|
3415
3415
|
`))Z.push(` ${z}`)}if(Y.blocked_by.length>0)Z.push(`deps blocked-by ${Y.blocked_by.join(", ")}`);return Z.push(`${X.took_ms} ms`),`${Z.join(`
|
|
3416
3416
|
`)}
|
|
3417
3417
|
`}if(Z.push(...Ov(X.items,!1)),Z.push([...Pv(X),`${X.took_ms} ms`,...Cv(X)].join(" \xB7 ")),X.ready===0&&(X.blocked??0)>0&&X.top_blocker!==void 0){let Y=X.top_blocker;Z.push("all open tasks are blocked. top blocker:");let z=Y.assignee.length>0?`@${Y.assignee}`:"free";Z.push(` ${Y.id} ${g0(Y.priority)} ${Y.title} ${z} (blocks ${Y.blocks})`)}return`${Z.join(`
|
|
3418
3418
|
`)}
|
|
3419
|
-
`}function
|
|
3419
|
+
`}function D$0($){if($.blocked===void 0)return;let X=$.blocked_by_ancestor??0;return X>0?`${$.blocked+X} blocked (${X} via ancestor)`:`${$.blocked} blocked`}function Pv($){let X=[`${$.ready} ready`],Z=D$0($);if(Z!==void 0)X.push(Z);if($.in_progress!==void 0)X.push(`${$.in_progress} in_progress`);return X}function M$0($){let X=$;if(X.claimed!==void 0)return Av($);let Z=Ov(X.items,!0);return Z.push([...Pv(X),`${X.took_ms} ms`,...Cv(X)].join(" \xB7 ")),`${Z.join(`
|
|
3420
3420
|
`)}
|
|
3421
|
-
`}function C$0($){if($.flags.assignee!==void 0&&$.flags.free===!0)return rY("usage.invalid","--assignee and --free are mutually exclusive",2);let X=f($,"priority");if(X!==void 0&&L7(X)===void 0)return rY("usage.invalid",`invalid priority '${X}'; allowed: P0..P3 or 0..3`,2);let Z=f($,"kind");if(Z!==void 0&&!["task","bug","epic","chore"].includes(Z))return rY("usage.invalid",`invalid --kind '${Z}'; allowed: task, bug, epic, chore`,2);return}function A$0($,X,Z){let Y=$.driver.all(J$.ready_candidates,[$.scope,Z]),z=$.driver.all(J$.ready_expired_candidates,[$.scope,Date.now(),Z]),J=[...Y,...z],U=new Map;for(let T of $.driver.all(J$.ready_unblocks,[]))U.set(T.id,T.n);let K=new Map;for(let T of $.driver.all(J$.ready_anchor_states,[])){let q=K.get(T.id);if(q===void 0)K.set(T.id,[T.st]);else q.push(T.st)}let W=q$0(J,U,K,$.weights,Date.now()),V=f(X,"kind"),G=f(X,"priority"),H=G!==void 0?L7(G):void 0,N=f(X,"tag"),Q=f(X,"assignee"),L=X.flags.free===!0,B=N!==void 0?new Set(J.filter((T)=>T.attrs.includes(`"${N}"`)).map((T)=>T.id)):void 0;return W.filter((T)=>{if(T.type==="epic"&&V!=="epic")return!1;if(V!==void 0&&T.type!==V)return!1;if(H!==void 0&&T.priority!==H)return!1;if(Q!==void 0&&T.assignee!==Q)return!1;if(L&&T.assignee.length>0)return!1;if(B!==void 0&&!B.has(T.id))return!1;return!0})}function P$0($){return f($,"kind")!==void 0||f($,"priority")!==void 0||f($,"tag")!==void 0||f($,"assignee")!==void 0||$.flags.free===!0}function GK($,X=""){return Y2($.driver,{scope:$.scope,profile:cz,variant:`v4:${X}`},()=>({blocked:$.driver.one(J$.ready_stats_blocked,[$.scope,X])?.n??0,blockedByAncestor:$.driver.one(J$.ready_stats_blocked_anc,[$.scope,X])?.n??0,inProgress:$.driver.one(J$.ready_stats_in_progress,[$.scope,X])?.n??0,repoUnknown:$.driver.one(J$.ready_repo_unknown,[$.scope])?.n??0,repoForeign:X.length===0?0:$.driver.one(J$.ready_repo_foreign,[$.scope,X])?.n??0})).payload}function D$0($=$0){let X=(Z,Y)=>Y.flags.why===!0?O$0(Z):Av(Z);return{name:"ready",remote:!0,summary:"ready queue: open tasks without open blockers",flags:[{name:"n",short:"n",value:"number",description:"limit rows (default 10)"},{name:"kind",value:"string",description:"task|bug|epic|chore"},{name:"priority",value:"string",description:"P0|P1|P2|P3 or 0|1|2|3"},{name:"tag",value:"string",description:"must carry this tag"},{name:"assignee",value:"string",description:"only this assignee"},{name:"free",description:"only unassigned"},{name:"claim",description:"atomically claim the top task"},{name:"why",description:"print score terms for every row"},{name:"lease",value:"string",description:"lease TTL for --claim (default 30m)"},{name:"as",value:"string",description:"actor for --claim (default $MYC_ACTOR/$USER)"},{name:"repo",value:"string",description:"repository scope (S59): a repo name, or `all` to drop the filter"}],help:"Score = w_priority\xB7P + w_unblocks\xB7U + w_freshness\xB7F + w_anchors\xB7A + w_type\xB7T, "+"weights from workspace.toml [ready] (S21 defaults 0.40/0.27/0.14/0.10/0.09). --why prints the real terms; --claim takes the top task atomically.",handler:async(Z)=>{let Y=performance.now(),z=C$0(Z);if(z!==void 0)return z;let J=B5,U=f(Z,"lease");if(U!==void 0){let G=P$(U);if(G===void 0)return rY("usage.invalid",`invalid lease '${U}'; format: 30m, 2h`,2);J=G}let K=await $8(Z,async(G)=>{let H=[Z.flags.why===!0?"--why":"",Z.flags.claim===!0?"--claim":"",f(Z,"tag")!==void 0?"--tag":"",f(Z,"kind")!==void 0?"--kind":""].filter((T)=>T!=="");if(H.length>0)return rY("precond.no_remote",`the server queue does not answer ${H.join(", ")} yet`,5,"take a task by id: myc --server <url> claim <id>");let N=await G.ready({n:typeof Z.flags.n==="number"?Z.flags.n:void 0,repo:f(Z,"repo")}),Q=Number(N.meta.total??0);return{ok:!0,data:{items:N.data,ready:Q,repo:f(Z,"repo")??"",took_ms:Math.round((performance.now()-Y)*100)/100},meta:{...N.meta,remote:G.ws}}});if(K!==void 0)return K;let W=await $.openStore(Z);if(!W.ok)return W.failure;let V=W.handle;try{let G=L5(V,f(Z,"repo")),H=GK(V,G),{blocked:N,blockedByAncestor:Q,inProgress:L}=H,B={repo:G,repo_undetermined:V.repo.repo===void 0,repo_reason:c4(V.repo),repo_unknown:H.repoUnknown,repo_foreign:H.repoForeign},T=t(Z,"n")??10,q=P$0(Z),j=q?{items:A$0(V,Z,G),total:-1}:VK(V,Z.flags.claim===!0?Math.max(T,50):T,Date.now(),G),O=j.items,A=q?O.length:j.total;if(Z.flags.claim===!0){for(let P of O){let _=V.claims.claim(P.id,J);if(_===void 0)continue;let M=V.store.getNode(P.id),E=V.store.edgesTo(P.id,"blocks").map((k)=>{let y=V.store.getNode(k.src);return y!==void 0&&y.status==="closed"&&y.closed_at!==null?`${k.src} (closed ${new Date(y.closed_at).toISOString().slice(0,10)})`:`${k.src} (${y?.status??"?"})`}),b={items:[],ready:A,blocked:N,blocked_by_ancestor:Q,in_progress:L,...B,claimed:{id:P.id,holder:V.actor,lease_expires:_.expiresAt,lease_ttl_ms:J,type:P.type,priority:P.priority,title:P.title,body:M.body,blocked_by:E},took_ms:Math.round(performance.now()-Y)};return{ok:!0,data:b,meta:{took_ms:b.took_ms}}}let F={items:[],ready:0,blocked:N,blocked_by_ancestor:Q,in_progress:L,...B,took_ms:Math.round(performance.now()-Y)};return{ok:!0,data:F,meta:{took_ms:F.took_ms}}}let R;if(O.length===0&&N>0){let F=V.driver.one(J$.ready_top_blocker,[]);if(F!==void 0){let P=V.store.getNode(F.id);if(P!==void 0)R={id:P.id,priority:P.priority,title:P.title,assignee:P.assignee,blocks:F.n}}}let D={items:q?O.slice(0,T):O,ready:A,blocked:N,blocked_by_ancestor:Q,in_progress:L,...B,...R!==void 0?{top_blocker:R}:{},took_ms:Math.round(performance.now()-Y)};return{ok:!0,data:D,meta:{took_ms:D.took_ms,count:D.items.length,repo:G.length>0?G:null,repo_unknown:H.repoUnknown,repo_foreign:H.repoForeign}}}finally{V.close()}},renderHuman:X}}var J$,H$0,jv=3,x5=($)=>Math.round($*100)/100;var HK=v(()=>{o();DY();V0();w5();j0();J$=n4,H$0=[1,0.6666666666666666,0.3333333333333333,0]});var kv={};s(kv,{realPrimeDeps:()=>_v,primeQueries:()=>J8,createPrimeCommand:()=>x$0,MIN_BUDGET:()=>iB,DEFAULT_BUDGET:()=>oB});import{existsSync as M$0}from"fs";import{join as R$0}from"path";function QK($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function nB($,X,Z,Y,z){return z0(rZ($.scope,X,Z,Y,z),$.driver)}function E$0($,X){return`v6:${$}:${X}`}function v$0($,X,Z,Y){if(X!==void 0&&X.trim().length>0)return{payload:nB($,"project",X,Z,Y),cache:"miss"};let z=Y2($.driver,{scope:$.scope,profile:pz,variant:E$0(Z,Y)},()=>nB($,"project",void 0,Z,Y));return{payload:z.payload,cache:z.cache}}function y$0($){return{id:$.id,priority:$.priority,type:$.type,title:$.title,unblocks:$.unblocks,...$.estimate_min!==void 0?{estimate_min:$.estimate_min}:{}}}function S$0($){let X=$.driver.all(dB.prime_inprogress,[$.scope,Dv]);return{total:X.length<Dv?X.length:$.driver.one(dB.prime_inprogress_count,[$.scope])?.n??X.length,items:X.map((Y)=>({id:Y.id,title:Y.title,priority:Y.priority,assignee:Y.assignee,lease_holder:Y.lease_holder,lease_expires:Y.lease_expires}))}}function g$0($){if($===void 0)return"agent";return Rv.includes($)?$:void 0}function b$0($){if($===void 0)return"agent";return $==="agent"||$==="md"||$==="json"?$:void 0}function x$0($=_v){return{name:"prime",remote:!0,summary:"session bootstrap: what we already know about the project",flags:w$0,help:"READY > IN PROGRESS > CORE > DECISIONS > NEXT, in that priority order \u2014 the tail is cut "+"first and predictably when --budget is too small. Never calls the embedder; --focus filters the L2/L3 digest by substring, not by semantic search. Model routing (S12) is called "+"separately and ships with M5 \u2014 it is not part of this build; `myc bootstrap` is a separate "+"command. Neither is duplicated here.",handler:async(X)=>{let Z=performance.now(),Y=t(X,"budget")??oB;if(!Number.isFinite(Y)||Y<iB)return QK("usage.invalid",`--budget too small (${Y}); minimum ${iB}`,2);let z=Math.floor(Y),J=g$0(f(X,"role"));if(J===void 0)return QK("usage.invalid",`invalid --role; allowed: ${Rv.join("|")}`,2);let U=b$0(f(X,"format"));if(U===void 0)return QK("usage.invalid","invalid --format; allowed: agent|md|json",2);let K=f(X,"focus"),W=z8(f(X,"session")),V=await $8(X,async(N)=>{if(K!==void 0&&K.trim()!=="")return QK("precond.no_remote","--focus is not answered by the server yet",5);let Q=await N.prime({session:W,repo:f(X,"repo")}),L=Q.data,B=f(X,"repo")??"",T=L.nodes;return{ok:!0,data:{ws:N.ws,node_count:T,idx_ok:!0,now:Date.now(),empty:T===0,beads:!1,role:J,ready_total:L.total_ready,ready:L.ready.map((j)=>({id:j.id,priority:j.priority,type:"",title:j.title,unblocks:j.unblocks})),blocked:-1,in_progress_total:-1,in_progress:L.in_progress.map((j)=>({id:j.id,title:j.title,priority:j.priority??2,assignee:j.assignee,lease_holder:j.lease_holder??"",lease_expires:j.lease_expires??0})),core:L.digest.core,decisions:L.digest.decisions,session:W,reach_hidden:L.digest.reach.hidden,reach_unknown:L.digest.reach.unknown,repo:B,repo_undetermined:!1,repo_reason:"",repo_unknown:0,repo_foreign:0,mem_repo_unknown:0,mem_repo_foreign:0,pending_review:L.digest.pending,anchor_lost_hidden:L.digest.lost,degraded:[],format:U,budget:z,chars:0,truncated:!1,cut:[],cache:"miss",took_ms:Math.round(performance.now()-Z)},meta:{...Q.meta,remote:N.ws,budget:z}}});if(V!==void 0)return V;let G=await $.openStore(X);if(!G.ok)return G.failure;let H=G.handle;try{let N=Date.now(),Q=H.driver.one(dB.prime_node_count,[H.scope])?.n??0,L=Q===0,B=L&&M$0(R$0(H.wsDir,".beads")),T=L5(H,f(X,"repo")),q=GK(H,T),{blocked:j,inProgress:O}=q,A=L?{items:[],total:0}:VK(H,f$0,N,T),R=L?{total:0,items:[]}:S$0(H),D=L?{payload:{core:[],decisions:[],reach:{hidden:0,unknown:0},repo:{hidden:0,unknown:0},pending:0,lost:0},cache:"miss"}:v$0(H,K,W,T),F=[],P=D.payload.core,_=D.payload.decisions,M=D.payload.reach.hidden,E=D.payload.reach.unknown,b=D.payload.repo.hidden,k=D.payload.repo.unknown,y=D.payload.pending,g=D.payload.lost;if(!L)try{let d=await $.openPersonal(X);if(!d.ok)X.warn("degraded.personal_tier",`personal tier failed to open: ${d.failure.msg}`),F.push(`personal_tier: ${d.failure.msg}`);else if(d.handle!==void 0){let a=d.handle;try{let e=nB(a,"personal",K,W,T);P=[...P,...e.core].slice(0,aZ),_=[..._,...e.decisions].slice(0,sZ),M+=e.reach.hidden,E+=e.reach.unknown,b+=e.repo.hidden,k+=e.repo.unknown,y+=e.pending,g+=e.lost}finally{a.close()}}}catch(d){let a=d instanceof Error?d.message:String(d);X.warn("degraded.personal_tier",`personal tier failed to open: ${a}`),F.push(`personal_tier: ${a}`)}let S=Math.round(performance.now()-Z),w={ws:H.slug,node_count:Q,idx_ok:!0,now:N,empty:L,beads:B,role:J,ready_total:A.total,ready:A.items.map(y$0),blocked:j,in_progress_total:R.total,in_progress:R.items,core:P,decisions:_,session:W,reach_hidden:M,reach_unknown:E,repo:T,repo_undetermined:H.repo.repo===void 0,repo_reason:c4(H.repo),repo_unknown:q.repoUnknown,repo_foreign:q.repoForeign,mem_repo_unknown:k,mem_repo_foreign:b,pending_review:y,anchor_lost_hidden:g,degraded:F,...K!==void 0?{focus:K}:{},format:U,budget:z,cache:D.cache,took_ms:S};NY(H.mycDir,"session-start",S,W.length>0?"ok":"no-session");let h=Mv(w,z);return{ok:!0,data:{...w,chars:h.chars,truncated:h.truncated,cut:h.cut},meta:{took_ms:S,cache:D.cache,session:W.length>0?W:null,reach_hidden:M,reach_unknown:E,repo:T.length>0?T:null,repo_unknown:q.repoUnknown,repo_foreign:q.repoForeign,mem_repo_unknown:k,mem_repo_foreign:b,pending_review:y,anchor_lost_hidden:g,degraded:F.length>0?F:void 0}}}finally{H.close()}},renderHuman:(X)=>{let Z=X;if(Z.format==="json")return`${JSON.stringify(X,null,2)}
|
|
3422
|
-
`;return Mv(Z,Z.budget).text}}}function Iv($){let X=[];if($.tier==="personal")X.push("@personal");if($.reach==="session")X.push("@session");else if($.reach==="unknown")X.push("@no-reach");return X.length>0?` [${X.join(" ")}]`:""}function
|
|
3421
|
+
`}function R$0($){if($.flags.assignee!==void 0&&$.flags.free===!0)return rY("usage.invalid","--assignee and --free are mutually exclusive",2);let X=f($,"priority");if(X!==void 0&&L7(X)===void 0)return rY("usage.invalid",`invalid priority '${X}'; allowed: P0..P3 or 0..3`,2);let Z=f($,"kind");if(Z!==void 0&&!["task","bug","epic","chore"].includes(Z))return rY("usage.invalid",`invalid --kind '${Z}'; allowed: task, bug, epic, chore`,2);return}function _$0($,X,Z){let Y=$.driver.all(J$.ready_candidates,[$.scope,Z]),z=$.driver.all(J$.ready_expired_candidates,[$.scope,Date.now(),Z]),J=[...Y,...z],U=new Map;for(let T of $.driver.all(J$.ready_unblocks,[]))U.set(T.id,T.n);let K=new Map;for(let T of $.driver.all(J$.ready_anchor_states,[])){let q=K.get(T.id);if(q===void 0)K.set(T.id,[T.st]);else q.push(T.st)}let W=A$0(J,U,K,$.weights,Date.now()),V=f(X,"kind"),G=f(X,"priority"),H=G!==void 0?L7(G):void 0,N=f(X,"tag"),Q=f(X,"assignee"),L=X.flags.free===!0,B=N!==void 0?new Set(J.filter((T)=>T.attrs.includes(`"${N}"`)).map((T)=>T.id)):void 0;return W.filter((T)=>{if(T.type==="epic"&&V!=="epic")return!1;if(V!==void 0&&T.type!==V)return!1;if(H!==void 0&&T.priority!==H)return!1;if(Q!==void 0&&T.assignee!==Q)return!1;if(L&&T.assignee.length>0)return!1;if(B!==void 0&&!B.has(T.id))return!1;return!0})}function I$0($){return f($,"kind")!==void 0||f($,"priority")!==void 0||f($,"tag")!==void 0||f($,"assignee")!==void 0||$.flags.free===!0}function GK($,X=""){return Y2($.driver,{scope:$.scope,profile:cz,variant:`v4:${X}`},()=>({blocked:$.driver.one(J$.ready_stats_blocked,[$.scope,X])?.n??0,blockedByAncestor:$.driver.one(J$.ready_stats_blocked_anc,[$.scope,X])?.n??0,inProgress:$.driver.one(J$.ready_stats_in_progress,[$.scope,X])?.n??0,repoUnknown:$.driver.one(J$.ready_repo_unknown,[$.scope])?.n??0,repoForeign:X.length===0?0:$.driver.one(J$.ready_repo_foreign,[$.scope,X])?.n??0})).payload}function k$0($=$0){let X=(Z,Y)=>Y.flags.why===!0?M$0(Z):Av(Z);return{name:"ready",remote:!0,summary:"ready queue: open tasks without open blockers",flags:[{name:"n",short:"n",value:"number",description:"limit rows (default 10)"},{name:"kind",value:"string",description:"task|bug|epic|chore"},{name:"priority",value:"string",description:"P0|P1|P2|P3 or 0|1|2|3"},{name:"tag",value:"string",description:"must carry this tag"},{name:"assignee",value:"string",description:"only this assignee"},{name:"free",description:"only unassigned"},{name:"claim",description:"atomically claim the top task"},{name:"why",description:"print score terms for every row"},{name:"lease",value:"string",description:"lease TTL for --claim (default 30m)"},{name:"as",value:"string",description:"actor for --claim (default $MYC_ACTOR/$USER)"},{name:"repo",value:"string",description:"repository scope (S59): a repo name, or `all` to drop the filter"}],help:"Score = w_priority\xB7P + w_unblocks\xB7U + w_freshness\xB7F + w_anchors\xB7A + w_type\xB7T, "+"weights from workspace.toml [ready] (S21 defaults 0.40/0.27/0.14/0.10/0.09). --why prints the real terms; --claim takes the top task atomically.",handler:async(Z)=>{let Y=performance.now(),z=R$0(Z);if(z!==void 0)return z;let J=B5,U=f(Z,"lease");if(U!==void 0){let G=P$(U);if(G===void 0)return rY("usage.invalid",`invalid lease '${U}'; format: 30m, 2h`,2);J=G}let K=await $8(Z,async(G)=>{let H=[Z.flags.why===!0?"--why":"",Z.flags.claim===!0?"--claim":"",f(Z,"tag")!==void 0?"--tag":"",f(Z,"kind")!==void 0?"--kind":""].filter((T)=>T!=="");if(H.length>0)return rY("precond.no_remote",`the server queue does not answer ${H.join(", ")} yet`,5,"take a task by id: myc --server <url> claim <id>");let N=await G.ready({n:typeof Z.flags.n==="number"?Z.flags.n:void 0,repo:f(Z,"repo")}),Q=Number(N.meta.total??0);return{ok:!0,data:{items:N.data,ready:Q,repo:f(Z,"repo")??"",took_ms:Math.round((performance.now()-Y)*100)/100},meta:{...N.meta,remote:G.ws}}});if(K!==void 0)return K;let W=await $.openStore(Z);if(!W.ok)return W.failure;let V=W.handle;try{let G=L5(V,f(Z,"repo")),H=GK(V,G),{blocked:N,blockedByAncestor:Q,inProgress:L}=H,B={repo:G,repo_undetermined:V.repo.repo===void 0,repo_reason:c4(V.repo),repo_unknown:H.repoUnknown,repo_foreign:H.repoForeign},T=t(Z,"n")??10,q=I$0(Z),j=q?{items:_$0(V,Z,G),total:-1}:VK(V,Z.flags.claim===!0?Math.max(T,50):T,Date.now(),G),O=j.items,A=q?O.length:j.total;if(Z.flags.claim===!0){for(let P of O){let _=V.claims.claim(P.id,J);if(_===void 0)continue;let M=V.store.getNode(P.id),E=V.store.edgesTo(P.id,"blocks").map((k)=>{let y=V.store.getNode(k.src);return y!==void 0&&y.status==="closed"&&y.closed_at!==null?`${k.src} (closed ${new Date(y.closed_at).toISOString().slice(0,10)})`:`${k.src} (${y?.status??"?"})`}),b={items:[],ready:A,blocked:N,blocked_by_ancestor:Q,in_progress:L,...B,claimed:{id:P.id,holder:V.actor,lease_expires:_.expiresAt,lease_ttl_ms:J,type:P.type,priority:P.priority,title:P.title,body:M.body,blocked_by:E},took_ms:Math.round(performance.now()-Y)};return{ok:!0,data:b,meta:{took_ms:b.took_ms}}}let F={items:[],ready:0,blocked:N,blocked_by_ancestor:Q,in_progress:L,...B,took_ms:Math.round(performance.now()-Y)};return{ok:!0,data:F,meta:{took_ms:F.took_ms}}}let R;if(O.length===0&&N>0){let F=V.driver.one(J$.ready_top_blocker,[]);if(F!==void 0){let P=V.store.getNode(F.id);if(P!==void 0)R={id:P.id,priority:P.priority,title:P.title,assignee:P.assignee,blocks:F.n}}}let D={items:q?O.slice(0,T):O,ready:A,blocked:N,blocked_by_ancestor:Q,in_progress:L,...B,...R!==void 0?{top_blocker:R}:{},took_ms:Math.round(performance.now()-Y)};return{ok:!0,data:D,meta:{took_ms:D.took_ms,count:D.items.length,repo:G.length>0?G:null,repo_unknown:H.repoUnknown,repo_foreign:H.repoForeign}}}finally{V.close()}},renderHuman:X}}var J$,T$0,jv=3,x5=($)=>Math.round($*100)/100;var HK=v(()=>{o();DY();V0();w5();j0();J$=n4,T$0=[1,0.6666666666666666,0.3333333333333333,0]});var kv={};s(kv,{realPrimeDeps:()=>_v,primeQueries:()=>J8,createPrimeCommand:()=>p$0,MIN_BUDGET:()=>iB,DEFAULT_BUDGET:()=>oB});import{existsSync as E$0}from"fs";import{join as v$0}from"path";function QK($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function nB($,X,Z,Y,z){return z0(rZ($.scope,X,Z,Y,z),$.driver)}function g$0($,X){return`v6:${$}:${X}`}function b$0($,X,Z,Y){if(X!==void 0&&X.trim().length>0)return{payload:nB($,"project",X,Z,Y),cache:"miss"};let z=Y2($.driver,{scope:$.scope,profile:pz,variant:g$0(Z,Y)},()=>nB($,"project",void 0,Z,Y));return{payload:z.payload,cache:z.cache}}function w$0($){return{id:$.id,priority:$.priority,type:$.type,title:$.title,unblocks:$.unblocks,...$.estimate_min!==void 0?{estimate_min:$.estimate_min}:{}}}function h$0($){let X=$.driver.all(dB.prime_inprogress,[$.scope,Dv]);return{total:X.length<Dv?X.length:$.driver.one(dB.prime_inprogress_count,[$.scope])?.n??X.length,items:X.map((Y)=>({id:Y.id,title:Y.title,priority:Y.priority,assignee:Y.assignee,lease_holder:Y.lease_holder,lease_expires:Y.lease_expires}))}}function m$0($){if($===void 0)return"agent";return Rv.includes($)?$:void 0}function u$0($){if($===void 0)return"agent";return $==="agent"||$==="md"||$==="json"?$:void 0}function p$0($=_v){return{name:"prime",remote:!0,summary:"session bootstrap: what we already know about the project",flags:l$0,help:"READY > IN PROGRESS > CORE > DECISIONS > NEXT, in that priority order \u2014 the tail is cut "+"first and predictably when --budget is too small. Never calls the embedder; --focus filters the L2/L3 digest by substring, not by semantic search. Model routing (S12) is called "+"separately and ships with M5 \u2014 it is not part of this build; `myc bootstrap` is a separate "+"command. Neither is duplicated here.",handler:async(X)=>{let Z=performance.now(),Y=t(X,"budget")??oB;if(!Number.isFinite(Y)||Y<iB)return QK("usage.invalid",`--budget too small (${Y}); minimum ${iB}`,2);let z=Math.floor(Y),J=m$0(f(X,"role"));if(J===void 0)return QK("usage.invalid",`invalid --role; allowed: ${Rv.join("|")}`,2);let U=u$0(f(X,"format"));if(U===void 0)return QK("usage.invalid","invalid --format; allowed: agent|md|json",2);let K=f(X,"focus"),W=z8(f(X,"session")),V=await $8(X,async(N)=>{if(K!==void 0&&K.trim()!=="")return QK("precond.no_remote","--focus is not answered by the server yet",5);let Q=await N.prime({session:W,repo:f(X,"repo")}),L=Q.data,B=f(X,"repo")??"",T=L.nodes;return{ok:!0,data:{ws:N.ws,node_count:T,idx_ok:!0,now:Date.now(),empty:T===0,beads:!1,role:J,ready_total:L.total_ready,ready:L.ready.map((j)=>({id:j.id,priority:j.priority,type:"",title:j.title,unblocks:j.unblocks})),blocked:-1,in_progress_total:-1,in_progress:L.in_progress.map((j)=>({id:j.id,title:j.title,priority:j.priority??2,assignee:j.assignee,lease_holder:j.lease_holder??"",lease_expires:j.lease_expires??0})),core:L.digest.core,decisions:L.digest.decisions,session:W,reach_hidden:L.digest.reach.hidden,reach_unknown:L.digest.reach.unknown,repo:B,repo_undetermined:!1,repo_reason:"",repo_unknown:0,repo_foreign:0,mem_repo_unknown:0,mem_repo_foreign:0,pending_review:L.digest.pending,anchor_lost_hidden:L.digest.lost,degraded:[],format:U,budget:z,chars:0,truncated:!1,cut:[],cache:"miss",took_ms:Math.round(performance.now()-Z)},meta:{...Q.meta,remote:N.ws,budget:z}}});if(V!==void 0)return V;let G=await $.openStore(X);if(!G.ok)return G.failure;let H=G.handle;try{let N=Date.now(),Q=H.driver.one(dB.prime_node_count,[H.scope])?.n??0,L=Q===0,B=L&&E$0(v$0(H.wsDir,".beads")),T=L5(H,f(X,"repo")),q=GK(H,T),{blocked:j,inProgress:O}=q,A=L?{items:[],total:0}:VK(H,x$0,N,T),R=L?{total:0,items:[]}:h$0(H),D=L?{payload:{core:[],decisions:[],reach:{hidden:0,unknown:0},repo:{hidden:0,unknown:0},pending:0,lost:0},cache:"miss"}:b$0(H,K,W,T),F=[],P=D.payload.core,_=D.payload.decisions,M=D.payload.reach.hidden,E=D.payload.reach.unknown,b=D.payload.repo.hidden,k=D.payload.repo.unknown,y=D.payload.pending,g=D.payload.lost;if(!L)try{let d=await $.openPersonal(X);if(!d.ok)X.warn("degraded.personal_tier",`personal tier failed to open: ${d.failure.msg}`),F.push(`personal_tier: ${d.failure.msg}`);else if(d.handle!==void 0){let a=d.handle;try{let e=nB(a,"personal",K,W,T);P=[...P,...e.core].slice(0,aZ),_=[..._,...e.decisions].slice(0,sZ),M+=e.reach.hidden,E+=e.reach.unknown,b+=e.repo.hidden,k+=e.repo.unknown,y+=e.pending,g+=e.lost}finally{a.close()}}}catch(d){let a=d instanceof Error?d.message:String(d);X.warn("degraded.personal_tier",`personal tier failed to open: ${a}`),F.push(`personal_tier: ${a}`)}let S=Math.round(performance.now()-Z),w={ws:H.slug,node_count:Q,idx_ok:!0,now:N,empty:L,beads:B,role:J,ready_total:A.total,ready:A.items.map(w$0),blocked:j,in_progress_total:R.total,in_progress:R.items,core:P,decisions:_,session:W,reach_hidden:M,reach_unknown:E,repo:T,repo_undetermined:H.repo.repo===void 0,repo_reason:c4(H.repo),repo_unknown:q.repoUnknown,repo_foreign:q.repoForeign,mem_repo_unknown:k,mem_repo_foreign:b,pending_review:y,anchor_lost_hidden:g,degraded:F,...K!==void 0?{focus:K}:{},format:U,budget:z,cache:D.cache,took_ms:S};NY(H.mycDir,"session-start",S,W.length>0?"ok":"no-session");let h=Mv(w,z);return{ok:!0,data:{...w,chars:h.chars,truncated:h.truncated,cut:h.cut},meta:{took_ms:S,cache:D.cache,session:W.length>0?W:null,reach_hidden:M,reach_unknown:E,repo:T.length>0?T:null,repo_unknown:q.repoUnknown,repo_foreign:q.repoForeign,mem_repo_unknown:k,mem_repo_foreign:b,pending_review:y,anchor_lost_hidden:g,degraded:F.length>0?F:void 0}}}finally{H.close()}},renderHuman:(X)=>{let Z=X;if(Z.format==="json")return`${JSON.stringify(X,null,2)}
|
|
3422
|
+
`;return Mv(Z,Z.budget).text}}}function Iv($){let X=[];if($.tier==="personal")X.push("@personal");if($.reach==="session")X.push("@session");else if($.reach==="unknown")X.push("@no-reach");return X.length>0?` [${X.join(" ")}]`:""}function i$0($){return $.map((X)=>`- ${X.title}${Iv(X)}`)}function n$0($){return`${new Date($.updated_at).toISOString().slice(0,10)} ${$.id} ${$.title}${Iv($)}`}function d$0($){let X=[$.session.length>0?`session ${$.session.slice(0,S$0)}`:"session not specified"];if($.reach_hidden>0)X.push(`${$.reach_hidden} from other sessions hidden`);if($.reach_unknown>0)X.push(`${$.reach_unknown} without reach`);if($.pending_review>0)X.push(`${$.pending_review} pending review hidden \u2014 ${f$0}`);if($.anchor_lost_hidden>0)X.push(`${$.anchor_lost_hidden} with code gone hidden`);return X.push(...o$0($)),X.join(" \xB7 ")}function o$0($){let X=[];if($.repo.length>0)X.push(`repo ${$.repo}`);if($.repo_undetermined)X.push(`repo reach undetermined: ${$.repo_reason}`);if($.repo_foreign>0)X.push(`${$.repo_foreign} from other repos hidden`);if($.repo_unknown>0)X.push(`${$.repo_unknown} without repo reach`);if($.mem_repo_foreign>0)X.push(`${$.mem_repo_foreign} ${$.mem_repo_foreign===1?"note":"notes"} from other repos hidden`);if($.mem_repo_unknown>0)X.push(`${$.mem_repo_unknown} ${$.mem_repo_unknown===1?"note":"notes"} without repo reach`);return X}function a$0($,X){let Z=X?"## ":"# ",Y=[];if($.empty)return Y.push({key:"empty",text:"Workspace is empty. Nothing is remembered about this project yet."}),Y.push({key:"next",text:[`${Z}NEXT`,...$.beads?["myc import --from beads .beads/ is right here \u2014 its tasks can be imported"]:[],'myc create "<first task>" -p P1','myc remember "<what matters about this project>"'].join(`
|
|
3423
3423
|
`)}),Y;let z=$.ready.map((U)=>{let K=U.estimate_min!==void 0?` ${Q7(U.estimate_min)}`:"";return`${U.id} ${g0(U.priority)} ${U.type} ${U.title} unblocks ${U.unblocks}${K}`});if(Y.push({key:"ready",text:[`${Z}READY ${$.ready.length} of ${$.ready_total}`,...z].join(`
|
|
3424
3424
|
`)}),$.in_progress.length>0){let U=$.in_progress.map((K)=>{let W=K.assignee.length>0?`@${K.assignee}`:"unassigned";return`${K.id} ${g0(K.priority)} ${K.title} ${W} ${Z4(K.lease_holder,K.lease_expires,$.now)}`});Y.push({key:"in_progress",text:[`${Z}IN PROGRESS ${$.in_progress_total>$.in_progress.length?`${$.in_progress.length} of ${$.in_progress_total}`:$.in_progress_total}`,...U].join(`
|
|
3425
|
-
`)})}if($.core.length>0)Y.push({key:"core",text:[`${Z}CORE L3 ${$.core.length}`,...
|
|
3426
|
-
`)});if($.decisions.length>0)Y.push({key:"decisions",text:[`${Z}DECISIONS L2 ${$.decisions.length}`,...$.decisions.map(
|
|
3425
|
+
`)})}if($.core.length>0)Y.push({key:"core",text:[`${Z}CORE L3 ${$.core.length}`,...i$0($.core)].join(`
|
|
3426
|
+
`)});if($.decisions.length>0)Y.push({key:"decisions",text:[`${Z}DECISIONS L2 ${$.decisions.length}`,...$.decisions.map(n$0)].join(`
|
|
3427
3427
|
`)});let J=[`${Z}NEXT`,"myc ready --claim claim the top task atomically"];if($.role==="human")J.push("myc --help list commands");else J.push('myc recall "<topic>" facts and decisions on the topic'),J.push('myc remember "<fact>" record a conclusion');return Y.push({key:"next",text:J.join(`
|
|
3428
|
-
`)}),Y}function
|
|
3428
|
+
`)}),Y}function s$0($,X){let Z=[],Y=0,z=[],J=!1;for(let U of $){if(J){z.push(U.key);continue}let K=Z.length>0?2:0;if(Y+K+U.text.length<=X){Z.push(U.text),Y+=K+U.text.length;continue}let W=X-Y-K-1;if(W>=c$0)Z.push(`${U.text.slice(0,W)}\u2026`),Y=X;else z.push(U.key);J=!0}return{body:Z.join(`
|
|
3429
3429
|
|
|
3430
|
-
`),cut:z}}function
|
|
3430
|
+
`),cut:z}}function r$0($){let X=$.idx_ok?"idx ok":"idx stale";return`myc ${E0} \xB7 ws=${$.ws} sqlite \xB7 ${$.node_count} ${$.node_count===1?"node":"nodes"} \xB7 ${X} \xB7 ${new Date($.now).toISOString()}`}function Mv($,X){let Z=r$0($),Y=a$0($,$.format==="md"),z=Math.max(0,X-cB-y$0-Z.length-4),{body:J,cut:U}=s$0(Y,z),K=U.length>0,W=[Z,J].filter((H)=>H.length>0),V=`${W.join(`
|
|
3431
3431
|
|
|
3432
|
-
`).length} chars \xB7 ${$.took_ms} ms \xB7 cache ${$.cache}`;if(K)V+=` \xB7 cut ${U.join(",")}`;if(V.length>cB)V=V.slice(0,cB);V+=` \xB7 ${
|
|
3432
|
+
`).length} chars \xB7 ${$.took_ms} ms \xB7 cache ${$.cache}`;if(K)V+=` \xB7 cut ${U.join(",")}`;if(V.length>cB)V=V.slice(0,cB);V+=` \xB7 ${d$0($)}`;let G=`${W.join(`
|
|
3433
3433
|
|
|
3434
3434
|
`)}
|
|
3435
3435
|
|
|
3436
3436
|
${V}
|
|
3437
|
-
`;return{text:G,chars:G.length,truncated:K,cut:U}}var oB=2000,iB=200,cB=90,
|
|
3437
|
+
`;return{text:G,chars:G.length,truncated:K,cut:U}}var oB=2000,iB=200,cB=90,y$0=225,f$0="myc review",S$0=8,Rv,dB,x$0=3,Dv=3,_v,l$0,c$0=40;var Ev=v(()=>{o();V0();w5();v8();HK();LY();j0();Rv=["agent","leader","human"];dB=J8;_v={openStore:$0.openStore,openPersonal:($)=>D6($)};l$0=[{name:"budget",value:"number",description:`output character budget (default ${oB})`},{name:"role",value:"string",description:"agent|leader|human (default agent)"},{name:"focus",value:"string",description:"filter L2/L3 digest by a substring topic"},{name:"format",value:"string",description:"agent|md|json (default agent)"},{name:"session",value:"string",description:"session identity for memory reach (default $MYC_SESSION_ID/$CLAUDE_SESSION_ID)"},{name:"repo",value:"string",description:"repository scope (S59): a repo name, or `all` to drop the filter"}]});var yv=`<!doctype html>
|
|
3438
3438
|
<html lang="en">
|
|
3439
3439
|
<head>
|
|
3440
3440
|
<meta charset="utf-8">
|
|
@@ -7892,18 +7892,18 @@ self.onmessage = (event: MessageEvent<InMessage>): void => {
|
|
|
7892
7892
|
}
|
|
7893
7893
|
if (msg.type === "layout") run(msg);
|
|
7894
7894
|
};
|
|
7895
|
-
`;var wv=()=>{};function uv($){return new Bun.Transpiler({loader:"ts",target:"browser"}).transformSync($)}function lv(){if(aB!==void 0)return aB;let $=new Map;return $.set("/",{body:hv,type:"text/html; charset=utf-8"}),$.set("/index.html",{body:hv,type:"text/html; charset=utf-8"}),$.set("/app.css",{body:
|
|
7895
|
+
`;var wv=()=>{};function uv($){return new Bun.Transpiler({loader:"ts",target:"browser"}).transformSync($)}function lv(){if(aB!==void 0)return aB;let $=new Map;return $.set("/",{body:hv,type:"text/html; charset=utf-8"}),$.set("/index.html",{body:hv,type:"text/html; charset=utf-8"}),$.set("/app.css",{body:Z80,type:"text/css; charset=utf-8"}),$.set("/app.js",{body:uv(Y80),type:mv}),$.set("/layout.worker.js",{body:uv(z80),type:mv}),aB=$,$}function sB($){return lv().get($)}function rB(){let $=0;for(let X of lv().values())$+=Buffer.byteLength(X.body,"utf8");return $}var hv,Z80,Y80,z80,mv="text/javascript; charset=utf-8",aB;var tB=v(()=>{vv();fv();gv();wv();hv=yv,Z80=Sv,Y80=bv,z80=xv});function J80($){try{let X=JSON.parse($);return typeof X.type==="string"?X.type:"task"}catch{return"task"}}function U80($){return{id:$.id,title:$.title,priority:$.priority,type:J80($.attrs),assignee:$.assignee,updated_at:$.updated_at}}function W80($){let X=new Map,Z=new Map;if(!$.has("edges"))return{parentOf:X,progressOf:Z};for(let Y of $.all(K80)){X.set(Y.child_id,{id:Y.parent_id,title:Y.parent_title});let z=Z.get(Y.parent_id);if(z===void 0)z={done:0,cancelled:0,total:0},Z.set(Y.parent_id,z);if(z.total+=1,Y.child_status==="closed")z.done+=1;else if(Y.child_status==="cancelled")z.cancelled+=1}return{parentOf:X,progressOf:Z}}function V80($,X){let Z=X.parentOf.get($.id),Y=X.progressOf.get($.id);if(Z===void 0&&Y===void 0)return $;return{...$,...Z!==void 0?{parent:Z}:{},...Y!==void 0?{progress:Y}:{}}}function cv($,X){let Z=performance.now(),Y={columns:Object.fromEntries(pv.map((U)=>[U,[]])),took_ms:0};if(!$.has("nodes"))return Y;let z=W80($),J={};for(let U of pv){let K=$.all(G80[U],[X.scope]).map(U80).map((W)=>V80(W,z));K.sort((W,V)=>W.priority-V.priority||V.updated_at-W.updated_at),J[U]=K}return{columns:J,took_ms:Math.round(performance.now()-Z)}}function iv($,X){if(!$.has("nodes")||!$.has("edges"))return[];return $.all(H80,[X]).map((Z)=>{let Y={};try{Y=JSON.parse(Z.attrs)}catch{}let z=typeof Y.type==="string"?Y.type:Z.kind;return{id:Z.id,title:Z.title,kind:Z.kind,status:Z.status,priority:Z.priority,type:z}})}var pv,tY="id, title, priority, assignee, attrs, updated_at",K80=`
|
|
7896
7896
|
SELECT c.id AS child_id, c.status AS child_status, p.id AS parent_id, p.title AS parent_title
|
|
7897
7897
|
FROM edges e
|
|
7898
7898
|
JOIN nodes c ON c.id = e.src
|
|
7899
7899
|
JOIN nodes p ON p.id = e.dst
|
|
7900
7900
|
WHERE e.type = 'parent' AND e.deleted_at IS NULL
|
|
7901
|
-
AND c.deleted_at IS NULL AND p.deleted_at IS NULL`,
|
|
7901
|
+
AND c.deleted_at IS NULL AND p.deleted_at IS NULL`,G80,H80=`
|
|
7902
7902
|
SELECT n.id AS id, n.title AS title, n.kind AS kind, n.status AS status,
|
|
7903
7903
|
n.priority AS priority, n.attrs AS attrs
|
|
7904
7904
|
FROM edges e JOIN nodes n ON n.id = e.dst
|
|
7905
7905
|
WHERE e.src = ?1 AND e.type = 'blocks' AND e.deleted_at IS NULL
|
|
7906
|
-
AND n.deleted_at IS NULL AND n.status = 'open' AND n.open_blockers = 1`;var nv=v(()=>{pv=["open","blocked","in_progress","closed","cancelled"];
|
|
7906
|
+
AND n.deleted_at IS NULL AND n.status = 'open' AND n.open_blockers = 1`;var nv=v(()=>{pv=["open","blocked","in_progress","closed","cancelled"];G80={open:`SELECT ${tY} FROM nodes
|
|
7907
7907
|
WHERE scope=?1 AND kind='task' AND status='open' AND open_blockers=0 AND deleted_at IS NULL`,blocked:`SELECT ${tY} FROM nodes
|
|
7908
7908
|
WHERE scope=?1 AND kind='task' AND status='open' AND open_blockers>0 AND deleted_at IS NULL`,in_progress:`SELECT ${tY} FROM nodes
|
|
7909
7909
|
WHERE scope=?1 AND kind='task' AND status='in_progress' AND deleted_at IS NULL`,closed:`SELECT ${tY} FROM nodes
|
|
@@ -7911,37 +7911,37 @@ SELECT n.id AS id, n.title AS title, n.kind AS kind, n.status AS status,
|
|
|
7911
7911
|
ORDER BY updated_at DESC LIMIT 100`,cancelled:`SELECT ${tY} FROM nodes
|
|
7912
7912
|
WHERE scope=?1 AND kind='task' AND status='cancelled' AND deleted_at IS NULL
|
|
7913
7913
|
ORDER BY updated_at DESC LIMIT 100`}});function Z6($,X,Z,Y,z){return{ok:!1,status:$,code:X,msg:Z,hint:Y,degraded:[],warn:[],...z!==void 0?{extra:z}:{}}}function av($){switch($){case 2:return 400;case 3:return 404;case 4:return 409;case 5:return 422;case 7:return 503;case 8:return 403;case 9:return 504;default:return 500}}async function q4($,X){let Z;try{Z=await $([...X,"--json"])}catch(K){let W=K instanceof Error?K.message:String(K);return Z6(500,"write.engine",`write path failed: ${W}`)}let Y=Z.stdout.trim().split(`
|
|
7914
|
-
`).filter((K)=>K.length>0).pop()??"",z;try{z=JSON.parse(Y)}catch{return Z6(500,"write.envelope",`write path returned no envelope (code ${Z.code}): ${Y.slice(0,200)}`)}let J=z.meta?.degraded??[],U=z.warn??[];if(!z.ok||z.error!==void 0){let K=z.error??{code:"write.failed",msg:"command refused without a code",exit:1};return{ok:!1,status:av(K.exit),code:K.code,msg:K.msg,hint:K.hint,degraded:J,warn:U}}return{ok:!0,status:200,data:z.data??{},degraded:J,warn:U}}function eB($,X){let Z=["-C",$,"--db",X];return async(Y)=>{let{run:z,defaultRegistry:J,registerAll:U}=await Promise.resolve().then(() => (v8(),nI));if(J.top.length===0)U(J);let K=await z([...Z,...Y]),W=typeof K.stdout==="string"?K.stdout:[...K.stdout].join("");return{code:K.code,stdout:W,stderr:K.stderr}}}function
|
|
7915
|
-
${Z}`:X];if($.status!==void 0)return Z6(422,"precond.use_op","status is not set at creation: a note is born active","note statuses (active/superseded/retracted) are changed by the shared path myc update");let J=$.tags;if(J!==void 0&&J!==null){let Q=h5("tags",J);if(!Q.ok)return v0(Q.msg);z.push("--tag",Q.text)}let U=$.layer;if(U!==void 0&&U!==null){let Q=
|
|
7914
|
+
`).filter((K)=>K.length>0).pop()??"",z;try{z=JSON.parse(Y)}catch{return Z6(500,"write.envelope",`write path returned no envelope (code ${Z.code}): ${Y.slice(0,200)}`)}let J=z.meta?.degraded??[],U=z.warn??[];if(!z.ok||z.error!==void 0){let K=z.error??{code:"write.failed",msg:"command refused without a code",exit:1};return{ok:!1,status:av(K.exit),code:K.code,msg:K.msg,hint:K.hint,degraded:J,warn:U}}return{ok:!0,status:200,data:z.data??{},degraded:J,warn:U}}function eB($,X){let Z=["-C",$,"--db",X];return async(Y)=>{let{run:z,defaultRegistry:J,registerAll:U}=await Promise.resolve().then(() => (v8(),nI));if(J.top.length===0)U(J);let K=await z([...Z,...Y]),W=typeof K.stdout==="string"?K.stdout:[...K.stdout].join("");return{code:K.code,stdout:W,stderr:K.stderr}}}function Q80($,X,Z){if(X==="confirm")return{argv:["review","confirm",$],clockFields:[]};let Y=R$(Z,"reason")?.trim();if(Y===void 0||Y.length===0)return v0("reject requires 'reason'","the reason is written into the node: whoever meets this candidate again reads it");return{argv:["review","reject",$,"--reason",Y],clockFields:[]}}function dv($,X){return{code:"reason.unwritten",msg:`the ${$} reason is not saved in the graph: "${X.slice(0,120)}"`}}function R$($,X){let Z=$[X];return typeof Z==="string"?Z:void 0}function v0($,X){return Z6(400,"usage.invalid",$,X)}function h5($,X){if($==="tags"){if(!Array.isArray(X))return{ok:!1,msg:"'tags' must be an array of strings"};let Z=X.map((Y)=>typeof Y==="string"?Y.trim():"");if(Z.some((Y)=>Y.length===0))return{ok:!1,msg:"empty tag in 'tags'"};if(Z.some((Y)=>Y.includes(",")))return{ok:!1,msg:"a comma inside a tag is indistinguishable from the list separator"};return{ok:!0,text:Z.join(",")}}if($==="priority"){if(typeof X==="number")return{ok:!0,text:String(X)};if(typeof X==="string")return{ok:!0,text:X};return{ok:!1,msg:"'priority' must be P0..P3, 0..3 or a number"}}if(typeof X!=="string")return{ok:!1,msg:`'${$}' must be a string`};if($==="body"&&X==="-")return{ok:!1,msg:"body '-' means stdin for the CLI and makes no sense over HTTP"};return{ok:!0,text:X}}function F80($){if(typeof $!=="string")return{ok:!1,msg:"'layer' must be a string L0..L3"};let X=/^L?([0-3])$/i.exec($.trim());if(!X)return{ok:!1,msg:`invalid layer '${$}'; allowed: L0..L3`};return{ok:!0,text:`L${X[1]}`}}function j80($){let X=R$($,"title")?.trim();if(X===void 0||X.length===0)return v0("missing 'title'","POST /api/nodes {kind: 'note', title, body?, tags?\u2026}");if(X==="-")return v0("text '-' means stdin for the CLI and makes no sense over HTTP");let Z=R$($,"body");if(Z==="-")return v0("body '-' means stdin for the CLI and makes no sense over HTTP");let z=["remember",Z!==void 0&&Z.length>0?`${X}
|
|
7915
|
+
${Z}`:X];if($.status!==void 0)return Z6(422,"precond.use_op","status is not set at creation: a note is born active","note statuses (active/superseded/retracted) are changed by the shared path myc update");let J=$.tags;if(J!==void 0&&J!==null){let Q=h5("tags",J);if(!Q.ok)return v0(Q.msg);z.push("--tag",Q.text)}let U=$.layer;if(U!==void 0&&U!==null){let Q=F80(U);if(!Q.ok)return v0(Q.msg);z.push("--layer",Q.text)}let K=$.acl;if(K!==void 0&&K!==null){let Q=h5("acl",K);if(!Q.ok)return v0(Q.msg);z.push("--acl",Q.text)}let W=$.source;if(W!==void 0&&W!==null){let Q=h5("source",W);if(!Q.ok)return v0(Q.msg);z.push("--source",Q.text)}let V=$.anchor;if(V!==void 0&&V!==null){let Q=h5("anchor",V);if(!Q.ok)return v0(Q.msg);z.push("--anchor",Q.text)}let G=$.reach;if(G!==void 0&&G!==null){if(typeof G!=="string"||!ov.includes(G))return v0(`'reach' must be ${ov.join(" | ")}`,"session by default; project is an explicit decision");z.push("--reach",G)}let H=R$($,"session");if(H!==void 0)z.push("--session",H);let N=Object.keys($).filter((Q)=>!["kind","title","body","tags","layer","acl","source","anchor","reach","session","if_match"].includes(Q));if(N.length>0)return v0(`fields foreign to a note: ${N.join(", ")}`,"myc remember has no flags for priority, assignee, estimate, parent or dependencies");return{argv:z,clockFields:[]}}function $T($){let X=R$($,"kind");if(X==="note")return j80($);let Z=X!==void 0?T80[X]:void 0;if(Z!==void 0)return Z6(501,"unsupported.kind",`kind '${X}' cannot be created: ${Z}`);let Y=R$($,"title")?.trim();if(Y===void 0||Y.length===0)return v0("missing 'title'","POST /api/nodes {title, kind?, body?, priority?, tags?}");if($.status!==void 0)return Z6(422,"precond.use_op","status is not set at creation: a node is born in the initial status of its scale","status changes go through POST /api/nodes/<id>/op");let z=["create",Y];if(X!==void 0)z.push("--kind",q80[X]??X);for(let V of["body","priority","tags","assignee","acl","estimate"]){let G=$[V];if(G===void 0||G===null)continue;let H=h5(V,G);if(!H.ok)return v0(H.msg);z.push(eY[V].flag,H.text)}let J=R$($,"repo");if(J!==void 0)z.push("--repo",J.trim());let U=R$($,"parent");if(U!==void 0)z.push("--parent",U);let K=$.dep;if(Array.isArray(K)&&K.length>0)z.push("--dep",K.join(","));let W=R$($,"anchor");if(W!==void 0)z.push("--anchor",W);return{argv:z,clockFields:[]}}function XT($,X){if(X.status!==void 0){let K=typeof X.status==="string"?X.status:"",W=N80[K];return Z6(422,"precond.use_op",W!==void 0?`status '${K}' is not assigned by a write: ${W}`:`status is not assigned by a write; operations: ${T4.join(", ")}`,`POST /api/nodes/${$}/op {"op":"\u2026"}`)}let Z=["update",$],Y=[],z=!1;for(let[K,W]of Object.entries(eY)){let V=X[K];if(V===void 0)continue;let G=h5(K,V);if(!G.ok)return v0(G.msg);Z.push(W.flag,G.text),Y.push(W.clock)}for(let K of Object.keys(X)){let W=B80[K];if(W!==void 0)return Z6(501,"unsupported.field",`field '${K}' is not written: ${W}`)}let J=X.parent;if(J!==void 0){if(J===null||typeof J==="string"&&J.trim().length===0)Z.push("--no-parent");else if(typeof J==="string")Z.push("--parent",J.trim());else return v0("'parent' must be an epic id string, or an empty string to leave the epic");z=!0}let U=Object.keys(X).filter((K)=>eY[K]===void 0&&K!=="if_match"&&K!=="parent");if(U.length>0)return v0(`unknown fields: ${U.join(", ")}`,`editable: ${v9.join(", ")}`);if(Y.length===0&&!z)return v0("nothing to update: no fields",`fields: ${v9.join(", ")}, parent`);return{argv:Z,clockFields:Y}}function ZT($,X){let Z=R$(X,"op"),Y=[...T4,...$3].join(", ");if(Z===void 0)return v0("missing 'op'",`operations: ${Y}`);let z=L80[Z];if(z!==void 0)return Z6(501,"unsupported.op",`operation '${Z}' is not implemented: ${z}`);if($3.includes(Z))return Q80($,Z,X);if(!T4.includes(Z))return v0(`unknown operation '${Z}'`,`allowed: ${Y}`);let J=X.lease_minutes,U=typeof J==="number"&&Number.isInteger(J)&&J>=5&&J<=480?J:J===void 0?30:void 0;if(U===void 0)return v0("'lease_minutes' must be an integer from 5 to 480");switch(Z){case"claim":case"extend":{let K=["claim",$,"--lease",`${U}m`];if(X.steal===!0)K.push("--steal");return{argv:K,clockFields:[]}}case"release":{let K=["release",$];if(X.force===!0)K.push("--force");return{argv:K,clockFields:[]}}case"close":{let K=R$(X,"reason")?.trim();if(K===void 0||K.length===0)return v0("close requires 'reason'","the reason goes into the project memory");let W=["close",$,"--reason",K],V=R$(X,"outcome");if(V!==void 0)W.push("--outcome",V);let G=R$(X,"verify");if(G!==void 0)W.push("--verify",G);let H=R$(X,"duplicate_of");if(H!==void 0)W.push("--dup",H);return{argv:W,clockFields:[]}}case"reopen":{let K=R$(X,"reason")?.trim();if(K===void 0||K.length===0)return v0("reopen requires 'reason'");return{argv:["update",$,"--status","open"],clockFields:[],warn:[dv("reopen",K)]}}case"cancel":{let K=R$(X,"reason")?.trim();if(K===void 0||K.length===0)return v0("cancel requires 'reason'","a cancel is a judgment, and its reason is read later");return{argv:["update",$,"--status","cancelled"],clockFields:[],warn:[dv("cancel",K)]}}case"assign":{let K=R$(X,"assignee");if(K===void 0)return v0("assign requires 'assignee'");return{argv:["update",$,"--assign",K],clockFields:["assignee"]}}case"priority":{let K=X.priority;if(K===void 0)return v0("priority requires 'priority'");let W=h5("priority",K);if(!W.ok)return v0(W.msg);return{argv:["update",$,"--priority",W.text],clockFields:["priority"]}}}}function X3($,X){let Z=$.all("SELECT field, CAST(hlc AS TEXT) AS hlc, site_id FROM field_clock WHERE entity_id = ?1",[X]),Y={};for(let z of Z)Y[z.field]=`${z.hlc}.${z.site_id}`;return Y}function YT($,X,Z,Y){if(Y===void 0||Y===null)return;if(typeof Y!=="object"||Array.isArray(Y))return v0("'if_match' must be an object {field: clock}");let z=Y,J=X3($,X),U=[];for(let[K,W]of Object.entries(z)){let V=eY[K];if(V===void 0)return v0(`if_match: unknown field '${K}'`,`fields: ${v9.join(", ")}`);if(!Z.clockFields.includes(V.clock))return v0(`if_match: field '${K}' is not written by this request`,"clocks are declared only for the request's fields \u2014 CRDT merges the rest");let G=J[V.clock]??null;if((W??null)!==G)U.push({field:K,expected:W??null,actual:G})}if(U.length===0)return;return Z6(409,"conflict.version",`node ${X} changed since it was read, fields: ${U.map((K)=>K.field).join(", ")}`,"re-read GET /api/nodes/<id>, merge the edit and retry",{conflicts:U,clk:J})}function zT($=process.env){return $.MYC_ACTOR??$.USER??"agent"}function JT($,X,Z){if($.meta("acl_enforced")!=="1")return;let Y=$.one("SELECT acl, owner_id, team_id, agent_id FROM nodes WHERE id = ?1",[X]);if(Y===void 0)return;let z=(J)=>Z6(403,"denied.acl",`${X}: ${J} (principal ${Z})`);switch(Y.acl){case"private":return Y.owner_id===Z?void 0:z("the node is private and owned by someone else");case"agent":return Y.agent_id===Z?void 0:z("the node is pinned to another agent");case"restricted":return($.one("SELECT count(*) AS n FROM acl_grants WHERE node_id = ?1 AND principal = ?2",[X,Z])?.n??0)>0?void 0:z("the node is restricted and there is no grant");default:return}}function UT($,X){let Z=$.one(`SELECT id, kind, title, body, status, priority, assignee, acl, attrs,
|
|
7916
7916
|
open_blockers, lease_holder, lease_expires, updated_at, deleted_at
|
|
7917
|
-
FROM nodes WHERE id = ?1`,[X]);if(Z===void 0)return;let Y={};try{Y=JSON.parse(String(Z.attrs??"{}"))}catch{Y={}}return{...Z,id:String(Z.id),attrs:Y,clk:X3($,X)}}var eY,v9,T4,$3,
|
|
7917
|
+
FROM nodes WHERE id = ?1`,[X]);if(Z===void 0)return;let Y={};try{Y=JSON.parse(String(Z.attrs??"{}"))}catch{Y={}}return{...Z,id:String(Z.id),attrs:Y,clk:X3($,X)}}var eY,v9,T4,$3,N80,L80,B80,T80,q80,ov;var Z3=v(()=>{eY={title:{flag:"--title",clock:"title"},body:{flag:"--body",clock:"body"},priority:{flag:"--priority",clock:"priority"},assignee:{flag:"--assign",clock:"assignee"},acl:{flag:"--acl",clock:"acl"},tags:{flag:"--tag",clock:"attrs.tags"},estimate:{flag:"--estimate",clock:"attrs.estimate_min"}},v9=Object.keys(eY),T4=["claim","release","close","reopen","assign","priority","extend","cancel"],$3=["confirm","reject"];N80={in_progress:"claim \u2014 in_progress is taken with a lease, otherwise two agents consider the task theirs",blocked:"none: blocked is computed from open blockers and cannot be set",closed:"close \u2014 closing requires a reason and reports what it unblocked",open:"release \u2014 a task returns to the queue only by dropping its lease",cancelled:"cancel \u2014 a cancel must report what it released into the queue"},L80={note:"a note on a node needs a replies_to edge, and the CLI has no command for arbitrary edges; "+"MCP writes it bypassing the CLI \u2014 the surfaces must be unified there, not with a third branch here",comment:"a comment on a node needs a replies_to edge, and the CLI has no command for arbitrary edges "+"(dep add only knows blocks/blocked-by); create --parent does not fit here \u2014 it would distort "+"the epic progress in board.ts. A CLI command for the replies_to edge is needed"},B80={type:"the engine cannot change attrs.type of an existing node: myc update has no such flag; the type is chosen at creation (--kind task|bug|epic|chore), and editing it on a live node "+"needs a flag in packages/cli \u2014 not a third write branch here",layer:"the layer of an existing node does not change through the shared write path: myc update has no layer flag; "+"the layer is set at creation (--layer on myc remember) or raised L0\u2192L2/L3 \u2014 "+"by a new node with a derived_from edge, not by editing this one",reach:"session reach (S58) is recorded at creation (--reach on myc remember); "+"a fact is promoted to project reach by an explicit decision \u2014 an exact repeat "+"with --reach project; the engine cannot change reach after the fact",repo:"repo reach (S59) is written at creation (--repo on myc create) and derived "+"from the call path; myc update has no reach flag \u2014 it does not change after the fact"},T80={fragment:"myc create has no --kind fragment: the core kind exists, but the CLI has no write path for it "+"(fragments are born on agent paths \u2014 absorb, import); "+"no third write branch is built here",entity:"myc create has no --kind entity: the core kind exists, but the CLI has no write path for it "+"(entities are born on agent paths \u2014 absorb, import); "+"no third write branch is built here"},q80={doc:"document"};ov=["session","project"]});async function sv($,X){let Z=["bootstrap"];if(X!==void 0)Z.push("--budget",String(X));return q4($,Z)}async function rv($){return q4($,["bootstrap","list"])}function tv($,X,Z=20){if(!$.has("oplog"))return[];let Y=Math.min(Math.max(Math.floor(Z),1),200);return $.all(O80,[X,Y]).map((J)=>({seq:J.seq,ts_ms:J.ts_ms,actor:J.actor,text:C80(J.value)}))}function C80($){if($===null)return null;try{let X=JSON.parse($);return typeof X==="string"?X:$}catch{return $}}function Y3($,X){return{ok:!1,status:400,code:"usage.invalid",msg:$,hint:X,degraded:[],warn:[]}}function ev($,X){let Z=X.text;if(typeof Z!=="string"||Z.length===0)return Y3("missing 'text'","POST /api/bootstrap/<key> {text: string, global?: boolean}");if(Z==="-")return Y3("text '-' means stdin for the CLI and makes no sense over HTTP");let Y=X.global;if(Y!==void 0&&typeof Y!=="boolean")return Y3("'global' \u2014 boolean");let z=["bootstrap","set"];if(Y===!0)z.push("--global");return z.push($,Z),{argv:z,clockFields:[]}}function $y($,X){let Z=X.op;if(Z!=="rm")return Y3(Z===void 0?"missing 'op'":`unknown operation '${String(Z)}'`,"allowed: rm");let Y=X.global;if(Y!==void 0&&typeof Y!=="boolean")return Y3("'global' \u2014 boolean");let z=["bootstrap","rm"];if(Y===!0)z.push("--global");return z.push($),{argv:z,clockFields:[]}}var O80=`
|
|
7918
7918
|
SELECT seq, ts_ms, actor, value
|
|
7919
7919
|
FROM oplog
|
|
7920
7920
|
WHERE entity_id = ?1 AND field = 'body'
|
|
7921
7921
|
ORDER BY hlc DESC
|
|
7922
|
-
LIMIT ?2`;var Xy=v(()=>{Z3()});function Zy($,X){if($==="task"){let Z=X.type;if(typeof Z==="string"&&Z.length>0)return Z}return $}function
|
|
7923
|
-
${Y}`:$.title;return{id:$.id,author:$.assignee.length>0?$.assignee:"agent",role:Z,body:z,created_at:$.created_at}}function
|
|
7922
|
+
LIMIT ?2`;var Xy=v(()=>{Z3()});function Zy($,X){if($==="task"){let Z=X.type;if(typeof Z==="string"&&Z.length>0)return Z}return $}function A80($){let X={};try{X=JSON.parse($.attrs)}catch{}return{id:$.id,title:$.title,kind:$.kind,status:$.status,priority:$.priority,type:Zy($.kind,X)}}function NK($,X,Z,Y){return $.all(X?P80:D80,[Z,Y]).map(A80)}function R80($){let X={};try{X=JSON.parse($.attrs)}catch{}let Z=typeof X.role==="string"&&X.role.length>0?X.role:"agent",Y=typeof $.body==="string"?$.body:"",z=Y.length>0?`${$.title}
|
|
7923
|
+
${Y}`:$.title;return{id:$.id,author:$.assignee.length>0?$.assignee:"agent",role:Z,body:z,created_at:$.created_at}}function _80($,X){return $.all(M80,[X]).map(R80)}function Yy($,X){if(!$.has("nodes")||!$.has("edges"))return;let Z=$.one(`SELECT id, kind, title, body, status, priority, assignee, acl, attrs, layer,
|
|
7924
7924
|
open_blockers, lease_holder, lease_expires, created_at, updated_at, closed_at
|
|
7925
7925
|
FROM nodes WHERE id = ?1 AND deleted_at IS NULL`,[X]);if(Z===void 0)return;let Y={};try{Y=JSON.parse(Z.attrs)}catch{}let z=Array.isArray(Y.tags)?Y.tags.filter((T)=>typeof T==="string"):[],J=C8(Y),U=A$(Y),K=Y.estimate_min,W=Z.lease_holder.length>0&&Z.lease_expires!==null&&Z.lease_expires>0?{holder:Z.lease_holder,expires:Z.lease_expires}:null,V=NK($,!1,X,"parent")[0]??null,G=NK($,!0,X,"parent").sort((T,q)=>T.priority-q.priority||T.id.localeCompare(q.id)),H=G.filter((T)=>T.status==="closed").length,N=G.filter((T)=>T.status==="cancelled").length,Q=G.length>0?{done:H,cancelled:N,total:G.length}:null,L=$.all(`SELECT e.type AS type, n.id AS id, n.title AS title
|
|
7926
7926
|
FROM edges e JOIN nodes n ON n.id = e.dst
|
|
7927
7927
|
WHERE e.src = ?1 AND e.deleted_at IS NULL AND n.deleted_at IS NULL
|
|
7928
|
-
AND e.type IN ('relates','derived_from','duplicates','supersedes')`,[X]),B={relates:"relates-to",derived_from:"derived-from"};return{id:Z.id,kind:Z.kind,type:Zy(Z.kind,Y),title:Z.title,body:Z.body,status:Z.status,priority:Z.priority,assignee:Z.assignee,acl:Z.acl,tags:z,estimate_min:typeof K==="number"?K:null,created_at:Z.created_at,updated_at:Z.updated_at,closed_at:Z.closed_at,open_blockers:Z.open_blockers,lease:W,layer:Z.layer,reach:J.reach,session:J.session,repo:U.repo,repo_state:U.state,parent:V,children:G,progress:Q,blocked_by:NK($,!0,X,"blocks"),blocks:NK($,!1,X,"blocks"),links:L.map((T)=>({type:B[T.type]??T.type,id:T.id,title:T.title})),comments:
|
|
7928
|
+
AND e.type IN ('relates','derived_from','duplicates','supersedes')`,[X]),B={relates:"relates-to",derived_from:"derived-from"};return{id:Z.id,kind:Z.kind,type:Zy(Z.kind,Y),title:Z.title,body:Z.body,status:Z.status,priority:Z.priority,assignee:Z.assignee,acl:Z.acl,tags:z,estimate_min:typeof K==="number"?K:null,created_at:Z.created_at,updated_at:Z.updated_at,closed_at:Z.closed_at,open_blockers:Z.open_blockers,lease:W,layer:Z.layer,reach:J.reach,session:J.session,repo:U.repo,repo_state:U.state,parent:V,children:G,progress:Q,blocked_by:NK($,!0,X,"blocks"),blocks:NK($,!1,X,"blocks"),links:L.map((T)=>({type:B[T.type]??T.type,id:T.id,title:T.title})),comments:_80($,X)}}var P80=`
|
|
7929
7929
|
SELECT n.id, n.title, n.kind, n.status, n.priority, n.attrs
|
|
7930
7930
|
FROM edges e JOIN nodes n ON n.id = e.src
|
|
7931
7931
|
WHERE e.dst = ?1 AND e.type = ?2
|
|
7932
|
-
AND e.deleted_at IS NULL AND n.deleted_at IS NULL`,
|
|
7932
|
+
AND e.deleted_at IS NULL AND n.deleted_at IS NULL`,D80=`
|
|
7933
7933
|
SELECT n.id, n.title, n.kind, n.status, n.priority, n.attrs
|
|
7934
7934
|
FROM edges e JOIN nodes n ON n.id = e.dst
|
|
7935
7935
|
WHERE e.src = ?1 AND e.type = ?2
|
|
7936
|
-
AND e.deleted_at IS NULL AND n.deleted_at IS NULL`,
|
|
7936
|
+
AND e.deleted_at IS NULL AND n.deleted_at IS NULL`,M80=`
|
|
7937
7937
|
SELECT n.id, n.title, n.body, n.assignee, n.attrs, n.created_at
|
|
7938
7938
|
FROM edges e JOIN nodes n ON n.id = e.src
|
|
7939
7939
|
WHERE e.dst = ?1 AND e.type = 'replies_to'
|
|
7940
7940
|
AND e.deleted_at IS NULL AND n.deleted_at IS NULL
|
|
7941
|
-
ORDER BY n.created_at ASC, n.id ASC`;var zy=v(()=>{o()});function
|
|
7942
|
-
FROM nodes WHERE id = ?1 AND deleted_at IS NULL`,[X])}function Uy($){try{let X=JSON.parse($);return typeof X==="object"&&X!==null&&!Array.isArray(X)?X:{}}catch{return{}}}function
|
|
7941
|
+
ORDER BY n.created_at ASC, n.id ASC`;var zy=v(()=>{o()});function E80($,X){return $.one(`SELECT id, title, status, actor, created_at, head_id, hlc, site_id, attrs
|
|
7942
|
+
FROM nodes WHERE id = ?1 AND deleted_at IS NULL`,[X])}function Uy($){try{let X=JSON.parse($);return typeof X==="object"&&X!==null&&!Array.isArray(X)?X:{}}catch{return{}}}function v80($){return Uy($).type==="decision"}function y9($){let X=Uy($).absorb;if(typeof X!=="object"||X===null||Array.isArray(X))return;let Z=X.reason;return typeof Z==="string"&&Z.length>0?Z:void 0}function KT($){return{id:$.id,title:$.title,status:$.status,author:$.actor,created_at:$.created_at}}function y80($){return{rows:(X,Z)=>$.all(Zz.version_rows.sql,[X,Z]),row:(X)=>$.one("SELECT id, head_id, hlc, site_id FROM nodes WHERE id = ?1 AND deleted_at IS NULL",[X]),supersedes:(X)=>{let Z=[];for(let Y of $.all("SELECT src, dst FROM edges WHERE type = 'supersedes' AND deleted_at IS NULL AND src = ?1",[X]))Z.push({newer:Y.src,older:Y.dst});for(let Y of $.all("SELECT src, dst FROM edges WHERE type = 'supersedes' AND deleted_at IS NULL AND dst = ?1",[X]))Z.push({newer:Y.src,older:Y.dst});return Z}}}function Ky($,X={}){let Z=performance.now(),Y=X.limit??I80,z=[];if(!$.has("nodes")||!$.has("edges"))return{chains:[],contradictions:[],total_decisions:0,degraded:z,took_ms:Math.round(performance.now()-Z)};let J=$.all(k80).filter((B)=>v80(B.attrs)),U=new Map(J.map((B)=>[B.id,B])),K=y80($),W=[],V=new Set,G=!1;for(let B of J){if(V.has(B.id))continue;let{graph:T,truncated:q}=e6(K,{id:B.id,head_id:B.head_id,hlc:B.hlc,site_id:B.site_id},GX+1);if(q)G=!0;let j=T.chain(B.id),O=T.head(B.id),A=T.heads(B.id);for(let D of j)V.add(D);let R=[];for(let D of j){let F=U.get(D)??E80($,D);if(F===void 0)continue;R.push({...KT(F),current:D===O,...y9(F.attrs)!==void 0?{reason:y9(F.attrs)}:{}})}if(R.length===0)continue;W.push({head:O,links:R,...A.length>1?{forked:A}:{}})}if(G)z.push({code:"decisions.chain_truncated",msg:"some version chains exceed the read budget \u2014 shown truncated"});let H=W;if(W.length>Y)z.push({code:"decisions.limit",msg:`more decisions than the read limit (${Y}) \u2014 some chains are not shown`}),H=W.slice(0,Y);H=[...H].sort((B,T)=>{let q=B.links.find((O)=>O.current);return(T.links.find((O)=>O.current)?.created_at??0)-(q?.created_at??0)});let N=$.all("SELECT src, dst FROM edges WHERE type = 'contradicts' AND deleted_at IS NULL"),Q=new Set,L=[];for(let B of N){let T=U.get(B.src),q=U.get(B.dst);if(T===void 0||q===void 0)continue;let j=T.id<q.id?`${T.id}\x00${q.id}`:`${q.id}\x00${T.id}`;if(Q.has(j))continue;if(Q.add(j),Jy.has(T.status)||Jy.has(q.status))continue;L.push({a:KT(T),b:KT(q),...(y9(T.attrs)??y9(q.attrs))!==void 0?{reason:y9(T.attrs)??y9(q.attrs)}:{}})}return L.sort((B,T)=>B.a.id<T.a.id?-1:B.a.id>T.a.id?1:0),{chains:H,contradictions:L,total_decisions:J.length,degraded:z,took_ms:Math.round(performance.now()-Z)}}var Jy,I80=2000,k80=`
|
|
7943
7943
|
SELECT id, title, status, actor, created_at, head_id, hlc, site_id, attrs
|
|
7944
|
-
FROM nodes WHERE deleted_at IS NULL`;var Wy=v(()=>{o();Jy=new Set(["closed","cancelled","superseded","retracted"])});import{Database as Vy}from"bun:sqlite";function WT($){try{l$()}catch(W){if(W instanceof m8||W instanceof L$)throw new u6(W.code,`${W.message} \u2014 fix: ${W.hint}`);throw W}let X;try{X=new Vy($,{readonly:!0}),q8(X)}catch(W){let V=W instanceof Error?W.message:String(W);throw new u6("db.open",`could not open the database read-only: ${V}`)}let Z=!1;try{X.query("SELECT 1 FROM sqlite_master LIMIT 1").all()}catch{X.close();try{X=new Vy($),q8(X),Z=!0}catch(W){let V=W instanceof Error?W.message:String(W);throw new u6("db.open",`could not open the database: ${V}`)}X.exec("PRAGMA query_only = 1")}for(let W of
|
|
7944
|
+
FROM nodes WHERE deleted_at IS NULL`;var Wy=v(()=>{o();Jy=new Set(["closed","cancelled","superseded","retracted"])});import{Database as Vy}from"bun:sqlite";function WT($){try{l$()}catch(W){if(W instanceof m8||W instanceof L$)throw new u6(W.code,`${W.message} \u2014 fix: ${W.hint}`);throw W}let X;try{X=new Vy($,{readonly:!0}),q8(X)}catch(W){let V=W instanceof Error?W.message:String(W);throw new u6("db.open",`could not open the database read-only: ${V}`)}let Z=!1;try{X.query("SELECT 1 FROM sqlite_master LIMIT 1").all()}catch{X.close();try{X=new Vy($),q8(X),Z=!0}catch(W){let V=W instanceof Error?W.message:String(W);throw new u6("db.open",`could not open the database: ${V}`)}X.exec("PRAGMA query_only = 1")}for(let W of S80)try{X.exec(W)}catch{}if(Z){if(X.query("PRAGMA query_only").get()?.query_only!==1)throw X.close(),new u6("db.open","a database without -wal/-shm was opened with a writable handle, but query_only is not supported \u2014 reading is unsafe")}let Y=new Map,z=(W)=>{let V=Y.get(W);if(V===void 0)V=X.query(W),Y.set(W,V);return V},J=new Set,U=!1,K=()=>{if(U)return;try{let W=X.query("SELECT name FROM sqlite_master WHERE type IN ('table','view')").all();for(let V of W)J.add(V.name)}catch{}U=!0};return{path:$,one(W,V=[]){let G=z(W).get(...V);return G===null?void 0:G},all(W,V=[]){return z(W).all(...V)},has(W){return K(),J.has(W)},meta(W){if(K(),!J.has("myc_meta"))return;return this.one("SELECT value FROM myc_meta WHERE key = ?1",[W])?.value},journalMode(){try{return X.query("PRAGMA journal_mode").get()?.journal_mode??"unknown"}catch{return"unknown"}},raw(){return X},close(){Y.clear(),X.close()}}}var f80=2000,S80,u6;var VT=v(()=>{n0();S80=[`PRAGMA busy_timeout = ${f80}`,"PRAGMA query_only = 1","PRAGMA cache_size = -32768","PRAGMA mmap_size = 268435456","PRAGMA temp_store = MEMORY"];u6=class u6 extends Error{code;constructor($,X){super(X);this.code=$;this.name="VizDbError"}}});function QT($,X={}){let Z=performance.now(),Y=X.nodeLimit??25000,z=X.edgeLimit??60000;if(!$.has("nodes")||!$.has("edges"))return{...Gy,limit:Y};let J=$.one("SELECT count(*) AS n FROM nodes WHERE deleted_at IS NULL")?.n??0,U=$.one("SELECT count(*) AS n FROM edges WHERE deleted_at IS NULL")?.n??0;if(J===0)return{...Gy,limit:Y,took_ms:Math.round(performance.now()-Z)};let K=$.all(`
|
|
7945
7945
|
WITH deg AS (
|
|
7946
7946
|
SELECT src AS id, count(*) AS n FROM edges WHERE deleted_at IS NULL GROUP BY src
|
|
7947
7947
|
UNION ALL
|
|
@@ -7955,34 +7955,34 @@ SELECT n.id, n.kind, n.status, n.layer, n.priority, n.title, n.updated_at,
|
|
|
7955
7955
|
WHERE n.deleted_at IS NULL
|
|
7956
7956
|
ORDER BY deg DESC, n.updated_at DESC, n.id ASC
|
|
7957
7957
|
LIMIT ?1`,[Y]),W=new Map,V=Array(K.length);for(let H=0;H<K.length;H++){let N=K[H];W.set(N.id,H),V[H]={id:N.id,kind:N.kind,status:N.status,layer:N.layer,priority:N.priority,title:N.title,deg:N.deg,updated_at:N.updated_at}}let G=[];for(let H of $.all(`
|
|
7958
|
-
SELECT src, type, dst FROM edges WHERE deleted_at IS NULL LIMIT ?1`,[z])){let N=W.get(H.src),Q=W.get(H.dst);if(N===void 0||Q===void 0)continue;G.push({s:N,d:Q,t:H.type})}return{nodes:V,edges:G,total_nodes:J,total_edges:U,truncated:J>K.length,limit:Y,took_ms:Math.round(performance.now()-Z)}}var GT=25000,HT=60000,Gy;var NT=v(()=>{Gy={nodes:[],edges:[],total_nodes:0,total_edges:0,truncated:!1,limit:25000,took_ms:0}});import{existsSync as
|
|
7959
|
-
`)){let J=z.trim();if(J.length===0||J.startsWith("#"))continue;let U=/^\[([a-z_]+)\]$/i.exec(J);if(U){Y=U[1].toLowerCase();continue}let K=/^([a-z_]+)\s*=\s*(.+)$/.exec(J);if(!K)continue;let W=K[1],V=K[2].trim();if(Y==="ready"&&
|
|
7958
|
+
SELECT src, type, dst FROM edges WHERE deleted_at IS NULL LIMIT ?1`,[z])){let N=W.get(H.src),Q=W.get(H.dst);if(N===void 0||Q===void 0)continue;G.push({s:N,d:Q,t:H.type})}return{nodes:V,edges:G,total_nodes:J,total_edges:U,truncated:J>K.length,limit:Y,took_ms:Math.round(performance.now()-Z)}}var GT=25000,HT=60000,Gy;var NT=v(()=>{Gy={nodes:[],edges:[],total_nodes:0,total_edges:0,truncated:!1,limit:25000,took_ms:0}});import{existsSync as g80,readFileSync as b80,statSync as w80}from"fs";import{join as x80,resolve as Hy,sep as h80}from"path";function Qy($){let X="myc",Z={...LT},Y="";for(let z of $.split(`
|
|
7959
|
+
`)){let J=z.trim();if(J.length===0||J.startsWith("#"))continue;let U=/^\[([a-z_]+)\]$/i.exec(J);if(U){Y=U[1].toLowerCase();continue}let K=/^([a-z_]+)\s*=\s*(.+)$/.exec(J);if(!K)continue;let W=K[1],V=K[2].trim();if(Y==="ready"&&m80.includes(W)){let G=Number(V);if(Number.isFinite(G)&&G>=0)Z[W]=G}else if(Y===""&&W==="slug"){let G=/^"([a-z][a-z0-9]{1,7})"$/.exec(V);if(G)X=G[1]}}return{slug:X,weights:Z}}function BT($){let X="myc",Z=LT,Y=x80($,".myc","workspace.toml");if(g80(Y))try{let z=Qy(b80(Y,"utf8"));X=z.slug,Z=z.weights}catch{}return{slug:X,weights:Z,scope:X==="myc"?"":X}}function LK($){try{return w80($).size}catch{return 0}}function Ny($,X){if(X===void 0||X.trim().length===0)return"project";let Z=Hy(X,".myc"),Y=Hy($);return Y===Z||Y.startsWith(Z+h80)?"personal":"project"}var LT,m80;var BK=v(()=>{LT={priority:0.4,unblocks:0.27,freshness:0.14,anchors:0.1,type:0.09},m80=["priority","unblocks","freshness","anchors","type"]});function z3($,X){return $.all(X).map((Z)=>({key:Z.key??"\u2014",n:Number(Z.n??0)}))}function u80($,X){let Z=$.meta(X);if(Z===void 0)return null;let Y=Number(Z);return Number.isFinite(Y)?Y:null}function TT($,X){let Z=performance.now(),Y=[],z=$.has("nodes"),J=$.has("edges"),U=$.has("oplog"),K=$.has("jobs"),W=$.has("anchors"),V=$.has("schema_migrations");if(!z)Y.push({code:"schema.missing",msg:"the database has no nodes table \u2014 the schema is not applied; `myc init` or `myc doctor --schema`"});let G=V?$.one(sz($.has(y$)))?.v??null:null;if(G===null)Y.push({code:"schema.version_unknown",msg:V?"schema_migrations is empty \u2014 not a single migration applied":"the database has no schema_migrations table \u2014 the schema version cannot be read"});let H=LK(X.dbPath),N=LK(`${X.dbPath}-wal`),Q=LK(`${X.dbPath}-shm`);if(N>=By)Y.push({code:"wal.hard_limit",msg:`WAL ${(N/1048576).toFixed(1)} MB \u2014 above the hard ceiling of 32 MB; a checkpoint is needed`});else if(N>=Ly)Y.push({code:"wal.soft_limit",msg:`WAL ${(N/1048576).toFixed(1)} MB \u2014 above the soft ceiling of 8 MB`});let L=z?$.one("SELECT count(*) AS n FROM nodes WHERE deleted_at IS NULL")?.n??0:0,B=z?z3($,`SELECT kind AS key, count(*) AS n FROM nodes WHERE deleted_at IS NULL
|
|
7960
7960
|
GROUP BY kind ORDER BY n DESC`):[],T=J?$.one("SELECT count(*) AS n FROM edges WHERE deleted_at IS NULL")?.n??0:0,q=J?z3($,`SELECT type AS key, count(*) AS n FROM edges WHERE deleted_at IS NULL
|
|
7961
|
-
GROUP BY type ORDER BY n DESC`):[],j=$.meta("embed_fingerprint")??"",O=
|
|
7962
|
-
FROM oplog GROUP BY key ORDER BY n DESC LIMIT 8`):[],c=$.has("myc_health")?$.all("SELECT component, state, reason, since FROM myc_health ORDER BY component").map((l)=>({component:String(l.component),state:String(l.state),reason:String(l.reason??""),since:Number(l.since??0)})):[];for(let l of c){if(l.state==="ok")continue;Y.push({code:`health.${l.component}`,msg:`${l.component}: ${l.state}${l.reason.length>0?` \u2014 ${l.reason}`:""}`})}return{workspace:{slug:X.slug,db_path:X.dbPath,db_bytes:H,wal_bytes:N,shm_bytes:Q,journal_mode:$.journalMode(),schema_version:G,site_id:$.meta("site_id")??"",myc_version:$.meta("myc_version")??"",read_only:X.readOnly!==!1},nodes:{total:L,by_kind:B},edges:{total:T,by_type:q},embed:{model:j,dim:O,rows:A,pending:D,failed:F,state:P,detail:_},vec:{schema_applied:b,versions:E,loaded_here:R,detail:k},fts:{available:y,detail:y?"nodes_fts present":"no nodes_fts table"},jobs:{pending:g,failed:S,by_kind:w},anchors:{total:h,by_state:u},oplog:{count:a,last_seq:e?.seq??0,last_ts:e?.ts_ms??null,actors:r},components:c,degraded:Y,took_ms:Math.round(performance.now()-Z)}}var Ly=8388608,By=33554432;var qT=v(()=>{BK();n0()});function
|
|
7961
|
+
GROUP BY type ORDER BY n DESC`):[],j=$.meta("embed_fingerprint")??"",O=u80($,"embed_dim"),A=null,R=!1;try{if($.has("nodes_vec"))A=$.one("SELECT count(*) AS n FROM nodes_vec")?.n??0,R=!0}catch{A=null,R=!1}let D=K?$.one("SELECT count(*) AS n FROM jobs WHERE kind = 'embed' AND attempts < max_attempts")?.n??0:0,F=K?$.one("SELECT count(*) AS n FROM jobs WHERE kind = 'embed' AND attempts >= max_attempts")?.n??0:0,P="unknown",_;if(j.length===0)P="off",_="myc_meta.embed_fingerprint is empty \u2014 no vector written yet, search runs on FTS",Y.push({code:"embeddings.off",msg:"the embedding model has never written a vector (myc_meta.embed_fingerprint is empty) \u2014 "+"the vector branch of search and the absorb cosine are unavailable, semantics cut down to FTS"});else if(F>0)P="degraded",_=`${j}${O!==null?` dim=${O}`:""} \xB7 ${F} jobs exhausted their attempts`,Y.push({code:"embeddings.failed",msg:`${F} embedding jobs exhausted their attempts \u2014 some nodes will stay without a vector`});else P="ok",_=`${j}${O!==null?` dim=${O}`:""} \xB7 queue ${D}`;let E=$.has("schema_migrations_vec")?$.all("SELECT version FROM schema_migrations_vec ORDER BY version ASC").map((l)=>Number(l.version)):[],b=E.length>0;if(!b)Y.push({code:"vector.unavailable",msg:"the sqlite-vec extension (vec0) was never loaded: vector migrations are not applied \u2014 "+"vector search is off, the other surfaces work"});let k=b?`migrations applied (v${E.join(", v")})`+(R?` \xB7 vec0 loaded in the viewer process \xB7 ${A??0} vectors`:" \xB7 vec0 not loaded in the viewer process (the viewer does not load it)"):"vector migrations are not applied",y=$.has("nodes_fts");if(!y&&z)Y.push({code:"fts.missing",msg:"no nodes_fts table \u2014 full-text search is off"});let g=K?$.one("SELECT count(*) AS n FROM jobs WHERE attempts < max_attempts")?.n??0:0,S=K?$.one("SELECT count(*) AS n FROM jobs WHERE attempts >= max_attempts")?.n??0:0,w=K?z3($,"SELECT kind AS key, count(*) AS n FROM jobs GROUP BY kind ORDER BY n DESC"):[];if(S>0)Y.push({code:"jobs.failed",msg:`${S} background jobs exhausted their attempts`});let h=W?$.one("SELECT count(*) AS n FROM anchors")?.n??0:0,u=W?z3($,"SELECT state AS key, count(*) AS n FROM anchors GROUP BY state ORDER BY n DESC"):[],d=u.filter((l)=>l.key==="stale"||l.key==="lost").reduce((l,m)=>l+m.n,0);if(d>0)Y.push({code:"anchor.stale",msg:`${d} anchors stale \u2014 the binding no longer points at live code; myc anchor repair`});let a=U?$.one("SELECT count(*) AS n FROM oplog")?.n??0:0,e=U?$.one("SELECT seq, ts_ms FROM oplog ORDER BY seq DESC LIMIT 1"):void 0,r=U?z3($,`SELECT CASE WHEN actor = '' THEN '\u2014' ELSE actor END AS key, count(*) AS n
|
|
7962
|
+
FROM oplog GROUP BY key ORDER BY n DESC LIMIT 8`):[],c=$.has("myc_health")?$.all("SELECT component, state, reason, since FROM myc_health ORDER BY component").map((l)=>({component:String(l.component),state:String(l.state),reason:String(l.reason??""),since:Number(l.since??0)})):[];for(let l of c){if(l.state==="ok")continue;Y.push({code:`health.${l.component}`,msg:`${l.component}: ${l.state}${l.reason.length>0?` \u2014 ${l.reason}`:""}`})}return{workspace:{slug:X.slug,db_path:X.dbPath,db_bytes:H,wal_bytes:N,shm_bytes:Q,journal_mode:$.journalMode(),schema_version:G,site_id:$.meta("site_id")??"",myc_version:$.meta("myc_version")??"",read_only:X.readOnly!==!1},nodes:{total:L,by_kind:B},edges:{total:T,by_type:q},embed:{model:j,dim:O,rows:A,pending:D,failed:F,state:P,detail:_},vec:{schema_applied:b,versions:E,loaded_here:R,detail:k},fts:{available:y,detail:y?"nodes_fts present":"no nodes_fts table"},jobs:{pending:g,failed:S,by_kind:w},anchors:{total:h,by_state:u},oplog:{count:a,last_seq:e?.seq??0,last_ts:e?.ts_ms??null,actors:r},components:c,degraded:Y,took_ms:Math.round(performance.now()-Z)}}var Ly=8388608,By=33554432;var qT=v(()=>{BK();n0()});function c80($){try{let X=JSON.parse($);return X!==null&&typeof X==="object"&&!Array.isArray(X)?X:{}}catch{return{}}}function i80($){return Array.isArray($.tags)?$.tags.filter((X)=>typeof X==="string"):[]}function n80($){let X=c80($.attrs),Z=C8(X),Y=A$(X),z=typeof X.type==="string"&&X.type.length>0?X.type:null;return{id:$.id,kind:$.kind,subtype:z,title:$.title,status:$.status,layer:$.layer,acl:$.acl,tags:i80(X),reach:Z.reach,session:Z.session,repo:Y.repo,repo_state:Y.state,review:X.state===FT?FT:null,review_open:X.state===FT&&!l80.has($.status),updated_at:$.updated_at}}function jT($){return[...$.entries()].map(([X,Z])=>({key:X,n:Z})).sort((X,Z)=>Z.n-X.n||X.key.localeCompare(Z.key))}function d80($){let X=new Map,Z=new Map,Y={project:0,session:0,unknown:0},z={root:0,unknown:0,by_repo:new Map},J=0;for(let U of $){X.set(U.kind,(X.get(U.kind)??0)+1);let K=`L${U.layer}`;if(Z.set(K,(Z.get(K)??0)+1),Y[U.reach]+=1,U.repo_state==="root")z.root+=1;else if(U.repo_state==="unknown")z.unknown+=1;else z.by_repo.set(U.repo,(z.by_repo.get(U.repo)??0)+1);if(U.review_open)J+=1}return{by_kind:jT(X),by_layer:jT(Z),reach:Y,pending_review:J,repo:{...z,by_repo:jT(z.by_repo)}}}function OT($,X={}){let Z=performance.now();if(!$.has("nodes"))return{rows:[],total:0,shown:0,counts:{by_kind:[],by_layer:[],reach:{project:0,session:0,unknown:0},pending_review:0,repo:{root:0,unknown:0,by_repo:[]}},took_ms:Math.round(performance.now()-Z)};let Y=$.all(p80).map(n80),z=d80(Y),J=new Set((X.kinds??"").split(",").map((V)=>V.trim()).filter((V)=>Ty.includes(V))),U=(X.q??"").trim().toLowerCase(),K=Y.filter((V)=>{if(J.size>0&&!J.has(V.kind))return!1;if(X.layer!==void 0&&V.layer!==X.layer)return!1;if(X.reach!==void 0&&X.reach!==""&&V.reach!==X.reach)return!1;if(X.repo!==void 0&&X.repo!==""&&V.repo_state!==X.repo&&V.repo!==X.repo)return!1;if(U.length>0){if(!`${V.id} ${V.title} ${V.tags.join(" ")} ${V.subtype??""}`.toLowerCase().includes(U))return!1}return!0}),W=Math.max(1,Math.min(X.limit??f9,f9));return{rows:K.slice(0,W),total:Y.length,shown:Math.min(K.length,W),counts:z,took_ms:Math.round(performance.now()-Z)}}var Ty,FT="pending_review",qy,l80,p80=`
|
|
7963
7963
|
SELECT id, kind, title, status, layer, acl, attrs, updated_at
|
|
7964
7964
|
FROM nodes
|
|
7965
7965
|
WHERE deleted_at IS NULL AND kind IN ('note','doc','fragment','entity','skill')
|
|
7966
|
-
ORDER BY updated_at DESC, id ASC`,f9=2000;var CT=v(()=>{o();Ty=["note","doc","fragment","entity","skill"],qy=["superseded","retracted","cancelled"],
|
|
7966
|
+
ORDER BY updated_at DESC, id ASC`,f9=2000;var CT=v(()=>{o();Ty=["note","doc","fragment","entity","skill"],qy=["superseded","retracted","cancelled"],l80=new Set(qy)});function jy($){if($<86400000)return 1;if($<259200000)return 0.7;if($<604800000)return 0.4;return 0.15}function Oy($){if($===void 0||$.length===0)return{norm:0.5,label:"none"};if($.every((X)=>X==="fresh"))return{norm:1,label:"fresh"};if($.some((X)=>X==="stale"||X==="lost"))return{norm:0.2,label:"stale"};return{norm:0.6,label:"drifted"}}function Cy($){switch($){case"bug":return 1;case"task":return 0.5;default:return 0.25}}function X60($){let X=Math.max(0,$),Z=Math.floor(X/60000);if(Z<1)return`${Math.floor(X/1000)}s`;if(Z<60)return`${Z}m`;let Y=Math.floor(Z/60);if(Y<24)return`${Y}h`;return`${Math.floor(Y/24)}d`}function Ay($,X,Z,Y,z){let J={};try{J=JSON.parse($.attrs)}catch{}let U=typeof J.type==="string"?J.type:"task",K=Math.max(0,z-w7({updated_at:$.updated_at,attrs:J})),W=Oy(Z),V=a80[$.priority]??0,G=Math.min(X,Fy)/Fy,H=jy(K),N=Cy(U),Q=[{key:"priority",label:`P${$.priority}`,weight:Y.priority,norm:V,value:S9(Y.priority*V)},{key:"unblocks",label:`unblocks ${X}`,weight:Y.unblocks,norm:G,value:S9(Y.unblocks*G)},{key:"freshness",label:`freshness ${X60(K)}`,weight:Y.freshness,norm:H,value:S9(Y.freshness*H)},{key:"anchors",label:`anchors ${W.label}`,weight:Y.anchors,norm:W.norm,value:S9(Y.anchors*W.norm)},{key:"type",label:U,weight:Y.type,norm:N,value:S9(Y.type*N)}];return{id:$.id,title:$.title,priority:$.priority,type:U,assignee:$.assignee,unblocks:X,age_ms:K,anchors:W.label,score:S9(Q.reduce((L,B)=>L+B.value,0)),terms:Q}}function AT($,X){let Z=performance.now(),Y=X.limit??50,z={rows:[],ready:0,blocked:0,in_progress:0,weights:X.weights,took_ms:0};if(!$.has("nodes")||!$.has("edges"))return z;let J=X.now??Date.now(),U=$.all(s80,[X.scope]),K=new Map;for(let G of $.all(r80))K.set(G.id,G.n);let W=new Map;for(let G of $.all(t80)){let H=W.get(G.id);if(H===void 0)W.set(G.id,[G.st]);else H.push(G.st)}let V=U.map((G)=>Ay(G,K.get(G.id)??0,W.get(G.id),X.weights,J));return V.sort((G,H)=>H.score-G.score||G.priority-H.priority||G.id.localeCompare(H.id)),{rows:V.slice(0,Y),ready:V.length,blocked:$.one(e80,[X.scope])?.n??0,in_progress:$.one($60,[X.scope])?.n??0,weights:X.weights,took_ms:Math.round(performance.now()-Z)}}var o80="('closed','cancelled','superseded','retracted')",a80,Fy=3,s80=`
|
|
7967
7967
|
SELECT id, priority, status, assignee, title, updated_at, attrs
|
|
7968
7968
|
FROM nodes
|
|
7969
7969
|
WHERE scope = ?1 AND kind = 'task' AND status = 'open'
|
|
7970
|
-
AND open_blockers = 0 AND deleted_at IS NULL`,
|
|
7970
|
+
AND open_blockers = 0 AND deleted_at IS NULL`,r80,t80=`
|
|
7971
7971
|
SELECT e.src AS id, n.status AS st
|
|
7972
7972
|
FROM edges e JOIN nodes n ON n.id = e.dst
|
|
7973
7973
|
WHERE e.type = 'touches' AND e.deleted_at IS NULL
|
|
7974
|
-
AND n.kind = 'anchor' AND n.deleted_at IS NULL`,
|
|
7974
|
+
AND n.kind = 'anchor' AND n.deleted_at IS NULL`,e80=`
|
|
7975
7975
|
SELECT count(*) AS n FROM nodes
|
|
7976
7976
|
WHERE scope = ?1 AND kind = 'task' AND status = 'open'
|
|
7977
|
-
AND open_blockers > 0 AND deleted_at IS NULL
|
|
7977
|
+
AND open_blockers > 0 AND deleted_at IS NULL`,$60=`
|
|
7978
7978
|
SELECT count(*) AS n FROM nodes
|
|
7979
7979
|
WHERE scope = ?1 AND kind = 'task' AND status = 'in_progress'
|
|
7980
|
-
AND deleted_at IS NULL`,S9=($)=>Math.round($*100)/100;var PT=v(()=>{o();
|
|
7980
|
+
AND deleted_at IS NULL`,S9=($)=>Math.round($*100)/100;var PT=v(()=>{o();a80=[1,0.6666666666666666,0.3333333333333333,0],r80=`
|
|
7981
7981
|
SELECT e.src AS id, count(*) AS n
|
|
7982
7982
|
FROM edges e JOIN nodes d ON d.id = e.dst
|
|
7983
7983
|
WHERE e.type = 'blocks' AND e.deleted_at IS NULL
|
|
7984
|
-
AND d.deleted_at IS NULL AND d.status NOT IN ${
|
|
7985
|
-
GROUP BY e.src`});function
|
|
7984
|
+
AND d.deleted_at IS NULL AND d.status NOT IN ${o80}
|
|
7985
|
+
GROUP BY e.src`});function Z60($,X){return{arm:$.arm,modelId:$.modelId,effort:$.effort,harness:$.harness,attempts:$.attempts,qualityMean:$.qualityMean,quality:$.quality,costUsdMean:$.costUsdMean,costedAttempts:$.costedAttempts,costCoverage:$.costCoverage,cleanRate:$.cleanRate,enoughData:$.enoughData,isCheapest:X.cheapest===$.arm,isEqualGroup:X.equalGroup.includes($.arm)}}function Y60($,X,Z){return{available:!1,classes:[],coverage:{attempts:0,finished:0,withCost:0,arms:0,classes:0,tasksClosed:0,tasksAttributed:0},outcomeVersion:0,minAttempts:$,credibleMass:0.9,degraded:X,took_ms:Math.round(performance.now()-Z)}}function DT($,X={}){let Z=performance.now(),Y=X.minAttempts??3;if(!$.has("swarm_attempt"))return Y60(Y,[{code:"swarm.missing",msg:"no swarm_attempt table \u2014 attribution has not been started for a single attempt"}],Z);let z=gY($.raw(),{taskClass:X.taskClass,since:X.since,minAttempts:X.minAttempts}),J=[];if(z.classes.length===0)J.push({code:"swarm.no_attribution",msg:"no attribution: not a single closed attempt"});for(let G of z.classes)if(G.answer==="single_arm")J.push({code:`routing.single_arm.${G.taskClass}`,msg:`${G.taskClass}: nothing to compare \u2014 ${G.why}`});else if(G.answer==="insufficient_attempts")J.push({code:`routing.insufficient_attempts.${G.taskClass}`,msg:`${G.taskClass}: not enough observations \u2014 ${G.why}`});else if(G.answer==="no_cost_data")J.push({code:`routing.no_cost_data.${G.taskClass}`,msg:`${G.taskClass}: ${G.why}`});else if(G.separationPending)J.push({code:`routing.separation_pending.${G.taskClass}`,msg:`${G.taskClass}: difference not confirmed \u2014 ${G.why}`});let U=z.classes.map((G)=>({taskClass:G.taskClass,arms:G.arms.map((H)=>Z60(H,G)),qualityLeader:G.qualityLeader,cheapest:G.cheapest,separationPending:G.separationPending,answer:G.answer,why:G.why})),K=$.has("nodes")?$.one("SELECT count(*) AS n FROM nodes WHERE kind = 'task' AND status = 'closed' AND deleted_at IS NULL"):void 0,W=$.one("SELECT count(DISTINCT task_id) AS n FROM swarm_attempt WHERE finished_at IS NOT NULL"),V={attempts:z.coverage.attempts,finished:z.coverage.finished,withCost:z.coverage.withCost,arms:z.coverage.arms,classes:z.coverage.classes,tasksClosed:K?.n??0,tasksAttributed:W?.n??0};return{available:!0,classes:U,coverage:V,outcomeVersion:z.outcomeVersion,minAttempts:z.minAttempts,credibleMass:z.credibleMass,degraded:J,took_ms:Math.round(performance.now()-Z)}}var MT=v(()=>{B4()});function z60($){if($===null||$===void 0)return null;let X=typeof $==="string"?$:String($);return X.length>160?`${X.slice(0,160)}\u2026`:X}function RT($,X={}){let Z=performance.now(),Y=Math.min(Math.max(X.limit??100,1),1000);if(!$.has("oplog"))return{rows:[],total:0,last_seq:0,took_ms:0};let z=$.has("nodes")?`
|
|
7986
7986
|
SELECT o.seq, o.ts_ms, o.actor, o.op, o.entity, o.entity_id,
|
|
7987
7987
|
o.field, o.value, o.scope, o.origin,
|
|
7988
7988
|
(SELECT n.title FROM nodes n WHERE n.id = o.entity_id) AS title
|
|
@@ -7993,22 +7993,22 @@ SELECT seq, ts_ms, actor, op, entity, entity_id, field, value, scope, origin,
|
|
|
7993
7993
|
NULL AS title
|
|
7994
7994
|
FROM oplog
|
|
7995
7995
|
ORDER BY seq DESC
|
|
7996
|
-
LIMIT ?1`,U=$.all(z,[Y]).map((W)=>({seq:Number(W.seq??0),ts_ms:Number(W.ts_ms??0),actor:String(W.actor??""),op:String(W.op??""),entity:String(W.entity??""),entity_id:String(W.entity_id??""),field:W.field===null||W.field===void 0?null:String(W.field),value:e80(W.value),scope:String(W.scope??""),origin:Number(W.origin??1),title:W.title===null||W.title===void 0?null:String(W.title)})),K=$.one("SELECT count(*) AS n FROM oplog")?.n??0;return{rows:U,total:K,last_seq:U[0]?.seq??0,took_ms:Math.round(performance.now()-Z)}}function $60($,X={}){let Z=["recall",$];if(X.limit!==void 0)Z.push("-n",String(X.limit));if(X.offset!==void 0)Z.push("--offset",String(X.offset));if(X.budget!==void 0)Z.push("--budget",String(X.budget));if(X.kind!==void 0&&X.kind.length>0)Z.push("--kind",X.kind);if(X.tag!==void 0&&X.tag.length>0)Z.push("--tag",X.tag);if(X.layer!==void 0&&X.layer.length>0)Z.push("--layer",X.layer);if(X.since!==void 0&&X.since.length>0)Z.push("--since",X.since);if(X.anchor!==void 0&&X.anchor.length>0)Z.push("--anchor",X.anchor);if(X.mode!==void 0&&X.mode.length>0)Z.push("--mode",X.mode);if(X.why===!0)Z.push("--why");if(X.reach!==void 0&&X.reach.length>0)Z.push("--reach",X.reach);if(X.repo!==void 0&&X.repo.length>0)Z.push("--repo",X.repo);if(X.session!==void 0&&X.session.length>0)Z.push("--session",X.session);if(X.embedTimeoutMs!==void 0)Z.push("--embed-timeout",String(X.embedTimeoutMs));if(X.sources!==void 0)Z.push("--sources",String(X.sources));return Z}async function Py($,X,Z={}){return q4($,$60(X,Z))}var Dy=v(()=>{Z3()});import{existsSync as X60}from"fs";function h$($,X=200){return new Response(JSON.stringify($),{status:X,headers:{"content-type":"application/json; charset=utf-8",...Ry}})}function P7($,X,Z){return h$({error:X,msg:Z},$)}function J3($,X,Z,Y){let z=$.searchParams.get(X);if(z===null)return Z;let J=Number(z);if(!Number.isFinite(J)||J<=0)return Z;return Math.min(Math.floor(J),Y)}function _T($){if(!X60($.dbPath))throw new u6("db.missing",`no database file: ${$.dbPath}`);let X=BT($.dir),Z=Ny($.dbPath,$.homeDir??process.env.HOME),Y=$.nodeLimit??GT,z=$.edgeLimit??HT,J=WT($.dbPath),U={requests:0,errors:0},K=$.readOnly!==!0,W=$.runCli??eB($.dir,$.dbPath),V=(B,T={})=>{if(!B.ok)return U.errors++,h$({ok:!1,error:{code:B.code,msg:B.msg,...B.hint!==void 0?{hint:B.hint}:{}},meta:{degraded:B.degraded},warn:B.warn,...B.extra??{}},B.status);return h$({ok:!0,data:B.data,meta:{degraded:B.degraded},warn:B.warn,...T})},G=async(B,T,q)=>{if(!K)return U.errors++,P7(405,"method.not_allowed","the viewer is running read-only");let j;try{let P=await B.json();if(typeof P!=="object"||P===null||Array.isArray(P))throw Error("the body must be a JSON object");j=P}catch(P){return U.errors++,P7(400,"usage.body",`request body not parsed: ${P instanceof Error?P.message:String(P)}`)}let O=T(j);if(!("argv"in O))return V(O);if(q!==void 0){let P=JT(J,q,zT());if(P!==void 0)return V(P);let _=YT(J,q,O,j.if_match);if(_!==void 0)return V(_)}let A=await q4(W,O.argv);if(!A.ok)return V(A);let R=O.warn??[],D={...A,warn:[...A.warn,...R],degraded:[...A.degraded,...R.map((P)=>P.code)]},F=q??(typeof A.data.id==="string"?A.data.id:void 0);return V(D,F!==void 0?{clk:X3(J,F)}:{})},H=async(B)=>{U.requests++;let T=new URL(B.url),q=/^\/api\/nodes\/([^/]+)(\/op|\/card)?$/.exec(T.pathname),j=/^\/api\/nodes\/([^/]+)\/release-preview$/.exec(T.pathname),O=/^\/api\/bootstrap\/([^/]+)(\/op)?$/.exec(T.pathname),A=/^\/api\/bootstrap\/blocks\/([^/]+)\/history$/.exec(T.pathname);if(B.method==="POST"){if(T.pathname==="/api/nodes")return G(B,$T);if(q!==null&&q[2]!=="/card"){let R=q,D=decodeURIComponent(R[1]);return R[2]===void 0?G(B,(F)=>XT(D,F),D):G(B,(F)=>ZT(D,F),D)}if(O!==null){let R=decodeURIComponent(O[1]);return O[2]===void 0?G(B,(D)=>ev(R,D)):G(B,(D)=>$y(R,D))}return U.errors++,P7(404,"notfound",`no route POST ${T.pathname}`)}if(B.method!=="GET"&&B.method!=="HEAD")return U.errors++,P7(405,"method.not_allowed",`method ${B.method} is not served`);try{if(j!==null){let D=decodeURIComponent(j[1]);return h$({released:iv(J,D)})}if(q!==null){let D=decodeURIComponent(q[1]);if(q[2]==="/card"){let F=Yy(J,D);if(F===void 0)return U.errors++,P7(404,"notfound.node",`no node ${q[1]}`);return h$(F)}if(q[2]===void 0){let F=UT(J,D);if(F===void 0)return U.errors++,P7(404,"notfound.node",`no node ${q[1]}`);return h$(F)}}if(A!==null){let D=decodeURIComponent(A[1]),F=tv(J,D,J3(T,"limit",20,200));return h$({rows:F})}if(T.pathname==="/api/bootstrap"){let D=T.searchParams.get("budget"),F=D!==null&&Number.isFinite(Number(D))?Number(D):void 0,P=await sv(W,F);return V(P)}if(T.pathname==="/api/bootstrap/blocks"){let D=await rv(W);if(!D.ok)return V(D);let F=Array.isArray(D.data)?D.data:[];return V({...D,data:{rows:F}})}if(T.pathname==="/api/search"){let D=T.searchParams.get("q")??"";if(D.trim().length===0)return P7(400,"usage.invalid","a query is required: /api/search?q=<text>");let F=(M)=>T.searchParams.get(M)??void 0,P=(M)=>{let E=T.searchParams.get(M);if(E===null)return;let b=Number(E);return Number.isFinite(b)?b:void 0},_=await Py(W,D,{limit:P("n"),offset:P("offset"),budget:P("budget"),kind:F("kind"),tag:F("tag"),layer:F("layer"),since:F("since"),anchor:F("anchor"),mode:F("mode"),why:T.searchParams.get("why")!==null,reach:F("reach"),repo:F("repo"),session:F("session"),embedTimeoutMs:P("embed-timeout"),sources:P("sources")});return V(_)}switch(T.pathname){case"/api/boot":{let D=J.has("nodes")&&J.has("edges")&&J.has("oplog"),F={slug:X.slug,db_path:$.dbPath,tier:Z,nodes:D?J.one("SELECT count(*) AS n FROM nodes WHERE deleted_at IS NULL")?.n??0:0,edges:D?J.one("SELECT count(*) AS n FROM edges WHERE deleted_at IS NULL")?.n??0:0,node_limit:Y,read_only:!K,write_ops:T4,write_fields:v9,schema_ready:D,version:My};return h$(F)}case"/api/graph":return h$(QT(J,{nodeLimit:J3(T,"limit",Y,Y),edgeLimit:z}));case"/api/ready":return h$(AT(J,{scope:X.scope,weights:X.weights,limit:J3(T,"n",50,500)}));case"/api/board":return h$(cv(J,{scope:X.scope}));case"/api/oplog":return h$(RT(J,{limit:J3(T,"n",100,1000)}));case"/api/kb":{let D=T.searchParams.get("layer"),F=D!==null&&/^[0-3]$/.test(D)?Number(D):void 0;return h$(OT(J,{kinds:T.searchParams.get("kind")??void 0,layer:F,reach:T.searchParams.get("reach")??void 0,repo:T.searchParams.get("repo")??void 0,q:T.searchParams.get("q")??void 0,limit:J3(T,"limit",f9,f9)}))}case"/api/health":return h$(TT(J,{slug:X.slug,dbPath:$.dbPath,readOnly:!K}));case"/api/routing":return h$(DT(J));case"/api/decisions":return h$(Ky(J));default:break}let R=sB(T.pathname);if(R!==void 0)return new Response(R.body,{headers:{"content-type":R.type,"cache-control":"no-store",...Ry}});return U.errors++,P7(404,"notfound",`no route ${T.pathname}`)}catch(R){U.errors++;let D=R instanceof Error?R.message:String(R);return P7(500,"internal",D)}},N=Bun.serve({port:$.port??7788,hostname:$.hostname??"127.0.0.1",development:!1,fetch:H}),Q=N.hostname??"127.0.0.1",L=N.port??($.port??7788);return{url:`http://${Q}:${L}/`,port:L,hostname:Q,dbPath:$.dbPath,workspace:X,tier:Z,assetBytes:rB(),writable:K,stats:U,stop(){N.stop(!0),J.close()}}}var My="0.0.0",Ry;var _y=v(()=>{tB();nv();Xy();zy();Wy();VT();NT();qT();CT();PT();MT();Z3();Dy();BK();Ry={"content-security-policy":"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; worker-src 'self'; frame-ancestors 'none'; base-uri 'none'","x-content-type-options":"nosniff","referrer-policy":"no-referrer"}});var Iy=v(()=>{_y();Z3();VT();NT();CT();PT();MT();qT();BK();tB()});var vy={};s(vy,{realVizDeps:()=>Ey,createVizCommand:()=>V60,VIZ_SCREENS:()=>TK});import{existsSync as Z60}from"fs";import{join as Y60,resolve as z60}from"path";function g9($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,...Y!==void 0?{hint:Y}:{}}}function J60($,X){let Z=$.flags[X];return typeof Z==="string"?Z:void 0}function ky($,X){let Z=$.flags[X];if(typeof Z==="number")return Z;if(typeof Z==="string"){let Y=Number(Z);return Number.isFinite(Y)?Y:void 0}return}function U60(){return new Promise(($)=>{let X=(z)=>()=>{process.off("SIGINT",Z),process.off("SIGTERM",Y),$(z)},Z=X("SIGINT"),Y=X("SIGTERM");process.once("SIGINT",Z),process.once("SIGTERM",Y)})}function K60($){let X=process.platform==="darwin"?["open",$]:process.platform==="win32"?["cmd","/c","start","",$]:["xdg-open",$];try{Bun.spawn(X,{stdout:"ignore",stderr:"ignore",stdin:"ignore"})}catch{}}function V60($=Ey){let X=W60[TK.length]??String(TK.length);return{name:"viz",summary:"local web interface: graph, queue, board, cards, search, health \u2014 edits go through the CLI",help:`Starts a local server (127.0.0.1 unless --host) with the web interface. ${X[0].toUpperCase()}${X.slice(1)} screens \u2014 ${TK.map(([,Z])=>Z).join(", ")}; a task opens as a card with its thread. Reads go through a connection opened READ-ONLY, so the CLI keeps writing while the page is open. `+`Edits from the page \u2014 create a task or a note, change its fields, ${T4.join(", ")}, ${$3.join(" or ")} a compaction candidate (myc review), set or remove a bootstrap block \u2014 `+"are not written by the server itself: each runs through the same command engine as the terminal (oplog, ACL, field clocks), and an edit made against a stale copy is refused, not merged. The UI is embedded in the binary: zero external requests.",flags:[{name:"port",short:"p",value:"number",description:"port (default 7788)"},{name:"host",value:"string",description:"bind address (default 127.0.0.1)"},{name:"open",description:"open the page in the default browser"},{name:"limit",value:"number",description:"node cap for local layout (default 25000)"}],handler:async(Z)=>{let Y=z60(Z.globals.directory??process.cwd()),z=Z.globals.db??Y60(Y,".myc","myc.db");if(!Z60(z))return g9("ws.not_initialized",`workspace not initialized: no ${z}`,7,"myc init");let J=ky(Z,"port")??7788;if(!Number.isInteger(J)||J<0||J>65535)return g9("usage.invalid",`invalid port '${J}'`,2);let U=ky(Z,"limit")??25000;if(!Number.isInteger(U)||U<1)return g9("usage.invalid",`invalid --limit '${U}'`,2);if(U>25000)Z.warn("viz.limit_capped",`--limit ${U} is above the local layout cap of 25000 (S18) \u2014 using 25000`);let K=J60(Z,"host")??"127.0.0.1",W=Date.now(),V;try{V=$.start({dbPath:z,dir:Y,port:J,hostname:K,nodeLimit:Math.min(U,25000)})}catch(Q){if(Q instanceof u6)return g9("db.readonly_open",Q.message,1,"myc doctor");let L=Q instanceof Error?Q.message:String(Q);if(/EADDRINUSE|address already in use/i.test(L))return g9("conflict.port",`port ${J} is already in use: ${L}`,4,"myc viz --port 7789");return g9("internal.unexpected",L,1)}let G=await fetch(`${V.url}api/boot`).then((Q)=>Q.json());if(!G.schema_ready)Z.warn("schema.missing","the database has no myc tables \u2014 screens will show 'empty'; check myc init / myc doctor --schema");if(!Z.globals.json&&!Z.globals.ndjson&&!Z.globals.quiet){let Q=(V.assetBytes/1024).toFixed(0);$.write(`myc viz \xB7 ws=${V.workspace.slug} \xB7 ${G.nodes} nodes / ${G.edges} edges
|
|
7996
|
+
LIMIT ?1`,U=$.all(z,[Y]).map((W)=>({seq:Number(W.seq??0),ts_ms:Number(W.ts_ms??0),actor:String(W.actor??""),op:String(W.op??""),entity:String(W.entity??""),entity_id:String(W.entity_id??""),field:W.field===null||W.field===void 0?null:String(W.field),value:z60(W.value),scope:String(W.scope??""),origin:Number(W.origin??1),title:W.title===null||W.title===void 0?null:String(W.title)})),K=$.one("SELECT count(*) AS n FROM oplog")?.n??0;return{rows:U,total:K,last_seq:U[0]?.seq??0,took_ms:Math.round(performance.now()-Z)}}function J60($,X={}){let Z=["recall",$];if(X.limit!==void 0)Z.push("-n",String(X.limit));if(X.offset!==void 0)Z.push("--offset",String(X.offset));if(X.budget!==void 0)Z.push("--budget",String(X.budget));if(X.kind!==void 0&&X.kind.length>0)Z.push("--kind",X.kind);if(X.tag!==void 0&&X.tag.length>0)Z.push("--tag",X.tag);if(X.layer!==void 0&&X.layer.length>0)Z.push("--layer",X.layer);if(X.since!==void 0&&X.since.length>0)Z.push("--since",X.since);if(X.anchor!==void 0&&X.anchor.length>0)Z.push("--anchor",X.anchor);if(X.mode!==void 0&&X.mode.length>0)Z.push("--mode",X.mode);if(X.why===!0)Z.push("--why");if(X.reach!==void 0&&X.reach.length>0)Z.push("--reach",X.reach);if(X.repo!==void 0&&X.repo.length>0)Z.push("--repo",X.repo);if(X.session!==void 0&&X.session.length>0)Z.push("--session",X.session);if(X.embedTimeoutMs!==void 0)Z.push("--embed-timeout",String(X.embedTimeoutMs));if(X.sources!==void 0)Z.push("--sources",String(X.sources));return Z}async function Py($,X,Z={}){return q4($,J60(X,Z))}var Dy=v(()=>{Z3()});import{existsSync as U60}from"fs";function h$($,X=200){return new Response(JSON.stringify($),{status:X,headers:{"content-type":"application/json; charset=utf-8",...Ry}})}function P7($,X,Z){return h$({error:X,msg:Z},$)}function J3($,X,Z,Y){let z=$.searchParams.get(X);if(z===null)return Z;let J=Number(z);if(!Number.isFinite(J)||J<=0)return Z;return Math.min(Math.floor(J),Y)}function _T($){if(!U60($.dbPath))throw new u6("db.missing",`no database file: ${$.dbPath}`);let X=BT($.dir),Z=Ny($.dbPath,$.homeDir??process.env.HOME),Y=$.nodeLimit??GT,z=$.edgeLimit??HT,J=WT($.dbPath),U={requests:0,errors:0},K=$.readOnly!==!0,W=$.runCli??eB($.dir,$.dbPath),V=(B,T={})=>{if(!B.ok)return U.errors++,h$({ok:!1,error:{code:B.code,msg:B.msg,...B.hint!==void 0?{hint:B.hint}:{}},meta:{degraded:B.degraded},warn:B.warn,...B.extra??{}},B.status);return h$({ok:!0,data:B.data,meta:{degraded:B.degraded},warn:B.warn,...T})},G=async(B,T,q)=>{if(!K)return U.errors++,P7(405,"method.not_allowed","the viewer is running read-only");let j;try{let P=await B.json();if(typeof P!=="object"||P===null||Array.isArray(P))throw Error("the body must be a JSON object");j=P}catch(P){return U.errors++,P7(400,"usage.body",`request body not parsed: ${P instanceof Error?P.message:String(P)}`)}let O=T(j);if(!("argv"in O))return V(O);if(q!==void 0){let P=JT(J,q,zT());if(P!==void 0)return V(P);let _=YT(J,q,O,j.if_match);if(_!==void 0)return V(_)}let A=await q4(W,O.argv);if(!A.ok)return V(A);let R=O.warn??[],D={...A,warn:[...A.warn,...R],degraded:[...A.degraded,...R.map((P)=>P.code)]},F=q??(typeof A.data.id==="string"?A.data.id:void 0);return V(D,F!==void 0?{clk:X3(J,F)}:{})},H=async(B)=>{U.requests++;let T=new URL(B.url),q=/^\/api\/nodes\/([^/]+)(\/op|\/card)?$/.exec(T.pathname),j=/^\/api\/nodes\/([^/]+)\/release-preview$/.exec(T.pathname),O=/^\/api\/bootstrap\/([^/]+)(\/op)?$/.exec(T.pathname),A=/^\/api\/bootstrap\/blocks\/([^/]+)\/history$/.exec(T.pathname);if(B.method==="POST"){if(T.pathname==="/api/nodes")return G(B,$T);if(q!==null&&q[2]!=="/card"){let R=q,D=decodeURIComponent(R[1]);return R[2]===void 0?G(B,(F)=>XT(D,F),D):G(B,(F)=>ZT(D,F),D)}if(O!==null){let R=decodeURIComponent(O[1]);return O[2]===void 0?G(B,(D)=>ev(R,D)):G(B,(D)=>$y(R,D))}return U.errors++,P7(404,"notfound",`no route POST ${T.pathname}`)}if(B.method!=="GET"&&B.method!=="HEAD")return U.errors++,P7(405,"method.not_allowed",`method ${B.method} is not served`);try{if(j!==null){let D=decodeURIComponent(j[1]);return h$({released:iv(J,D)})}if(q!==null){let D=decodeURIComponent(q[1]);if(q[2]==="/card"){let F=Yy(J,D);if(F===void 0)return U.errors++,P7(404,"notfound.node",`no node ${q[1]}`);return h$(F)}if(q[2]===void 0){let F=UT(J,D);if(F===void 0)return U.errors++,P7(404,"notfound.node",`no node ${q[1]}`);return h$(F)}}if(A!==null){let D=decodeURIComponent(A[1]),F=tv(J,D,J3(T,"limit",20,200));return h$({rows:F})}if(T.pathname==="/api/bootstrap"){let D=T.searchParams.get("budget"),F=D!==null&&Number.isFinite(Number(D))?Number(D):void 0,P=await sv(W,F);return V(P)}if(T.pathname==="/api/bootstrap/blocks"){let D=await rv(W);if(!D.ok)return V(D);let F=Array.isArray(D.data)?D.data:[];return V({...D,data:{rows:F}})}if(T.pathname==="/api/search"){let D=T.searchParams.get("q")??"";if(D.trim().length===0)return P7(400,"usage.invalid","a query is required: /api/search?q=<text>");let F=(M)=>T.searchParams.get(M)??void 0,P=(M)=>{let E=T.searchParams.get(M);if(E===null)return;let b=Number(E);return Number.isFinite(b)?b:void 0},_=await Py(W,D,{limit:P("n"),offset:P("offset"),budget:P("budget"),kind:F("kind"),tag:F("tag"),layer:F("layer"),since:F("since"),anchor:F("anchor"),mode:F("mode"),why:T.searchParams.get("why")!==null,reach:F("reach"),repo:F("repo"),session:F("session"),embedTimeoutMs:P("embed-timeout"),sources:P("sources")});return V(_)}switch(T.pathname){case"/api/boot":{let D=J.has("nodes")&&J.has("edges")&&J.has("oplog"),F={slug:X.slug,db_path:$.dbPath,tier:Z,nodes:D?J.one("SELECT count(*) AS n FROM nodes WHERE deleted_at IS NULL")?.n??0:0,edges:D?J.one("SELECT count(*) AS n FROM edges WHERE deleted_at IS NULL")?.n??0:0,node_limit:Y,read_only:!K,write_ops:T4,write_fields:v9,schema_ready:D,version:My};return h$(F)}case"/api/graph":return h$(QT(J,{nodeLimit:J3(T,"limit",Y,Y),edgeLimit:z}));case"/api/ready":return h$(AT(J,{scope:X.scope,weights:X.weights,limit:J3(T,"n",50,500)}));case"/api/board":return h$(cv(J,{scope:X.scope}));case"/api/oplog":return h$(RT(J,{limit:J3(T,"n",100,1000)}));case"/api/kb":{let D=T.searchParams.get("layer"),F=D!==null&&/^[0-3]$/.test(D)?Number(D):void 0;return h$(OT(J,{kinds:T.searchParams.get("kind")??void 0,layer:F,reach:T.searchParams.get("reach")??void 0,repo:T.searchParams.get("repo")??void 0,q:T.searchParams.get("q")??void 0,limit:J3(T,"limit",f9,f9)}))}case"/api/health":return h$(TT(J,{slug:X.slug,dbPath:$.dbPath,readOnly:!K}));case"/api/routing":return h$(DT(J));case"/api/decisions":return h$(Ky(J));default:break}let R=sB(T.pathname);if(R!==void 0)return new Response(R.body,{headers:{"content-type":R.type,"cache-control":"no-store",...Ry}});return U.errors++,P7(404,"notfound",`no route ${T.pathname}`)}catch(R){U.errors++;let D=R instanceof Error?R.message:String(R);return P7(500,"internal",D)}},N=Bun.serve({port:$.port??7788,hostname:$.hostname??"127.0.0.1",development:!1,fetch:H}),Q=N.hostname??"127.0.0.1",L=N.port??($.port??7788);return{url:`http://${Q}:${L}/`,port:L,hostname:Q,dbPath:$.dbPath,workspace:X,tier:Z,assetBytes:rB(),writable:K,stats:U,stop(){N.stop(!0),J.close()}}}var My="0.0.0",Ry;var _y=v(()=>{tB();nv();Xy();zy();Wy();VT();NT();qT();CT();PT();MT();Z3();Dy();BK();Ry={"content-security-policy":"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; worker-src 'self'; frame-ancestors 'none'; base-uri 'none'","x-content-type-options":"nosniff","referrer-policy":"no-referrer"}});var Iy=v(()=>{_y();Z3();VT();NT();CT();PT();MT();qT();BK();tB()});var vy={};s(vy,{realVizDeps:()=>Ey,createVizCommand:()=>L60,VIZ_SCREENS:()=>TK});import{existsSync as K60}from"fs";import{join as W60,resolve as V60}from"path";function g9($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,...Y!==void 0?{hint:Y}:{}}}function G60($,X){let Z=$.flags[X];return typeof Z==="string"?Z:void 0}function ky($,X){let Z=$.flags[X];if(typeof Z==="number")return Z;if(typeof Z==="string"){let Y=Number(Z);return Number.isFinite(Y)?Y:void 0}return}function H60(){return new Promise(($)=>{let X=(z)=>()=>{process.off("SIGINT",Z),process.off("SIGTERM",Y),$(z)},Z=X("SIGINT"),Y=X("SIGTERM");process.once("SIGINT",Z),process.once("SIGTERM",Y)})}function Q60($){let X=process.platform==="darwin"?["open",$]:process.platform==="win32"?["cmd","/c","start","",$]:["xdg-open",$];try{Bun.spawn(X,{stdout:"ignore",stderr:"ignore",stdin:"ignore"})}catch{}}function L60($=Ey){let X=N60[TK.length]??String(TK.length);return{name:"viz",summary:"local web interface: graph, queue, board, cards, search, health \u2014 edits go through the CLI",help:`Starts a local server (127.0.0.1 unless --host) with the web interface. ${X[0].toUpperCase()}${X.slice(1)} screens \u2014 ${TK.map(([,Z])=>Z).join(", ")}; a task opens as a card with its thread. Reads go through a connection opened READ-ONLY, so the CLI keeps writing while the page is open. `+`Edits from the page \u2014 create a task or a note, change its fields, ${T4.join(", ")}, ${$3.join(" or ")} a compaction candidate (myc review), set or remove a bootstrap block \u2014 `+"are not written by the server itself: each runs through the same command engine as the terminal (oplog, ACL, field clocks), and an edit made against a stale copy is refused, not merged. The UI is embedded in the binary: zero external requests.",flags:[{name:"port",short:"p",value:"number",description:"port (default 7788)"},{name:"host",value:"string",description:"bind address (default 127.0.0.1)"},{name:"open",description:"open the page in the default browser"},{name:"limit",value:"number",description:"node cap for local layout (default 25000)"}],handler:async(Z)=>{let Y=V60(Z.globals.directory??process.cwd()),z=Z.globals.db??W60(Y,".myc","myc.db");if(!K60(z))return g9("ws.not_initialized",`workspace not initialized: no ${z}`,7,"myc init");let J=ky(Z,"port")??7788;if(!Number.isInteger(J)||J<0||J>65535)return g9("usage.invalid",`invalid port '${J}'`,2);let U=ky(Z,"limit")??25000;if(!Number.isInteger(U)||U<1)return g9("usage.invalid",`invalid --limit '${U}'`,2);if(U>25000)Z.warn("viz.limit_capped",`--limit ${U} is above the local layout cap of 25000 (S18) \u2014 using 25000`);let K=G60(Z,"host")??"127.0.0.1",W=Date.now(),V;try{V=$.start({dbPath:z,dir:Y,port:J,hostname:K,nodeLimit:Math.min(U,25000)})}catch(Q){if(Q instanceof u6)return g9("db.readonly_open",Q.message,1,"myc doctor");let L=Q instanceof Error?Q.message:String(Q);if(/EADDRINUSE|address already in use/i.test(L))return g9("conflict.port",`port ${J} is already in use: ${L}`,4,"myc viz --port 7789");return g9("internal.unexpected",L,1)}let G=await fetch(`${V.url}api/boot`).then((Q)=>Q.json());if(!G.schema_ready)Z.warn("schema.missing","the database has no myc tables \u2014 screens will show 'empty'; check myc init / myc doctor --schema");if(!Z.globals.json&&!Z.globals.ndjson&&!Z.globals.quiet){let Q=(V.assetBytes/1024).toFixed(0);$.write(`myc viz \xB7 ws=${V.workspace.slug} \xB7 ${G.nodes} nodes / ${G.edges} edges
|
|
7997
7997
|
db ${z} \xB7 read-only connection for reads (the CLI can still write)`+`${V.writable?"; edits go through the CLI's write path":"; edits are off"}
|
|
7998
7998
|
UI ${Q} KB embedded in the binary \xB7 zero external requests
|
|
7999
7999
|
`+`${V.url}${Z.flags.open===!0?" (opened in the browser)":""}
|
|
8000
8000
|
Ctrl-C to stop
|
|
8001
8001
|
`)}if(Z.flags.open===!0)$.open(V.url);let H=await $.wait();V.stop();let N={url:V.url,port:V.port,db:z,slug:V.workspace.slug,nodes:G.nodes,edges:G.edges,requests:V.stats.requests,errors:V.stats.errors,uptime_ms:Date.now()-W,signal:H,read_only:!V.writable};return{ok:!0,data:N,meta:{requests:N.requests,uptime_ms:N.uptime_ms}}},renderHuman:(Z)=>{let Y=Z;return`viz stopped (${Y.signal}) \xB7 ${Y.requests} ${Y.requests===1?"request":"requests"}, ${Y.errors} ${Y.errors===1?"error":"errors"} \xB7 ${Math.round(Y.uptime_ms/1000)}s
|
|
8002
|
-
`}}}var Ey,TK,
|
|
8002
|
+
`}}}var Ey,TK,N60;var yy=v(()=>{Iy();V0();Ey={start:($)=>_T({dbPath:$.dbPath,dir:$.dir,port:$.port,hostname:$.hostname,nodeLimit:$.nodeLimit}),wait:H60,open:Q60,write:($)=>{process.stdout.write($)}},TK=[["graph","graph (Canvas2D, layout in a Web Worker)"],["ready","ready queue with the S21 score terms"],["board","board"],["kb","knowledge base"],["timeline","oplog timeline"],["search","search"],["routing","model routing"],["decisions","decisions"],["bootstrap","bootstrap blocks"],["health","health and degradations"]],N60=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"]});var gy={};s(gy,{resolveGraphDir:()=>jK,resolveCacheDir:()=>IT,createExportCommand:()=>T60,GRAPH_DIR:()=>fy,GIT_SETUP_HINT:()=>OK,CACHE_DIR:()=>Sy});import{resolve as qK,join as FK}from"path";function jK($,X="out"){let Z=f($,X),Y=qK($.globals.directory??process.cwd());return Z!==void 0?qK(Y,Z):FK(Y,fy)}function IT($,X="cache"){let Z=f($,X),Y=qK($.globals.directory??process.cwd());return Z!==void 0?qK(Y,Z):FK(Y,Sy)}function B60($){let X=$,Z=[`${X.dir}: ${X.ops} operation${X.ops===1?"":"s"} (${X.sites} site${X.sites===1?"":"s"}, ${kX} per file)`,` written ${X.files.written.length}, unchanged ${X.files.unchanged.length}`+(X.files.removed.length>0?`, projections removed ${X.files.removed.length}`:"")];if(X.backfilled.length>0)Z.push(` ${X.backfilled.length} close${X.backfilled.length===1?"":"s"} written by an older build went into the oplog now`);if(X.pendingImport>0)Z.push(` ! the files hold ${X.pendingImport} operation${X.pendingImport===1?"":"s"} `+"missing from the database \u2014 myc import");return Z.push(`done in ${X.took_ms} ms`),`${Z.join(`
|
|
8003
8003
|
`)}
|
|
8004
|
-
`}function
|
|
8004
|
+
`}function T60($=$0){return{name:"export",summary:"write the oplog to .myc/graph for git (nothing derived is committed)",flags:[{name:"out",value:"string",description:"target directory (default .myc/graph)"}],help:"S42: only the oplog goes to git and it is merged by union on op_id (no text merge). Node/edge projections are a local cache in .myc/projections, rebuilt by `myc import` and never committed. Export never deletes or truncates oplog files; projection files left in .myc/graph by the old format are removed. Register the one merge driver once per clone:\n "+OK,handler:async(X)=>{let Z=performance.now(),Y=await $.openStore(X);if(!Y.ok)return Y.failure;let z=Y.handle;try{let J;try{J=VJ(z.driver,jK(X),{store:z.store})}catch(K){if(K instanceof q6)return{ok:!1,code:"conflict.op_id",msg:K.message,exit:4,hint:"two live databases under one site_id \u2014 usually a copy of the workspace directory (cp -R/rsync), not a clone; see S65 in docs/design/ARCHITECTURE.md"};throw K}if(J.unexpressedCloses.length>0)X.warn("export.unexpressed_closes",`${J.unexpressedCloses.length} closed task(s) closed by an older build are not in the oplog yet \u2014 `+"they go out with the next export");if(J.pendingImport>0)X.warn("export.pending_import",`${J.pendingImport} ${J.pendingImport===1?"operation":"operations"} from ${J.dir} `+"not in the database yet \u2014 run myc import");return{ok:!0,data:{...J,took_ms:Math.round(performance.now()-Z)}}}finally{z.close()}},renderHuman:B60}}var fy,Sy,OK;var CK=v(()=>{n0();V0();j0();fy=FK(".myc","graph"),Sy=FK(".myc",o7);OK=`git config merge.${MX}.driver "myc merge-driver %O %A %B %L %P"`});var by={};s(by,{createImportCommand:()=>A60});import{existsSync as q60}from"fs";import{basename as F60,dirname as j60}from"path";function O60($){let X=$,Z=[],Y=X.dry_run?"dry-run: ":"";if(Z.push(`${Y}${X.dir}: files ${X.files}, lines ${X.read}, new ${X.fresh}`+(X.dry_run?"":`, applied ${X.applied}, stale ${X.stale}, duplicates ${X.duplicate}`)),X.initialized!==void 0)Z.push(` \xB7 ${X.initialized.db} created with slug=${X.initialized.slug} from .myc/workspace.toml (site_id ${X.initialized.site_id})`);if(X.cache!==void 0)Z.push(` cache ${X.cache.dir}: ${X.cache.nodes} ${X.cache.nodes===1?"node":"nodes"}, ${X.cache.edges} ${X.cache.edges===1?"edge":"edges"}; rewritten ${X.cache.files.written.length}, unchanged ${X.cache.files.unchanged.length}`+(X.cache.files.removed.length>0?`, empty removed ${X.cache.files.removed.length}`:""));if(X.deferred.length>0)Z.push(` ! not applied ${X.deferred.length}: node without kind in the log`);if(X.collided.length>0)Z.push(` ! clock collisions ${X.collided.length}`);return Z.push(`done in ${X.took_ms} ms`),`${Z.join(`
|
|
8005
8005
|
`)}
|
|
8006
|
-
`}function kT($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}async function
|
|
8006
|
+
`}function kT($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}async function C60($,X){if($.globals.db!==void 0||K0($,"dry-run"))return;let Z=j60(X);if(F60(Z)!==".myc")return;let Y=await yL(Z);if(Y===void 0)return;return{db:Y.dbPath,slug:Y.slug,site_id:Y.siteId}}function A60($=$0){return{name:"import",summary:"replay .myc/graph oplog into the db and rebuild the local projection cache",flags:[{name:"from",value:"string",description:"graph directory (default .myc/graph)"},{name:"cache",value:"string",description:"projection cache directory (default .myc/projections)"},{name:"dry-run",description:"count new operations, change nothing"},{name:"no-cache",description:"do not rebuild the node/edge projection cache"}],help:"Idempotent: only operations missing from the local oplog are applied, through the same CRDT path as sync (per-field LWW, add-wins edges, G-counters). The projection cache is a pure function of the merged log and is never committed (its directory ignores itself), so nothing needs to be committed after an import. In a fresh clone the local db is created here from the committed .myc/workspace.toml (its slug is taken as is, the file is never rewritten); without that config nothing is created and `myc init` stays the answer.",handler:async(X)=>{let Z=performance.now(),Y=jK(X,"from");if(!q60(Y))return kT("notfound.graph_dir",`graph directory not found: ${Y}`,3,"myc export creates it");let z=await C60(X,Y),J=await $.openStore(X);if(!J.ok)return J.failure;let U=J.handle;try{let K=K0(X,"dry-run"),W;try{W=HJ(U.store,Y,{dryRun:K,rebuildCache:!K0(X,"no-cache"),cacheDir:IT(X)})}catch(G){let H=G instanceof Error?G.message:String(G);if(/UNIQUE constraint failed/i.test(H))return kT("conflict.unique",`the database refused an operation: ${H}`,4,"myc doctor; duplicates of content and of attrs.external_ref are resolved on import, "+"another unique index is not \u2014 report it");return kT("precond.graph_format",`oplog file does not parse: ${H}`,5)}if(W.duplicates.length>0){let G=W.duplicates.length,H=W.duplicates.filter((L)=>L.by==="content").length,N=G-H,Q=[H>0?`${H} by content`:"",N>0?`${N} by attrs.external_ref`:""].filter((L)=>L!=="").join(", ");X.warn("import.duplicates",`${G} identity duplicate${G===1?"":"s"} resolved (${Q}): ${W.duplicates.slice(0,3).map((L)=>`${L.id} of ${L.of}`).join(", ")}${G>3?"\u2026":""}`)}if(W.backfilled.length>0)X.warn("import.backfilled",`${W.backfilled.length} close${W.backfilled.length===1?"":"s"} written by an older build `+"went into the oplog now \u2014 run myc export");if(W.deferred.length>0)X.warn("import.deferred",`${W.deferred.length} ${W.deferred.length===1?"operation":"operations"} not applied: node without kind in the log (${W.deferred.slice(0,3).join(", ")}\u2026)`);if(W.collided.length>0)X.warn("import.clock_collision",`${W.collided.length} ${W.collided.length===1?"operation":"operations"} with an unresolvable clock tie (${W.collided.slice(0,3).join(", ")}\u2026)`);return{ok:!0,data:{...W,dry_run:K,...z!==void 0?{initialized:z}:{},took_ms:Math.round(performance.now()-Z)}}}finally{U.close()}},renderHuman:O60}}var wy=v(()=>{n0();V0();fL();j0();CK()});var hy={};s(hy,{renderSyncHuman:()=>xy,createSyncCommand:()=>P60,SYNC_MAX_ROUNDS:()=>PK});function AK($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,...Y===void 0?{}:{hint:Y}}}function xy($){let X=$,Y=[`${X.dry?`would push ${X.pushed}, would pull ${X.pulled}`:`push ${X.pushed} op \xB7 pull ${X.pulled} op`} \xB7 ${X.rounds} round${X.rounds===1?"":"s"} \xB7 ${X.took_ms} ms`];if(!X.dry&&X.pulled>0){let z=[`applied ${X.applied}`,`duplicate ${X.duplicate}`,`stale ${X.stale}`];if(X.deferred>0)z.push(`deferred ${X.deferred}`);Y.push(` ${z.join(", ")}`)}if(X.incomplete)Y.push(` ! stopped at ${PK} rounds \u2014 more is left, run sync again`);return`${Y.join(`
|
|
8007
8007
|
`)}
|
|
8008
|
-
`}function
|
|
8009
|
-
`)){if(B+=1,T.trim().length===0)continue;let q;try{q=JSON.parse(T)}catch{throw Error(`not JSON: ${N instanceof Error?N.message:String(N)}; and not JSONL either: line ${B} does not parse`)}if(X8(q)&&q._type==="memory"){if(typeof q.key==="string"&&typeof q.value==="string")L[q.key]=q.value;continue}Q.push(q)}if(Q.length===0)throw Error("snapshot is empty: no tasks");X={issues:Q,memories:L}}if(X8(X)&&!("issues"in X)&&typeof X._type==="string"){if(X._type==="memory")throw Error("snapshot is empty: no tasks");X={issues:[X]}}if(Array.isArray(X))X={issues:X};if(!X8(X))throw Error("snapshot root is not an object");if(!Array.isArray(X.issues))throw Error("no issues array");let Z=[],Y=new Set,z=new Map,J=[],U=new Map,K=[],W=new Map,V=[];for(let[N,Q]of X.issues.entries()){let L=`issues[${N}]`,B=Array.isArray(Q)&&Q.length===1&&X8(Q[0])?Q[0]:Q;if(!X8(B))throw Error(`${L}: not an object`);let{id:T,title:q,status:j,issue_type:O,priority:A}=B;if(typeof T!=="string"||T.length===0)throw Error(`${L}: no id`);if(Y.has(T))throw Error(`${L}: duplicate id '${T}'`);if(Y.add(T),typeof q!=="string")throw Error(`${L} (${T}): no title`);if(typeof j!=="string"||j.trim().length===0)throw Error(`${L} (${T}): no status`);let R=j;if(!
|
|
8010
|
-
`).filter((H)=>H.trim().length>0).length;if(K===0)return;let W;try{W=MK(J)}catch(H){let N=H instanceof Error?H.message:String(H);if(/no tasks/.test(N))return;return{beadsDir:Z,path:z,lines:K,issues:void 0,statuses:"",parseError:N,written:U}}if(W.issues.length===0)return;let V=new Map;for(let H of W.issues){let N=H.source_status??H.status;V.set(N,(V.get(N)??0)+1)}let G=[...V].sort((H,N)=>N[1]-H[1]||H[0].localeCompare(N[0])).map(([H,N])=>`${H} ${N}`).join(", ");return{beadsDir:Z,path:z,lines:K,issues:W.issues.length,statuses:G,parseError:void 0,written:U}}function py($){if($.issues===void 0)return`${$.path} with ${$.lines} ${$.lines===1?"line":"lines"}, written ${$.written}, that does not parse as a snapshot (${$.parseError})`;return`${$.path} with ${$.issues} ${$.issues===1?"task":"tasks"} (${$.statuses}), written ${$.written}`}function
|
|
8011
|
-
`).entries()){if(z.trim().length===0)continue;let J;try{J=JSON.parse(z)}catch(U){throw Error(`bd export: line ${Y+1} is not JSON: ${U instanceof Error?U.message:String(U)}`)}if(!X8(J))throw Error(`bd export: line ${Y+1} is not an object`);if(J._type==="memory"){if(typeof J.key==="string"&&typeof J.value==="string")Z[J.key]=J.value;continue}X.push(J)}return MK(JSON.stringify({issues:X,memories:Z}))}function ey($){if($.closed_at===void 0)return null;let X=Date.parse($.closed_at);return Number.isNaN(X)?null:X}function b9($){return typeof $==="string"&&$.trim().length>0?$:null}function
|
|
8008
|
+
`}function P60($=$0){return{name:"sync",remote:!0,summary:"exchange operations with a team server (push what it lacks, pull what you lack)",flags:[{name:"push-only",description:"send ours, ask for nothing back"},{name:"pull-only",description:"ask for theirs, send nothing"},{name:"dry-run",description:"count both directions, change nothing"},{name:"max-ops",value:"number",description:`operations per round (default ${P8})`}],help:"The client always initiates: the server is another site, not the source of truth, and the "+"network is never in the hot path \u2014 prime, ready and show read the local database. "+"Needs --server (or MYC_SERVER) and MYC_TOKEN with the 'sync' scope: a replica is complete by construction, so taking one means seeing everything in the workspace. The workspace "+"itself is the local slug by default (.myc/workspace.toml) \u2014 the same file that builds node "+"ids \u2014 so the usual call is just MYC_SERVER=https://host myc sync; --ws/MYC_WS or an "+"address path override it for a foreign workspace. Merging is CRDT (per-field LWW, add-wins edges, G-counters) and idempotent by op_id, so an interrupted exchange is resumed by running it again.",handler:async(X)=>{let Z=performance.now(),Y=X.flags["push-only"]===!0,z=X.flags["pull-only"]===!0;if(Y&&z)return AK("usage.direction","--push-only and --pull-only exclude each other",2);let J=X.flags["dry-run"]===!0,U=t(X,"max-ops")??P8;if(U<1||U>P8)return AK("usage.max_ops",`--max-ops is between 1 and ${P8}, got ${U}`,2);let K=await $.openStore(X);if(!K.ok)return K.failure;let W=K.handle;try{let V=await $8(X,async(G)=>{if(W.scope!==G.ws)return AK("usage.ws_mismatch",`this workspace writes scope '${W.scope}', the server workspace is '${G.ws}' \u2014 `+"syncing them would move nodes into a workspace neither side lists",2,W.scope===""?"this workspace has no scope at all, so it has no server counterpart yet":`point --server at /ws/${W.scope} instead`);let H=W.store.syncWatermarks(W.scope),N={},Q=0,L=0,B=0,T=0,q=0,j=0,O=0,A=!0,R="",D=[];while(O<PK){O++;let _=(await G.sync({site_id:W.store.siteId,have:H,ops:D,...Y?{want:!1}:{},...J?{dry:!0}:{}})).data;Q+=D.length,R=_.site_id??R,N=_.watermarks??{};let M=_.ops??[];if(L+=M.length,A=_.more===!0,M.length>0&&!J){let b=W.store.applyOps(yV(M),0);B+=b.applied,T+=b.duplicate,q+=b.stale,j+=b.deferred.length,H=mz(M,W.store.syncWatermarks(W.scope))}else if(M.length>0)H=mz(M,H);if(D=(z?{ops:[],more:!1}:W.store.syncCollect(W.scope,N,U)).ops,D.length===0&&!A)break;if(J){Q+=D.length;break}}if(!J&&R!=="")W.store.syncRecordPeer(R,N,Date.now());return{ok:!0,data:{ws:G.ws,peer_site:R,pushed:Q,pulled:L,applied:B,duplicate:T,stale:q,deferred:j,rounds:O,dry:J,incomplete:O>=PK&&(A||D.length>0),took_ms:Math.round(performance.now()-Z)},meta:{remote:G.ws}}});if(V!==void 0)return V;return AK("precond.no_remote","sync needs a server: there is nothing to exchange with",5,"myc --server <url> sync, or set MYC_SERVER and MYC_TOKEN")}finally{W.close()}},renderHuman:xy}}var PK=100;var my=v(()=>{o();w5();V0();j0()});var Bf={};s(Bf,{parseBeadsSnapshot:()=>MK,noteToNodeInput:()=>Vf,memoryToNodeInput:()=>Hf,issueToNodeInput:()=>Wf,importBeadsSnapshot:()=>Lf,createImportBeadsCommand:()=>c60,commentToNodeInput:()=>Gf,commentRef:()=>gT,collectBeadsSnapshot:()=>ty,BeadsJsonlOnly:()=>W3});import{existsSync as D60,readFileSync as yT,statSync as M60}from"fs";import{join as uy}from"path";function DK($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function v60($,X){if(!X8($))throw Error(`${X}: comment is not an object`);let Z=$.text??$.body??$.comment;if(typeof Z!=="string"||Z.trim().length===0)return;let Y=$.id,z=$.author??$.created_by,J=$.created_at;return{id:typeof Y==="string"&&Y.length>0?Y:typeof Y==="number"?String(Y):X,text:Z,...typeof z==="string"&&z.length>0?{author:z}:{},...typeof J==="string"?{created_at:J}:{}}}function X8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function y60($,X){if(!X8($))throw Error(`${X}: dependency is not an object`);if(!("id"in $)&&!("depends_on_id"in $))throw Error(`${X}: dependency has no id`);let Z=$.id??$.depends_on_id;if(Z===null||Z==="")return;if(typeof Z!=="string")throw Error(`${X}: dependency id is not a string`);let Y=$.dependency_type??$.type;return{id:Z,...typeof Y==="string"?{dependency_type:Y}:{}}}function MK($){let X;try{X=JSON.parse($)}catch(N){let Q=[],L={},B=0;for(let T of $.split(`
|
|
8009
|
+
`)){if(B+=1,T.trim().length===0)continue;let q;try{q=JSON.parse(T)}catch{throw Error(`not JSON: ${N instanceof Error?N.message:String(N)}; and not JSONL either: line ${B} does not parse`)}if(X8(q)&&q._type==="memory"){if(typeof q.key==="string"&&typeof q.value==="string")L[q.key]=q.value;continue}Q.push(q)}if(Q.length===0)throw Error("snapshot is empty: no tasks");X={issues:Q,memories:L}}if(X8(X)&&!("issues"in X)&&typeof X._type==="string"){if(X._type==="memory")throw Error("snapshot is empty: no tasks");X={issues:[X]}}if(Array.isArray(X))X={issues:X};if(!X8(X))throw Error("snapshot root is not an object");if(!Array.isArray(X.issues))throw Error("no issues array");let Z=[],Y=new Set,z=new Map,J=[],U=new Map,K=[],W=new Map,V=[];for(let[N,Q]of X.issues.entries()){let L=`issues[${N}]`,B=Array.isArray(Q)&&Q.length===1&&X8(Q[0])?Q[0]:Q;if(!X8(B))throw Error(`${L}: not an object`);let{id:T,title:q,status:j,issue_type:O,priority:A}=B;if(typeof T!=="string"||T.length===0)throw Error(`${L}: no id`);if(Y.has(T))throw Error(`${L}: duplicate id '${T}'`);if(Y.add(T),typeof q!=="string")throw Error(`${L} (${T}): no title`);if(typeof j!=="string"||j.trim().length===0)throw Error(`${L} (${T}): no status`);let R=j;if(!_60.has(j)){let E=I60.get(j);if(R=E??sy,K.push(`${T}: ${j}\u2192${R}`),E===void 0)W.set(j,[...W.get(j)??[],T])}if(typeof O!=="string"||O.length===0)throw Error(`${L} (${T}): no issue_type`);if(!R60.has(O))z.set(O,(z.get(O)??0)+1);if(typeof A!=="number"||!Number.isInteger(A))throw Error(`${L} (${T}): priority is not an integer`);let D=A;if(A<0||A>3)D=A<0?0:3,J.push(`${T}: P${A}\u2192P${D}`);let F=B.dependencies;if(F!==void 0&&!Array.isArray(F))throw Error(`${L} (${T}): dependencies is not an array`);let P=[];for(let[E,b]of(F??[]).entries()){let k=y60(b,`${L}.dependencies[${E}]`);if(k!==void 0){P.push(k);continue}let y=X8(b)?b.dependency_type??b.type:void 0;V.push(`${T}: ${typeof y==="string"?y:"?"}`)}let _=B.comments;if(_!==void 0&&!Array.isArray(_))throw Error(`${L} (${T}): comments is not an array`);let M=_===void 0?void 0:_.map((E,b)=>v60(E,`${L}.comments[${b}]`)).filter((E)=>E!==void 0);for(let E of Object.keys(B)){if(k60.has(E)||E60.has(E))continue;U.set(E,(U.get(E)??0)+1)}Z.push({...B,status:R,source_status:R!==j?j:void 0,priority:D,...F!==void 0?{dependencies:P}:{},...M!==void 0?{comments:M}:{}})}let G=X.memories,H;if(G!==void 0){if(!X8(G))throw Error("memories is not an object");H={};for(let[N,Q]of Object.entries(G))if(typeof Q==="string")H[N]=Q}return{issues:Z,memories:H,...z.size>0?{unknownTypes:Object.fromEntries(z)}:{},...J.length>0?{clampedPriorities:J}:{},...U.size>0?{unknownFields:Object.fromEntries(U)}:{},...K.length>0?{mappedStatuses:K}:{},...W.size>0?{unknownStatuses:Object.fromEntries(W)}:{},...V.length>0?{danglingDeps:V}:{}}}function ry($,X){let Z;try{Z=Bun.spawnSync(["bd",...X],{cwd:$,stdout:"pipe",stderr:"pipe"})}catch(Y){throw Error(`bd failed to start (${Y instanceof Error?Y.message:String(Y)}); you can build the snapshot by hand and pass it as a file: myc import-beads snapshot.json`)}if(Z.exitCode!==0){let Y=Z.stderr?.toString().trim()??"";throw Error(`bd ${X[0]} exited with code ${Z.exitCode}${Y.length>0?`: ${Y}`:""}; you can build the snapshot by hand and pass it as a file: myc import-beads snapshot.json`)}return Z.stdout?.toString()??""}function ty($){let X;try{X=ry($,["export","--include-memories"])}catch(Y){let z=ly($);if(z===void 0)throw Y;throw new W3("precond.bd",`${Y instanceof Error?Y.message:String(Y)}. There is ${py(z)}: ${cy}`,z.path)}let Z=f60(X);if(Z.issues.length===0){let Y=ly($);if(Y!==void 0)throw new W3("precond.bd_empty",`bd export returned no tasks from ${Y.beadsDir}, but there is ${py(Y)}: the database was never loaded from that file, or was emptied since; ${cy}`,Y.path)}return Z}function ly($){let X;try{X=JSON.parse(ry($,["where","--json"]))}catch{return}if(!X8(X)||typeof X.path!=="string"||X.path.length===0)return;let Z=X.path,Y="issues.jsonl";try{let H=JSON.parse(yT(uy(Z,"metadata.json"),"utf8"));if(X8(H)&&typeof H.jsonl_export==="string"&&H.jsonl_export.length>0)Y=H.jsonl_export}catch{}let z=uy(Z,Y),J,U;try{J=yT(z,"utf8"),U=M60(z).mtime.toISOString().slice(0,10)}catch{return}let K=J.split(`
|
|
8010
|
+
`).filter((H)=>H.trim().length>0).length;if(K===0)return;let W;try{W=MK(J)}catch(H){let N=H instanceof Error?H.message:String(H);if(/no tasks/.test(N))return;return{beadsDir:Z,path:z,lines:K,issues:void 0,statuses:"",parseError:N,written:U}}if(W.issues.length===0)return;let V=new Map;for(let H of W.issues){let N=H.source_status??H.status;V.set(N,(V.get(N)??0)+1)}let G=[...V].sort((H,N)=>N[1]-H[1]||H[0].localeCompare(N[0])).map(([H,N])=>`${H} ${N}`).join(", ");return{beadsDir:Z,path:z,lines:K,issues:W.issues.length,statuses:G,parseError:void 0,written:U}}function py($){if($.issues===void 0)return`${$.path} with ${$.lines} ${$.lines===1?"line":"lines"}, written ${$.written}, that does not parse as a snapshot (${$.parseError})`;return`${$.path} with ${$.issues} ${$.issues===1?"task":"tasks"} (${$.statuses}), written ${$.written}`}function f60($){let X=[],Z={};for(let[Y,z]of $.split(`
|
|
8011
|
+
`).entries()){if(z.trim().length===0)continue;let J;try{J=JSON.parse(z)}catch(U){throw Error(`bd export: line ${Y+1} is not JSON: ${U instanceof Error?U.message:String(U)}`)}if(!X8(J))throw Error(`bd export: line ${Y+1} is not an object`);if(J._type==="memory"){if(typeof J.key==="string"&&typeof J.value==="string")Z[J.key]=J.value;continue}X.push(J)}return MK(JSON.stringify({issues:X,memories:Z}))}function ey($){if($.closed_at===void 0)return null;let X=Date.parse($.closed_at);return Number.isNaN(X)?null:X}function b9($){return typeof $==="string"&&$.trim().length>0?$:null}function S60($,X){return`${$f($.field)}
|
|
8012
8012
|
## ${$.heading}
|
|
8013
8013
|
|
|
8014
8014
|
${X}
|
|
@@ -8020,52 +8020,52 @@ ${Xf(X.field)}`;for(let z=$.indexOf(Z);z!==-1;z=$.indexOf(Z,z+1)){if(z>0&&$[z-1]
|
|
|
8020
8020
|
|
|
8021
8021
|
`)return $.slice(0,X.from-2)+$.slice(X.to);if($.slice(X.to,X.to+2)===`
|
|
8022
8022
|
|
|
8023
|
-
`)return $.slice(0,X.from)+$.slice(X.to+2);return $.slice(0,X.from)+$.slice(X.to)}function
|
|
8023
|
+
`)return $.slice(0,X.from)+$.slice(X.to+2);return $.slice(0,X.from)+$.slice(X.to)}function g60($){let X={acceptance_criteria:null,design:null},Z=$??"";for(let Y of K3){let z=Zf(Z,Y);if(z===void 0)continue;let J=`## ${Y.heading}
|
|
8024
8024
|
|
|
8025
|
-
`;X[Y.field]=z.inner.startsWith(J)?z.inner.slice(J.length):z.inner,Z=Yf(Z,z)}return{rest:Z.trim().length>0?Z:null,sections:X}}function zf($,X,Z){let Y=$??"",z=Zf(Y,X);if(Z===null){if(z===void 0)return $;let U=Yf(Y,z);return U.trim().length>0?U:null}let J=
|
|
8025
|
+
`;X[Y.field]=z.inner.startsWith(J)?z.inner.slice(J.length):z.inner,Z=Yf(Z,z)}return{rest:Z.trim().length>0?Z:null,sections:X}}function zf($,X,Z){let Y=$??"",z=Zf(Y,X);if(Z===null){if(z===void 0)return $;let U=Yf(Y,z);return U.trim().length>0?U:null}let J=S60(X,Z);if(z!==void 0)return Y.slice(0,z.from)+J+Y.slice(z.to);return Y.trim().length===0?J:`${Y}
|
|
8026
8026
|
|
|
8027
8027
|
${J}`}function Jf($,X){return K3.reduce((Z,Y)=>zf(Z,Y,X[Y.field]),$)}function fT($){return{acceptance_criteria:b9($.acceptance_criteria),design:b9($.design)}}function ET($){return Math.max(Date.now(),$.store.clock.state.ts)}function Uf($){return{[C$.sourceCreated]:U3($.created_at),[C$.sourceUpdated]:U3($.updated_at),external_started_at:U3($.started_at),external_created_by:b9($.created_by)??void 0,external_owner:b9($.owner)??void 0,external_status:$.source_status,external_defer_until:U3($.defer_until)}}function Kf($){let X=$.labels?.filter((Z)=>Z.length>0)??[];if($.source_status!==void 0&&!X.includes($.source_status))return[...X,$.source_status];return[...X]}function Wf($,X,Z){let Y={type:$.issue_type,external_ref:$.id},z=Kf($);if(z.length>0)Y.tags=z;if($.status==="closed"&&$.close_reason!==void 0&&$.close_reason.length>0)Y.outcome={reason:$.close_reason};for(let[K,W]of Object.entries(Uf($)))if(W!==void 0)Y[K]=W;let J=Jf(b9($.description),fT($)),U=$.status==="closed"?ey($):null;return{kind:"task",scope:X,title:$.title,body:J,status:$.status,priority:$.priority,...$.assignee!==void 0&&$.assignee.length>0?{assignee:$.assignee}:{},...U!==null?{closed_at:U}:{},actor:Z,attrs:Y}}function ST($){let X=($.trim().split(`
|
|
8028
|
-
`,1)[0]??"").trim();return X.length<=iy?X:`${X.slice(0,iy-1).trimEnd()}\u2026`}function Vf($,X,Z,Y){return c7({text:X,title:ST(X).slice(0,80),scope:Z,actor:Y,external_ref:`${$.id}#notes`})}function U3($){if($===void 0)return;let X=Date.parse($);return Number.isFinite(X)?X:void 0}function Gf($,X,Z,Y){let z=U3(X.created_at);return c7({text:X.text,title:ST(X.text),scope:Z,actor:X.author!==void 0&&X.author.length>0?X.author:Y,external_ref:gT($,X),...z!==void 0?{external_created_at:z}:{}})}function gT($,X){return`${$.id}#comment:${X.id}`}function Hf($,X,Z,Y){return{kind:"note",scope:Z,layer:3,title:ST(X),body:X,actor:Y,attrs:{external_ref:`bd-remember:${$}`,memory_key:$}}}function u5($,X){return JSON.stringify($)===JSON.stringify(X)}function ny($){return Object.fromEntries(y60.map((X)=>[X,$[X]]))}function dy($){let X=Qf($),Z=fT($);return{title:$.title,body:b9($.description),status:$.status,priority:$.priority,assignee:$.assignee??"",tags:Kf($).sort(),outcome:$.status==="closed"&&$.close_reason!==void 0&&$.close_reason.length>0?{reason:$.close_reason}:null,closed_at:$.status==="closed"?ey($):null,parent:X.parent,blocks:X.blocks,acceptance_criteria:Z.acceptance_criteria,design:Z.design}}function f60($,X,Z){let{rest:Y,sections:z}=E60($.body);return{title:$.title,body:Y,status:$.status,priority:$.priority,assignee:$.assignee,tags:[...$.attrs.tags??[]].sort(),outcome:$.attrs.outcome??null,closed_at:$.closed_at,parent:X,blocks:[...Z].sort(),acceptance_criteria:z.acceptance_criteria,design:z.design}}function Qf($){let X=null,Z=[],Y=[],z=[];for(let J of $.dependencies??[]){let U=J.dependency_type===void 0?void 0:S60[J.dependency_type];if(J.dependency_type==="blocks")Z.push(J.id);else if(J.dependency_type==="parent-child")X=J.id;else if(U!==void 0)Y.push({ref:J.id,...U});else z.push({id:J.id,type:J.dependency_type})}return{parent:X,blocks:Z.sort(),extra:Y,unknown:z}}function vT($,X,Z,Y){if(u5($,X))return"sync";if(!Y)return"apply";if(u5($,Z))return"keep";if(u5(X,Z))return"apply";return"conflict"}function b8($){let X=typeof $==="string"?$:JSON.stringify($);return X.length<=oy?X:`${X.slice(0,oy-1)}\u2026`}function b60($){let X=new Map,Z=new Map,Y=new Map,z=new Set($.store.externalDuplicates().map((J)=>J.id));for(let J of["task","note"])for(let U of $.store.listNodes($.scope,J,g60)){let K=U.attrs.external_ref;if(typeof K==="string"){let V=X.get(K);if(V===void 0||z.has(V)&&!z.has(U.id))X.set(K,U.id),Y.set(K,A$(U.attrs));continue}let W=Nf(J,U.title,U.body);if(!Z.has(W))Z.set(W,U.id)}return{byRef:X,byContent:Z,repoByRef:Y}}function w60($,X,Z){let Y=new Map;if(Z===void 0)return Y;for(let[z,J]of $){let U=X.get(z);if(U===void 0||U.state==="unknown"||U.repo===Z)continue;Y.set(z,{id:J,repo:U.repo})}for(let z of Y.keys())$.delete(z);return Y}function ay($){return $.length===0?"the workspace root":`repo '${$}'`}function Nf($,X,Z){return`${$}\x00${V6($,X,Z)}`}function Lf($,X,Z){let Y=performance.now(),z=Z.dryRun,{byRef:J,byContent:U,repoByRef:K}=b60($),W=new Map;for(let[j,O]of J)W.set(O,j);let V=(j)=>W.get(j)??`myc:${j}`,G=w60(J,K,$.repo.repo),H=$.repo.repo??"",N=(j,O)=>{let A=G.get(j);if(A===void 0)return!1;return Q.skipped.push(`${j}: ${O} not imported \u2014 myc already has ${A.id} with this external_ref from ${ay(A.repo)}, and this import writes ${ay(H)}: two beads with the same id prefix, or a snapshot imported from another repo's directory; run the import from the directory of the beads it came from, or rename one prefix (bd rename-prefix)`),!0},Q={snapshot:Z.snapshotName,dry_run:z,issues_total:X.issues.length,tasks_created:0,tasks_existing:0,tasks_updated:0,fields_updated:0,sections_created:0,sections_updated:0,sections_removed:0,sections_existing:0,facts_updated:0,edges_created:0,edges_existing:0,edges_removed:0,notes_created:0,notes_existing:0,comments_created:0,comments_existing:0,memories_created:0,memories_existing:0,blockers_recounted:0,missing_refs:[],unknown_dep_types:[],statuses_mapped:[...X.mappedStatuses??[]],skipped:[],conflicts:[],kept_local:[],took_ms:0},L=(j)=>T.get(j)??J.get(j),B=(j,O,A)=>{let R=U.get(Nf(String(j.kind),j.title??"",j.body));if(R!==void 0){Q.skipped.push(`${O}: ${A} not imported \u2014 myc already has its own node ${R} with the same title and body (native nodes are identified by content); make the texts differ or delete the local duplicate, then re-run the import`);return}if(z)return`dry:${O}`;try{return $.store.createNode(j).id}catch(D){let F=D instanceof Error?D.message:String(D);if(!/UNIQUE constraint failed/i.test(F))throw D;Q.skipped.push(`${O}: ${A} not imported \u2014 node uniqueness violation (${F})`);return}},T=new Map,q=new Map;for(let j of X.issues){if(N(j.id,"task"))continue;let O=J.get(j.id);if(O===void 0){let w=Wf(j,$.scope,$.actor),h=B({...w,attrs:{...w.attrs,[m5]:ny(dy(j)),[C$.synced]:ET($)}},j.id,"task");if(h===void 0)continue;T.set(j.id,h),Q.tasks_created++;let u=fT(j);Q.sections_created+=K3.filter((d)=>u[d.field]!==null).length;continue}T.set(j.id,O),Q.tasks_existing++;let A=$.store.getNode(O);if(A===void 0)continue;let R=X8(A.attrs[m5])?A.attrs[m5]:void 0,D=R!==void 0,F=dy(j),P=f60(A,null,[]),_={},M={},E={},b={nodeId:O,baselineNew:_,columns:M,attrsPatch:E,applied:!1},k=(w,h)=>{let u=D&&R!==void 0&&w in R,d=vT(F[w],P[w],R?.[w],u);if(d==="apply")h(F[w]),b.applied=!0,Q.fields_updated++;else if(d==="keep")Q.kept_local.push(`${j.id}.${w}: local edit kept (in beads: ${b8(F[w])})`);else if(d==="conflict")Q.conflicts.push(`${j.id}.${w}: conflict \u2014 beads has '${b8(F[w])}', myc has '${b8(P[w])}', last import had '${b8(R?.[w])}'`);return _[w]=d==="conflict"?R?.[w]:F[w],d};k("title",(w)=>M.title=w);let y=new Set;k("body",()=>y.add("body"));for(let w of K3){let h=k(w.field,()=>y.add(w.field));if(h==="apply")if(P[w.field]===null)Q.sections_created++;else if(F[w.field]===null)Q.sections_removed++;else Q.sections_updated++;else if(h==="sync"&&F[w.field]!==null)Q.sections_existing++}if(y.size>0){let w=(h)=>y.has(h)?F[h]:P[h];M.body=y.has("body")?Jf(F.body,{acceptance_criteria:w("acceptance_criteria"),design:w("design")}):K3.reduce((h,u)=>y.has(u.field)?zf(h,u,F[u.field]):h,A.body)}k("status",(w)=>M.status=w),k("priority",(w)=>M.priority=w),k("assignee",(w)=>M.assignee=w),k("tags",(w)=>E.tags=w),k("outcome",(w)=>E.outcome=w),k("closed_at",(w)=>M.closed_at=w);let g=Uf(j),S=!1;for(let w of v60){let h=g[w],u=A.attrs[w];if(h===void 0){if(u===void 0||u===null)continue;E[w]=null}else if(u5(h,u))continue;else E[w]=h;S=!0}if(S)Q.facts_updated++;q.set(j.id,b)}for(let j of X.issues){let O=T.get(j.id),A=Qf(j);for(let k of A.unknown)Q.unknown_dep_types.push(`${j.id} \u2192 ${k.id}: type '${k.type??"?"}' is not imported`);for(let k of A.extra){let y=L(k.ref);if(O===void 0||y===void 0){Q.missing_refs.push(`${j.id} \u2192 ${k.ref}`);continue}let g=k.srcIsIssue?O:y,S=k.srcIsIssue?y:O;if($.store.getEdge(g,k.type,S)!==void 0){Q.edges_existing++;continue}if(!z)$.store.addEdge(g,k.type,S);Q.edges_created++}let R=q.get(j.id);if(R===void 0){for(let k of[A.parent,...A.blocks]){if(k===null)continue;let y=L(k);if(O===void 0||y===void 0){Q.missing_refs.push(`${j.id} \u2192 ${k}`);continue}let g=k===A.parent,S=g?O:y,w=g?y:O,h=g?"parent":"blocks";if($.store.getEdge(S,h,w)!==void 0){Q.edges_existing++;continue}if(!z)$.store.addEdge(S,h,w);Q.edges_created++}continue}let D=O===void 0?void 0:$.store.edgesFrom(O,"parent").find((k)=>k.deleted_at===null),F=D===void 0?null:V(D.dst),P=O===void 0?[]:$.store.edgesTo(O,"blocks").filter((k)=>k.deleted_at===null).map((k)=>V(k.src)).sort(),_=R.baselineNew,M=$.store.getNode(R.nodeId),E=M!==void 0&&X8(M.attrs[m5])?M.attrs[m5]:void 0,b=E!==void 0;{let k=vT(A.parent,F,E?.parent,b);if(k==="apply"){if(A.parent===null&&D!==void 0){if(!z)$.store.removeEdge(R.nodeId,"parent",D.dst);Q.edges_removed++,R.applied=!0}else if(A.parent!==null){let y=L(A.parent);if(y===void 0)Q.missing_refs.push(`${j.id} \u2192 ${A.parent}`);else{if(!z)$.store.addEdge(R.nodeId,"parent",y);Q.edges_created++,R.applied=!0}}}else{if(A.parent!==null&&A.parent===F)Q.edges_existing++;if(k==="keep"&&!u5(A.parent,F))Q.kept_local.push(`${j.id}.parent: local edit kept (in beads: ${b8(A.parent)})`);else if(k==="conflict")Q.conflicts.push(`${j.id}.parent: conflict \u2014 beads has '${b8(A.parent)}', myc has '${b8(F)}', last import had '${b8(E?.parent)}'`)}_.parent=k==="conflict"?E?.parent:A.parent}{let k=A.blocks,y=vT(k,P,E?.blocks,b);if(y==="apply"){Q.edges_existing+=k.filter((g)=>P.includes(g)).length;for(let g of k.filter((S)=>!P.includes(S))){let S=L(g);if(S===void 0){Q.missing_refs.push(`${j.id} \u2192 ${g}`);continue}if(!z)$.store.addEdge(S,"blocks",R.nodeId);Q.edges_created++,R.applied=!0}for(let g of P.filter((S)=>!k.includes(S))){let S=L(g);if(S===void 0)continue;if(!z)$.store.removeEdge(S,"blocks",R.nodeId);Q.edges_removed++,R.applied=!0}}else if(Q.edges_existing+=k.filter((g)=>P.includes(g)).length,y==="keep"&&!u5(k,P))Q.kept_local.push(`${j.id}.blocks: local edit kept (in beads: ${b8(k)})`);else if(y==="conflict")Q.conflicts.push(`${j.id}.blocks: conflict \u2014 beads has '${b8(k)}', myc has '${b8(P)}', last import had '${b8(E?.blocks)}'`);_.blocks=y==="conflict"?E?.blocks:k}}for(let j of q.values()){if(j.applied)Q.tasks_updated++;let O=$.store.getNode(j.nodeId);if(O===void 0)continue;let A=Object.keys(j.columns).length>0||Object.keys(j.attrsPatch).length>0,R=ny(j.baselineNew),D=!u5(O.attrs[m5]??void 0,R);if(!A&&!D)continue;if(!z)$.store.updateNode(j.nodeId,{...j.columns,attrs:{...j.attrsPatch,[m5]:R,[C$.synced]:ET($)}})}for(let j of X.issues){let O=j.notes;if(O===void 0||O.trim().length===0)continue;let A=`${j.id}#notes`;if(N(A,"note"))continue;if(J.has(A)){Q.notes_existing++;continue}let R=T.get(j.id);if(R===void 0){Q.skipped.push(`${A}: note not imported \u2014 task ${j.id} itself was not imported`);continue}let D=B(Vf(j,O,$.scope,$.actor),A,"note");if(D===void 0)continue;if(!z)$.store.addEdge(D,"replies_to",R);Q.notes_created++}for(let j of X.issues)for(let O of j.comments??[]){let A=gT(j,O);if(N(A,"comment"))continue;if(J.has(A)){Q.comments_existing++;continue}let R=T.get(j.id);if(R===void 0){Q.skipped.push(`${A}: comment not imported \u2014 task ${j.id} itself was not imported`);continue}let D=Gf(j,O,$.scope,$.actor),F=B({...D,attrs:{...D.attrs,[C$.synced]:ET($)}},A,"comment");if(F===void 0)continue;if(!z)$.store.addEdge(F,"replies_to",R);Q.comments_created++}for(let[j,O]of Object.entries(X.memories??{})){let A=`bd-remember:${j}`;if(N(A,"memory"))continue;if(J.has(A)){Q.memories_existing++;continue}if(B(Hf(j,O,$.scope,$.actor),A,"memory")===void 0)continue;Q.memories_created++}if(!z&&($.store.openBlockersDrift().length>0||$.store.ancBlockersDrift().length>0))Q.blockers_recounted=$.store.recountOpenBlockers();return Q.took_ms=Math.round(performance.now()-Y),Q}function x60($){let X=$,Y=[`${X.dry_run?"dry-run, nothing written: would import":"imported"} from ${X.snapshot}`,`tasks ${X.issues_total}: new ${X.tasks_created}, existing ${X.tasks_existing}`+(X.tasks_updated>0?`, updated ${X.tasks_updated} (${X.fields_updated} fields)`:""),`sections acceptance criteria / design in the body: new ${X.sections_created}, existing ${X.sections_existing}`+(X.sections_updated>0?`, updated ${X.sections_updated}`:"")+(X.sections_removed>0?`, removed ${X.sections_removed}`:""),...X.facts_updated>0?[`source dates and author written on ${X.facts_updated} existing ${X.facts_updated===1?"task":"tasks"}`]:[],...X.statuses_mapped.length>0?[`status no myc name, kept in attrs.external_status and as a tag (${X.statuses_mapped.length}): ${X.statuses_mapped.slice(0,5).join(", ")}`+(X.statuses_mapped.length>5?"\u2026":"")]:[],`edges new ${X.edges_created}, existing ${X.edges_existing}`+(X.edges_removed>0?`, removed ${X.edges_removed}`:""),`notes new ${X.notes_created}, existing ${X.notes_existing}`,`comments new ${X.comments_created}, existing ${X.comments_existing}`,`memories new ${X.memories_created}, existing ${X.memories_existing}`];if(!X.dry_run&&X.blockers_recounted>0)Y.push(`open_blockers recounted on ${X.blockers_recounted} ${X.blockers_recounted===1?"node":"nodes"}`);if(X.kept_local.length>0)Y.push(`local edits kept (${X.kept_local.length}): ${X.kept_local.slice(0,3).join(", ")}`+(X.kept_local.length>3?"\u2026":""));if(X.conflicts.length>0)Y.push(`! conflicts (${X.conflicts.length}), myc applied nothing: ${X.conflicts.slice(0,3).join(", ")}`+(X.conflicts.length>3?"\u2026":""));if(X.skipped.length>0)Y.push(`! not imported (${X.skipped.length}): ${X.skipped.slice(0,3).join("; ")}`+(X.skipped.length>3?"\u2026":""));if(X.unknown_dep_types.length>0)Y.push(`! dependency types with no myc edge (${X.unknown_dep_types.length}): ${X.unknown_dep_types.slice(0,3).join(", ")}`+(X.unknown_dep_types.length>3?"\u2026":""));if(X.missing_refs.length>0)Y.push(`! references with no target (${X.missing_refs.length}): ${X.missing_refs.slice(0,3).join(", ")}\u2026`);return Y.push(`done in ${X.took_ms} ms`),`${Y.join(`
|
|
8028
|
+
`,1)[0]??"").trim();return X.length<=iy?X:`${X.slice(0,iy-1).trimEnd()}\u2026`}function Vf($,X,Z,Y){return c7({text:X,title:ST(X).slice(0,80),scope:Z,actor:Y,external_ref:`${$.id}#notes`})}function U3($){if($===void 0)return;let X=Date.parse($);return Number.isFinite(X)?X:void 0}function Gf($,X,Z,Y){let z=U3(X.created_at);return c7({text:X.text,title:ST(X.text),scope:Z,actor:X.author!==void 0&&X.author.length>0?X.author:Y,external_ref:gT($,X),...z!==void 0?{external_created_at:z}:{}})}function gT($,X){return`${$.id}#comment:${X.id}`}function Hf($,X,Z,Y){return{kind:"note",scope:Z,layer:3,title:ST(X),body:X,actor:Y,attrs:{external_ref:`bd-remember:${$}`,memory_key:$}}}function u5($,X){return JSON.stringify($)===JSON.stringify(X)}function ny($){return Object.fromEntries(w60.map((X)=>[X,$[X]]))}function dy($){let X=Qf($),Z=fT($);return{title:$.title,body:b9($.description),status:$.status,priority:$.priority,assignee:$.assignee??"",tags:Kf($).sort(),outcome:$.status==="closed"&&$.close_reason!==void 0&&$.close_reason.length>0?{reason:$.close_reason}:null,closed_at:$.status==="closed"?ey($):null,parent:X.parent,blocks:X.blocks,acceptance_criteria:Z.acceptance_criteria,design:Z.design}}function x60($,X,Z){let{rest:Y,sections:z}=g60($.body);return{title:$.title,body:Y,status:$.status,priority:$.priority,assignee:$.assignee,tags:[...$.attrs.tags??[]].sort(),outcome:$.attrs.outcome??null,closed_at:$.closed_at,parent:X,blocks:[...Z].sort(),acceptance_criteria:z.acceptance_criteria,design:z.design}}function Qf($){let X=null,Z=[],Y=[],z=[];for(let J of $.dependencies??[]){let U=J.dependency_type===void 0?void 0:h60[J.dependency_type];if(J.dependency_type==="blocks")Z.push(J.id);else if(J.dependency_type==="parent-child")X=J.id;else if(U!==void 0)Y.push({ref:J.id,...U});else z.push({id:J.id,type:J.dependency_type})}return{parent:X,blocks:Z.sort(),extra:Y,unknown:z}}function vT($,X,Z,Y){if(u5($,X))return"sync";if(!Y)return"apply";if(u5($,Z))return"keep";if(u5(X,Z))return"apply";return"conflict"}function b8($){let X=typeof $==="string"?$:JSON.stringify($);return X.length<=oy?X:`${X.slice(0,oy-1)}\u2026`}function u60($){let X=new Map,Z=new Map,Y=new Map,z=new Set($.store.externalDuplicates().map((J)=>J.id));for(let J of["task","note"])for(let U of $.store.listNodes($.scope,J,m60)){let K=U.attrs.external_ref;if(typeof K==="string"){let V=X.get(K);if(V===void 0||z.has(V)&&!z.has(U.id))X.set(K,U.id),Y.set(K,A$(U.attrs));continue}let W=Nf(J,U.title,U.body);if(!Z.has(W))Z.set(W,U.id)}return{byRef:X,byContent:Z,repoByRef:Y}}function l60($,X,Z){let Y=new Map;if(Z===void 0)return Y;for(let[z,J]of $){let U=X.get(z);if(U===void 0||U.state==="unknown"||U.repo===Z)continue;Y.set(z,{id:J,repo:U.repo})}for(let z of Y.keys())$.delete(z);return Y}function ay($){return $.length===0?"the workspace root":`repo '${$}'`}function Nf($,X,Z){return`${$}\x00${V6($,X,Z)}`}function Lf($,X,Z){let Y=performance.now(),z=Z.dryRun,{byRef:J,byContent:U,repoByRef:K}=u60($),W=new Map;for(let[j,O]of J)W.set(O,j);let V=(j)=>W.get(j)??`myc:${j}`,G=l60(J,K,$.repo.repo),H=$.repo.repo??"",N=(j,O)=>{let A=G.get(j);if(A===void 0)return!1;return Q.skipped.push(`${j}: ${O} not imported \u2014 myc already has ${A.id} with this external_ref from ${ay(A.repo)}, and this import writes ${ay(H)}: two beads with the same id prefix, or a snapshot imported from another repo's directory; run the import from the directory of the beads it came from, or rename one prefix (bd rename-prefix)`),!0},Q={snapshot:Z.snapshotName,dry_run:z,issues_total:X.issues.length,tasks_created:0,tasks_existing:0,tasks_updated:0,fields_updated:0,sections_created:0,sections_updated:0,sections_removed:0,sections_existing:0,facts_updated:0,edges_created:0,edges_existing:0,edges_removed:0,notes_created:0,notes_existing:0,comments_created:0,comments_existing:0,memories_created:0,memories_existing:0,blockers_recounted:0,missing_refs:[],unknown_dep_types:[],statuses_mapped:[...X.mappedStatuses??[]],skipped:[],conflicts:[],kept_local:[],took_ms:0},L=(j)=>T.get(j)??J.get(j),B=(j,O,A)=>{let R=U.get(Nf(String(j.kind),j.title??"",j.body));if(R!==void 0){Q.skipped.push(`${O}: ${A} not imported \u2014 myc already has its own node ${R} with the same title and body (native nodes are identified by content); make the texts differ or delete the local duplicate, then re-run the import`);return}if(z)return`dry:${O}`;try{return $.store.createNode(j).id}catch(D){let F=D instanceof Error?D.message:String(D);if(!/UNIQUE constraint failed/i.test(F))throw D;Q.skipped.push(`${O}: ${A} not imported \u2014 node uniqueness violation (${F})`);return}},T=new Map,q=new Map;for(let j of X.issues){if(N(j.id,"task"))continue;let O=J.get(j.id);if(O===void 0){let w=Wf(j,$.scope,$.actor),h=B({...w,attrs:{...w.attrs,[m5]:ny(dy(j)),[C$.synced]:ET($)}},j.id,"task");if(h===void 0)continue;T.set(j.id,h),Q.tasks_created++;let u=fT(j);Q.sections_created+=K3.filter((d)=>u[d.field]!==null).length;continue}T.set(j.id,O),Q.tasks_existing++;let A=$.store.getNode(O);if(A===void 0)continue;let R=X8(A.attrs[m5])?A.attrs[m5]:void 0,D=R!==void 0,F=dy(j),P=x60(A,null,[]),_={},M={},E={},b={nodeId:O,baselineNew:_,columns:M,attrsPatch:E,applied:!1},k=(w,h)=>{let u=D&&R!==void 0&&w in R,d=vT(F[w],P[w],R?.[w],u);if(d==="apply")h(F[w]),b.applied=!0,Q.fields_updated++;else if(d==="keep")Q.kept_local.push(`${j.id}.${w}: local edit kept (in beads: ${b8(F[w])})`);else if(d==="conflict")Q.conflicts.push(`${j.id}.${w}: conflict \u2014 beads has '${b8(F[w])}', myc has '${b8(P[w])}', last import had '${b8(R?.[w])}'`);return _[w]=d==="conflict"?R?.[w]:F[w],d};k("title",(w)=>M.title=w);let y=new Set;k("body",()=>y.add("body"));for(let w of K3){let h=k(w.field,()=>y.add(w.field));if(h==="apply")if(P[w.field]===null)Q.sections_created++;else if(F[w.field]===null)Q.sections_removed++;else Q.sections_updated++;else if(h==="sync"&&F[w.field]!==null)Q.sections_existing++}if(y.size>0){let w=(h)=>y.has(h)?F[h]:P[h];M.body=y.has("body")?Jf(F.body,{acceptance_criteria:w("acceptance_criteria"),design:w("design")}):K3.reduce((h,u)=>y.has(u.field)?zf(h,u,F[u.field]):h,A.body)}k("status",(w)=>M.status=w),k("priority",(w)=>M.priority=w),k("assignee",(w)=>M.assignee=w),k("tags",(w)=>E.tags=w),k("outcome",(w)=>E.outcome=w),k("closed_at",(w)=>M.closed_at=w);let g=Uf(j),S=!1;for(let w of b60){let h=g[w],u=A.attrs[w];if(h===void 0){if(u===void 0||u===null)continue;E[w]=null}else if(u5(h,u))continue;else E[w]=h;S=!0}if(S)Q.facts_updated++;q.set(j.id,b)}for(let j of X.issues){let O=T.get(j.id),A=Qf(j);for(let k of A.unknown)Q.unknown_dep_types.push(`${j.id} \u2192 ${k.id}: type '${k.type??"?"}' is not imported`);for(let k of A.extra){let y=L(k.ref);if(O===void 0||y===void 0){Q.missing_refs.push(`${j.id} \u2192 ${k.ref}`);continue}let g=k.srcIsIssue?O:y,S=k.srcIsIssue?y:O;if($.store.getEdge(g,k.type,S)!==void 0){Q.edges_existing++;continue}if(!z)$.store.addEdge(g,k.type,S);Q.edges_created++}let R=q.get(j.id);if(R===void 0){for(let k of[A.parent,...A.blocks]){if(k===null)continue;let y=L(k);if(O===void 0||y===void 0){Q.missing_refs.push(`${j.id} \u2192 ${k}`);continue}let g=k===A.parent,S=g?O:y,w=g?y:O,h=g?"parent":"blocks";if($.store.getEdge(S,h,w)!==void 0){Q.edges_existing++;continue}if(!z)$.store.addEdge(S,h,w);Q.edges_created++}continue}let D=O===void 0?void 0:$.store.edgesFrom(O,"parent").find((k)=>k.deleted_at===null),F=D===void 0?null:V(D.dst),P=O===void 0?[]:$.store.edgesTo(O,"blocks").filter((k)=>k.deleted_at===null).map((k)=>V(k.src)).sort(),_=R.baselineNew,M=$.store.getNode(R.nodeId),E=M!==void 0&&X8(M.attrs[m5])?M.attrs[m5]:void 0,b=E!==void 0;{let k=vT(A.parent,F,E?.parent,b);if(k==="apply"){if(A.parent===null&&D!==void 0){if(!z)$.store.removeEdge(R.nodeId,"parent",D.dst);Q.edges_removed++,R.applied=!0}else if(A.parent!==null){let y=L(A.parent);if(y===void 0)Q.missing_refs.push(`${j.id} \u2192 ${A.parent}`);else{if(!z)$.store.addEdge(R.nodeId,"parent",y);Q.edges_created++,R.applied=!0}}}else{if(A.parent!==null&&A.parent===F)Q.edges_existing++;if(k==="keep"&&!u5(A.parent,F))Q.kept_local.push(`${j.id}.parent: local edit kept (in beads: ${b8(A.parent)})`);else if(k==="conflict")Q.conflicts.push(`${j.id}.parent: conflict \u2014 beads has '${b8(A.parent)}', myc has '${b8(F)}', last import had '${b8(E?.parent)}'`)}_.parent=k==="conflict"?E?.parent:A.parent}{let k=A.blocks,y=vT(k,P,E?.blocks,b);if(y==="apply"){Q.edges_existing+=k.filter((g)=>P.includes(g)).length;for(let g of k.filter((S)=>!P.includes(S))){let S=L(g);if(S===void 0){Q.missing_refs.push(`${j.id} \u2192 ${g}`);continue}if(!z)$.store.addEdge(S,"blocks",R.nodeId);Q.edges_created++,R.applied=!0}for(let g of P.filter((S)=>!k.includes(S))){let S=L(g);if(S===void 0)continue;if(!z)$.store.removeEdge(S,"blocks",R.nodeId);Q.edges_removed++,R.applied=!0}}else if(Q.edges_existing+=k.filter((g)=>P.includes(g)).length,y==="keep"&&!u5(k,P))Q.kept_local.push(`${j.id}.blocks: local edit kept (in beads: ${b8(k)})`);else if(y==="conflict")Q.conflicts.push(`${j.id}.blocks: conflict \u2014 beads has '${b8(k)}', myc has '${b8(P)}', last import had '${b8(E?.blocks)}'`);_.blocks=y==="conflict"?E?.blocks:k}}for(let j of q.values()){if(j.applied)Q.tasks_updated++;let O=$.store.getNode(j.nodeId);if(O===void 0)continue;let A=Object.keys(j.columns).length>0||Object.keys(j.attrsPatch).length>0,R=ny(j.baselineNew),D=!u5(O.attrs[m5]??void 0,R);if(!A&&!D)continue;if(!z)$.store.updateNode(j.nodeId,{...j.columns,attrs:{...j.attrsPatch,[m5]:R,[C$.synced]:ET($)}})}for(let j of X.issues){let O=j.notes;if(O===void 0||O.trim().length===0)continue;let A=`${j.id}#notes`;if(N(A,"note"))continue;if(J.has(A)){Q.notes_existing++;continue}let R=T.get(j.id);if(R===void 0){Q.skipped.push(`${A}: note not imported \u2014 task ${j.id} itself was not imported`);continue}let D=B(Vf(j,O,$.scope,$.actor),A,"note");if(D===void 0)continue;if(!z)$.store.addEdge(D,"replies_to",R);Q.notes_created++}for(let j of X.issues)for(let O of j.comments??[]){let A=gT(j,O);if(N(A,"comment"))continue;if(J.has(A)){Q.comments_existing++;continue}let R=T.get(j.id);if(R===void 0){Q.skipped.push(`${A}: comment not imported \u2014 task ${j.id} itself was not imported`);continue}let D=Gf(j,O,$.scope,$.actor),F=B({...D,attrs:{...D.attrs,[C$.synced]:ET($)}},A,"comment");if(F===void 0)continue;if(!z)$.store.addEdge(F,"replies_to",R);Q.comments_created++}for(let[j,O]of Object.entries(X.memories??{})){let A=`bd-remember:${j}`;if(N(A,"memory"))continue;if(J.has(A)){Q.memories_existing++;continue}if(B(Hf(j,O,$.scope,$.actor),A,"memory")===void 0)continue;Q.memories_created++}if(!z&&($.store.openBlockersDrift().length>0||$.store.ancBlockersDrift().length>0))Q.blockers_recounted=$.store.recountOpenBlockers();return Q.took_ms=Math.round(performance.now()-Y),Q}function p60($){let X=$,Y=[`${X.dry_run?"dry-run, nothing written: would import":"imported"} from ${X.snapshot}`,`tasks ${X.issues_total}: new ${X.tasks_created}, existing ${X.tasks_existing}`+(X.tasks_updated>0?`, updated ${X.tasks_updated} (${X.fields_updated} fields)`:""),`sections acceptance criteria / design in the body: new ${X.sections_created}, existing ${X.sections_existing}`+(X.sections_updated>0?`, updated ${X.sections_updated}`:"")+(X.sections_removed>0?`, removed ${X.sections_removed}`:""),...X.facts_updated>0?[`source dates and author written on ${X.facts_updated} existing ${X.facts_updated===1?"task":"tasks"}`]:[],...X.statuses_mapped.length>0?[`status no myc name, kept in attrs.external_status and as a tag (${X.statuses_mapped.length}): ${X.statuses_mapped.slice(0,5).join(", ")}`+(X.statuses_mapped.length>5?"\u2026":"")]:[],`edges new ${X.edges_created}, existing ${X.edges_existing}`+(X.edges_removed>0?`, removed ${X.edges_removed}`:""),`notes new ${X.notes_created}, existing ${X.notes_existing}`,`comments new ${X.comments_created}, existing ${X.comments_existing}`,`memories new ${X.memories_created}, existing ${X.memories_existing}`];if(!X.dry_run&&X.blockers_recounted>0)Y.push(`open_blockers recounted on ${X.blockers_recounted} ${X.blockers_recounted===1?"node":"nodes"}`);if(X.kept_local.length>0)Y.push(`local edits kept (${X.kept_local.length}): ${X.kept_local.slice(0,3).join(", ")}`+(X.kept_local.length>3?"\u2026":""));if(X.conflicts.length>0)Y.push(`! conflicts (${X.conflicts.length}), myc applied nothing: ${X.conflicts.slice(0,3).join(", ")}`+(X.conflicts.length>3?"\u2026":""));if(X.skipped.length>0)Y.push(`! not imported (${X.skipped.length}): ${X.skipped.slice(0,3).join("; ")}`+(X.skipped.length>3?"\u2026":""));if(X.unknown_dep_types.length>0)Y.push(`! dependency types with no myc edge (${X.unknown_dep_types.length}): ${X.unknown_dep_types.slice(0,3).join(", ")}`+(X.unknown_dep_types.length>3?"\u2026":""));if(X.missing_refs.length>0)Y.push(`! references with no target (${X.missing_refs.length}): ${X.missing_refs.slice(0,3).join(", ")}\u2026`);return Y.push(`done in ${X.took_ms} ms`),`${Y.join(`
|
|
8029
8029
|
`)}
|
|
8030
|
-
`}function
|
|
8031
|
-
`+OK,handler:($)=>{let X=BJ($.args);if(typeof X==="string")return V3("usage.args",X,2,"myc merge-driver %O %A %B %L %P");for(let z of[X.ours,X.theirs])if(!
|
|
8032
|
-
`}}var
|
|
8030
|
+
`}function c60($=$0){return{name:"import-beads",summary:"import and sync tasks, dependencies, notes and memories from beads",flags:[{name:"dry-run",description:"count what would be imported, change nothing"},{name:"as",value:"string",description:"actor for the records (default $MYC_ACTOR/$USER)"}],help:"Without arguments collects the snapshot itself via bd export --include-memories; a JSON file argument remains an option for moving between machines. "+"Every beads id is kept in attrs.external_ref; texts are copied verbatim \u2014 references like "+"myc-qie.7 inside descriptions are NOT rewritten. Acceptance criteria and design go into the task body as sections between <!-- beads:<field> --> markers, so show, ready and search see them; source dates and author go to attrs.external_* (created_at/updated_at of the node stay the time of the write). A beads status myc has no name for (deferred, or any unknown one) "+"is imported as blocked \u2014 out of ready, still holding what it blocks \u2014 with the beads status kept "+"in attrs.external_status and as a tag. Re-running is a sync, not just deduplication: fields changed in beads (status, priority, labels, close reason, parent, blockers) are applied through normal graph mutations. Local myc edits are never silently overwritten: one-sided local changes are kept and named in kept_local, two-sided changes are named in conflicts and left untouched.",handler:async(X)=>{let Z=X.args[0],Y,z;if(Z!==void 0){if(!D60(Z))return DK("notfound.file",`snapshot not found: ${Z}`,3);try{Y=MK(yT(Z,"utf8"))}catch(K){return DK("precond.snapshot_format",`snapshot does not parse: ${K instanceof Error?K.message:String(K)}`,5)}z=Z}else{let K=X.globals.directory??process.cwd();try{Y=ty(K)}catch(W){if(W instanceof W3)return DK(W.code,W.code==="precond.bd"?`could not build the snapshot via bd: ${W.message}`:W.message,5,`myc import-beads ${W.jsonlPath}`);return DK("precond.bd",`could not build the snapshot via bd: ${W instanceof Error?W.message:String(W)}`,5)}z=`bd (${K})`}let J=await $.openStore(X);if(!J.ok)return J.failure;let U=J.handle;try{let K;try{K=Lf(U,Y,{dryRun:K0(X,"dry-run"),snapshotName:z})}catch(Q){return C0(Q)}let W=Y.unknownTypes;if(W!==void 0){let Q=Object.entries(W).sort((L,B)=>B[1]-L[1]).map(([L,B])=>`${L}\xD7${B}`).join(", ");X.warn("import.unknown_types",`types myc does not know were imported verbatim into attrs.type: ${Q}`)}let V=Y.unknownFields;if(V!==void 0){let Q=Object.entries(V).sort((L,B)=>B[1]-L[1]||L[0].localeCompare(B[0])).map(([L,B])=>`${L}\xD7${B}`).join(", ");X.warn("import.unknown_fields",`beads task fields the import does not read and did not import anywhere: ${Q}`)}let G=Y.unknownStatuses;if(G!==void 0){let Q=Object.entries(G).sort((L,B)=>B[1].length-L[1].length||L[0].localeCompare(B[0])).map(([L,B])=>`${L}\xD7${B.length} (${B.slice(0,5).join(", ")}${B.length>5?", \u2026":""})`).join("; ");X.warn("import.unknown_statuses",`statuses myc does not know were imported as ${sy} \u2014 out of ready, still holding `+`what they block; the beads status is kept in attrs.external_status and as a tag: ${Q}`)}let H=Y.danglingDeps;if(H!==void 0&&H.length>0)X.warn("import.dangling_deps",`${H.length} ${H.length===1?"dependency has":"dependencies have"} an empty target in beads and ${H.length===1?"was":"were"} not imported: ${H.slice(0,5).join(", ")}${H.length>5?"\u2026":""}`);let N=Y.clampedPriorities;if(N!==void 0&&N.length>0)X.warn("import.priority_clamped",`${N.length} ${N.length===1?"priority":"priorities"} clamped to the myc scale P0..P3: ${N.slice(0,5).join(", ")}`);if(K.skipped.length>0)X.warn("import.skipped",`${K.skipped.length} ${K.skipped.length===1?"record":"records"} not imported: ${K.skipped.slice(0,3).join("; ")}`+(K.skipped.length>3?"\u2026":""));if(K.unknown_dep_types.length>0)X.warn("import.unknown_dep_types",`${K.unknown_dep_types.length} ${K.unknown_dep_types.length===1?"dependency":"dependencies"} of a type that has no myc edge: ${K.unknown_dep_types.slice(0,3).join(", ")}`+(K.unknown_dep_types.length>3?"\u2026":""));if(K.conflicts.length>0)X.warn("import.conflicts",`${K.conflicts.length} ${K.conflicts.length===1?"conflict":"conflicts"}: both sides changed the field, myc applied nothing (${K.conflicts.slice(0,2).join("; ")}\u2026)`);if(K.missing_refs.length>0)X.warn("import.missing_refs",`${K.missing_refs.length} ${K.missing_refs.length===1?"dependency":"dependencies"} with no target in the snapshot or the database (${K.missing_refs.slice(0,3).join(", ")}\u2026)`);return{ok:!0,data:K,meta:{took_ms:K.took_ms}}}finally{U.close()}},renderHuman:p60}}var R60,_60,I60,sy="blocked",k60,E60,W3,cy,K3,$f=($)=>`<!-- beads:${$} -->`,Xf=($)=>`<!-- /beads:${$} -->`,b60,iy=120,m5="beads_sync",w60,h60,oy=80,m60=1e6;var Tf=v(()=>{o();DY();V0();j0();R60=new Set(["task","bug","feature","epic","decision"]),_60=new Set(u8.task),I60=new Map([["deferred","blocked"]]),k60=new Set(["id","title","description","status","priority","issue_type","assignee","labels","dependencies","notes","comments","close_reason","closed_at","acceptance_criteria","design","created_at","updated_at","started_at","created_by","owner","defer_until"]),E60=new Set(["_type","comment_count","dependency_count","dependent_count"]);W3=class W3 extends Error{code;jsonlPath;constructor($,X,Z){super(X);this.code=$;this.jsonlPath=Z}};cy="the file is bd's passive export and can lag behind the database, so it is not picked up on its own \u2014 "+"import it explicitly if it is the state you want";K3=[{field:"acceptance_criteria",heading:"Acceptance criteria"},{field:"design",heading:"Design"}];b60=[C$.sourceCreated,C$.sourceUpdated,"external_started_at","external_created_by","external_owner","external_status","external_defer_until"];w60=["title","body","status","priority","assignee","tags","outcome","closed_at","parent","blocks","acceptance_criteria","design"];h60={"discovered-from":{type:"derived_from",srcIsIssue:!0},supersedes:{type:"supersedes",srcIsIssue:!1}}});var qf={};s(qf,{createMergeDriverCommand:()=>d60});import{existsSync as i60}from"fs";function V3($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function d60(){return{name:"merge-driver",summary:"git merge driver for .myc/graph oplog files: union by op_id",help:"Arguments as git passes them: %O (base) %A (ours, rewritten in place) %B (theirs) [%L marker size] [%P path]. Exit 4 (conflict) when a line does not parse or when one "+"op_id arrives from both sides with different content \u2014 the latter means two live "+`databases share a site_id (S65). Register once per clone:
|
|
8031
|
+
`+OK,handler:($)=>{let X=BJ($.args);if(typeof X==="string")return V3("usage.args",X,2,"myc merge-driver %O %A %B %L %P");for(let z of[X.ours,X.theirs])if(!i60(z))return V3("notfound.file",`file not found: ${z}`,3);let Z;try{Z=TJ(X)}catch(z){let J=z instanceof Error?z.message:String(z);return V3("precond.merge_io",J,5)}if(Z.code!==0||Z.outcome===void 0){if(Z.reason==="collision")return V3("conflict.op_id",Z.message,4,n60);return V3("conflict.oplog_line",Z.message,4)}return{ok:!0,data:{path:X.path??X.ours,lines:Z.outcome.lines,added:Z.outcome.added,message:Z.message}}},renderHuman:($)=>`${$.message}
|
|
8032
|
+
`}}var n60;var Ff=v(()=>{n0();V0();CK();n60="two live databases under one site_id \u2014 usually a copy of the workspace directory (cp -R/rsync), "+"not a clone; see S65 in docs/design/ARCHITECTURE.md"});var nf={};s(nf,{renderBootstrap:()=>If,renderBlock:()=>cT,realProbeEnv:()=>vf,realBootstrapDeps:()=>lf,readPersonalBlocks:()=>uf,mergeBlocks:()=>pT,isBootstrapKey:()=>mf,fingerprint:()=>kf,environmentFingerprint:()=>Ef,createBootstrapCommand:()=>C70,bootstrapQueries:()=>xf,autoBlocks:()=>Sf,MIN_BUDGET:()=>wT,DEFAULT_BUDGET:()=>lT,BOOTSTRAP_TOPIC:()=>_f,BOOTSTRAP_LIST_SQL:()=>wf,BOOTSTRAP_LAYER:()=>Rf,BOOTSTRAP_FORMAT_VERSION:()=>mT,BOOTSTRAP_CACHE_VERSION:()=>uT});import{existsSync as xT,mkdirSync as o60,readFileSync as hT,readdirSync as a60,statSync as s60,writeFileSync as r60}from"fs";import{homedir as jf}from"os";import{join as U$,resolve as t60}from"path";function Af($){if($.source==="manual")return Cf[`manual:${$.tier}`]??39;return Cf[`auto:${$.key}`]??90}function pT($){let X=new Map;for(let Z of $){let Y=`${Z.source}:${Z.key}`,z=X.get(Y);if(z===void 0||z.tier==="personal"&&Z.tier==="project")X.set(Y,Z)}return[...X.values()].sort((Z,Y)=>Af(Z)-Af(Y)||Z.key.localeCompare(Y.key))}function cT($){let X=$.tier==="personal"?"@personal":"",Z=`[${$.source}:${$.key}${X}]`,Y=$.text.split(`
|
|
8033
8033
|
`),z=`${Z} ${Y[0]??""}`.trimEnd();if(Y.length===1)return z;return[z,...Y.slice(1).map((J)=>` ${J}`.trimEnd())].join(`
|
|
8034
|
-
`)}function Pf($,X,Z){let Y=[$],z=$.length,J=[],U=[],K=!1;for(let W of X){let V=cT(W);if(K){J.push(W.key);continue}if(z+1+V.length<=Z){Y.push(V),z+=1+V.length;continue}let G=Z-z-2;if(G>=
|
|
8034
|
+
`)}function Pf($,X,Z){let Y=[$],z=$.length,J=[],U=[],K=!1;for(let W of X){let V=cT(W);if(K){J.push(W.key);continue}if(z+1+V.length<=Z){Y.push(V),z+=1+V.length;continue}let G=Z-z-2;if(G>=e60){let H=`${V.slice(0,G)}\u2026`;Y.push(H),z+=1+H.length,U.push(W.key)}else J.push(W.key);K=!0}return{parts:Y,used:z,dropped:J,clipped:U}}function Df($,X,Z){let Y=[];if($.dropped.length>0)Y.push(`dropped ${$.dropped.length}(${$.dropped.join(",")})`);if($.clipped.length>0)Y.push(`clipped ${$.clipped.length}(${$.clipped.join(",")})`);let z=`# CUT ${Y.join(" ")} \xB7 budget ${X}`;if(z.length<=Z)return z;let J=`# CUT dropped ${$.dropped.length} clipped ${$.clipped.length} \xB7 budget ${X}`;if(J.length<=Z)return J;return J.slice(0,Math.max(0,Z))}function If($){let X=pT($.blocks),Z=X.filter((N)=>N.source==="auto").length,Y=X.length-Z,z=`# MYC BOOTSTRAP v${mT} \xB7 ws=${$.ws}`+` \xB7 auto ${Z} \xB7 manual ${Y} \xB7 fp ${$.fp}`,J=$.budget-bT-2,U=Pf(z,X,J);if(U.dropped.length>0||U.clipped.length>0){let N=(L)=>`${L.dropped.join(",")}|${L.clipped.join(",")}`;for(let L=0;L<=X.length;L++){let B=Math.min(Of,Df(U,$.budget,Of).length),T=Pf(z,X,J-1-B),q=N(T)===N(U);if(U=T,q)break}let Q=Df(U,$.budget,J-U.used-1);if(Q.length>0)U.parts.push(Q)}let{dropped:K,clipped:W}=U,V=U.parts.join(`
|
|
8035
8035
|
`);if(V.length>J)V=V.slice(0,Math.max(0,J));let G=`# ${V.length} body chars / ${$.budget} budget`+` \xB7 ${$.stats.tookMs} ms \xB7 cache ${$.stats.cache}`;if(G.length>bT)G=G.slice(0,bT);let H=`${V}
|
|
8036
8036
|
${G}
|
|
8037
|
-
`;return{text:H,bodyChars:V.length,chars:H.length,budget:$.budget,truncated:K.length>0||W.length>0,dropped:K,clipped:W}}function kf($){let X=2166136261,Z=2654435769,Y=$.join("\x01");for(let z=0;z<Y.length;z++){let J=Y.charCodeAt(z);X=Math.imul(X^J,16777619)>>>0,Z=Math.imul(Z^J+z,2246822507)>>>0}return X.toString(16).padStart(8,"0")+Z.toString(16).padStart(8,"0")}function Ef($,X){let Z=[`v${mT}`];for(let Y of $){let z=Y.kind==="file"?"f":"d";try{let J=
|
|
8038
|
-
`))}function
|
|
8039
|
-
`))}function
|
|
8040
|
-
`))}function
|
|
8041
|
-
`))}function
|
|
8042
|
-
`))}function Sf($,X,Z){let Y=[
|
|
8043
|
-
`}}}function
|
|
8044
|
-
`}}}function
|
|
8037
|
+
`;return{text:H,bodyChars:V.length,chars:H.length,budget:$.budget,truncated:K.length>0||W.length>0,dropped:K,clipped:W}}function kf($){let X=2166136261,Z=2654435769,Y=$.join("\x01");for(let z=0;z<Y.length;z++){let J=Y.charCodeAt(z);X=Math.imul(X^J,16777619)>>>0,Z=Math.imul(Z^J+z,2246822507)>>>0}return X.toString(16).padStart(8,"0")+Z.toString(16).padStart(8,"0")}function Ef($,X){let Z=[`v${mT}`];for(let Y of $){let z=Y.kind==="file"?"f":"d";try{let J=s60(Y.path);Z.push(Y.kind==="file"?`${z}:${Y.path}:${J.mtimeMs}:${J.size}`:`${z}:${Y.path}:${J.mtimeMs}`)}catch{Z.push(`${z}:${Y.path}:-`)}}return Z.push(...X),kf(Z)}function $70($){let X=process.env.MYC_MODELS_DIR;if(X!==void 0&&X!=="")return X;return U$($,".cache","myc","models")}function X70($,X){let Z=[{kind:"file",path:U$($,".mcp.json")},{kind:"file",path:U$($,"opencode.json")},{kind:"dir",path:U$($,".claude","skills")},{kind:"dir",path:U$(X.home,".claude","skills")},{kind:"dir",path:U$($,".orca","skills")},{kind:"dir",path:U$(X.home,".orca","skills")},{kind:"dir",path:U$($,"graft")},{kind:"dir",path:X.modelsDir}];for(let Y of w9(X.modelsDir,32))Z.push({kind:"dir",path:U$(X.modelsDir,Y)});return Z}function Mf($){try{return JSON.parse(hT($,"utf8"))}catch{return null}}function w9($,X=200){try{return a60($,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()&&!Z.name.startsWith(".")).map((Z)=>Z.name).sort().slice(0,X)}catch{return[]}}function yf($,X,Z){return`${$} ${$===1?X:Z}`}function RK($,X){if($.length<=X)return $.join(",");return`${$.slice(0,X).join(",")},+${$.length-X}`}function F4($,X){return{key:$,source:"auto",tier:"project",text:X}}function Z70($){return F4("myc",["project memory and tasks; flags: --json|--ndjson|--strict|-C <dir>|--db <path>",`cmds: ${$.join(",")}`,"exit 0=ok 1=err 2=usage 3=notfound 4=conflict 5=precond 6=degraded 7=no-ws 8=denied 9=timeout","loop: myc ready --claim -> myc show <id> -> myc close <id>",'a launch rule autodetect cannot see: myc bootstrap set <key> "<text>"'].join(`
|
|
8038
|
+
`))}function Y70($){let X=new Map,Y=Mf(U$($,".mcp.json"))?.mcpServers;if(Y!==null&&typeof Y==="object")for(let[K,W]of Object.entries(Y)){let V=W??{},G=typeof V.command==="string"?V.command:"?";X.set(K,{name:K,command:G,from:".mcp.json"})}let J=Mf(U$($,"opencode.json"))?.mcp;if(J!==null&&typeof J==="object")for(let[K,W]of Object.entries(J)){if(X.has(K))continue;let G=(W??{}).command,H=Array.isArray(G)?String(G[0]??"?"):typeof G==="string"?G:"?";X.set(K,{name:K,command:H,from:"opencode.json"})}if(X.size===0)return null;let U=[...X.values()].sort((K,W)=>K.name.localeCompare(W.name));return F4("mcp",[`${yf(U.length,"server","servers")}: ${U.map((K)=>`${K.name}(${K.command})`).join(" ")}`,`config: ${[...new Set(U.map((K)=>K.from))].join(",")}; the host lists the tools, not the config`].join(`
|
|
8039
|
+
`))}function z70($,X){let Z=w9(U$($,".claude","skills")),Y=w9(U$(X.home,".claude","skills")),z=[...new Set([...w9(U$($,".orca","skills")),...w9(U$(X.home,".orca","skills"))])].sort(),J=X.which("orca");if(Z.length+Y.length+z.length===0&&J===null)return null;let U=[];if(Z.length>0)U.push(`project .claude/skills ${Z.length}: ${RK(Z,16)}`);if(Y.length>0)U.push(`personal ~/.claude/skills ${Y.length}; the host lists them`);if(z.length>0)U.push(`orca skills ${z.length}: ${RK(z,12)}`);else if(J!==null)U.push("orca cli present, no skills directory: `orca skills list` gives the full list");return F4("skills",U.join(`
|
|
8040
|
+
`))}function J70($,X){let Z=C2($,{path:X.path,which:(U)=>X.which(U)}),Y=Z.index,z=Z.bin;if(!Y)return null;let J=[`bin=${z??"none"} index=graft/`,'ask "<task>" --source | grep "<literal>" | skeleton <file> | callers <symbol> [--depth all] | map'];if(z===null)J.push("graph present, binary missing: install graft or read graft/*.md directly");return F4("graft",J.join(`
|
|
8041
|
+
`))}function U70($){let X=w9($.modelsDir),Z=[],Y=[];for(let J of X)(xT(U$($.modelsDir,J,"manifest.json"))?Z:Y).push(J);if(Z.length===0&&Y.length===0)return F4("models",`no embedding model installed (${$.modelsDir}); myc models fetch`);let z=[];if(Z.length>0)z.push(`${ff} ${RK(Z,8)}`);if(Y.length>0)z.push(`no manifest: ${RK(Y,4)}`);return F4("models",`embedding models ${z.join("; ")} (${$.modelsDir}); byte-level check: myc models list`)}function K70($,X,Z,Y){let z=S$(X.mycHome),J=!z.exists?"none (myc init --global); every manual block is a project one":Z>0?`${yf(Z,"manual block","manual blocks")}; a project block with the same key overrides the personal one`:"present, no manual blocks";return F4("tiers",`project=${Y??U$($,".myc")} personal=${z.dir} ${J}`)}function W70($){if($.length===0)return null;return F4("degraded",$.map((X)=>`${X.code}: ${X.msg}`).join(`
|
|
8042
|
+
`))}function Sf($,X,Z){let Y=[Z70(Z)],z=Y70($);if(z)Y.push(z);let J=z70($,X);if(J)Y.push(J);let U=J70($,X);if(U)Y.push(U);return Y.push(U70(X)),Y}function gf($){return U$($,"bootstrap.cache.json")}function bf($){try{let X=JSON.parse(hT(gf($),"utf8"));if(X.v!==uT)return null;if(X.trees===null||typeof X.trees!=="object")return null;return X}catch{return null}}function G70($,X,Z){let z=bf($)?.trees[X];if(z===void 0||z.fp!==Z||!Array.isArray(z.blocks))return null;return[...z.blocks]}function H70($,X,Z,Y){try{if(!xT($))o60($,{recursive:!0});let z=Date.now(),J=Object.entries(bf($)?.trees??{}).filter(([K])=>K!==X).sort((K,W)=>W[1].at-K[1].at).slice(0,V70-1),U={v:uT,trees:{...Object.fromEntries(J),[X]:{fp:Z,at:z,blocks:Y}}};return r60(gf($),JSON.stringify(U)),!0}catch{return!1}}function G3($){return $.driver.all(Q70.bootstrap_list,[$.scope]).sort((X,Z)=>X.title.localeCompare(Z.title))}function N70($){return G3($).map((X)=>({key:X.title,source:"manual",tier:"project",text:X.body}))}function mf($){return hf.test($)}function L70($){return{ok:!1,code:"usage.invalid",msg:`key '${$}' is not valid: expected ${hf.source}`,exit:2}}async function uf($,X){let Z=await D6($,X.mycHome);if(!Z.ok||Z.handle===void 0)return[];let Y=Z.handle;try{return G3(Y).map((z)=>({key:z.title,source:"manual",tier:"personal",text:z.body}))}finally{Y.close()}}async function cf($,X,Z){if(!Z){let z=await X.store.openStore($);return z.ok?{ok:!0,handle:z.handle,tier:"project"}:{ok:!1,failure:z.failure}}let Y=await D6($,X.env.mycHome);if(!Y.ok)return{ok:!1,failure:Y.failure};if(Y.handle===void 0)return{ok:!1,failure:{ok:!1,code:"ws.not_initialized",msg:`personal tier not created: no ${S$(X.env.mycHome).dbPath}`,exit:7,hint:"myc init --global"}};return{ok:!0,handle:Y.handle,tier:"personal"}}function T70($,X,Z){let Y=$.flags.budget,z=process.env.MYC_BOOTSTRAP_BUDGET,J;try{let K=U$(Z??U$(X,".myc"),"workspace.toml");if(xT(K))J=P6(hT(K,"utf8")).bootstrapBudget}catch{}let U=typeof Y==="number"?Y:z!==void 0&&z!==""?Number(z):J??lT;if(!Number.isFinite(U)||U<wT)return{ok:!1,code:"usage.invalid",msg:`--budget ${U}: minimum is ${wT} chars, below that not even the header fits`,exit:2};return Math.floor(U)}function q70($){return{name:"bootstrap",summary:"mandatory start-of-session context block for an agent",help:"Prints a ready-to-paste block: environment autodetect plus manual blocks "+"(myc bootstrap set). Every block is tagged with its source \u2014 [auto:*] or "+"[manual:*]. Autodetect is cached by an environment fingerprint.",flags:[B70,{name:"no-cache",description:"ignore and do not write the autodetect cache"},{name:"refresh",description:"recompute autodetect and rewrite the cache"}],handler:async(X)=>{let Z=performance.now(),Y=t60(X.globals.directory??process.cwd()),z=g2(Y,X.globals.db),J=T70(X,Y,z);if(typeof J!=="number")return J;let U=$.env,K=$.commands(),W=X.flags["no-cache"]===!0,V=X.flags.refresh===!0,G=Ef(X70(Y,U),[`path:${U.path}`,`cmds:${K.join(",")}`,`myc:${$.build??E0}`]),H=await $.store.openStore(X),N=[],Q=H.ok?H.handle:void 0;if(Q===void 0)X.warn("ws.absent",`workspace not initialized, no manual blocks: ${Y}`),N.push({code:"ws.absent",msg:"workspace not initialized, no manual blocks: myc init"});try{let L=Q!==void 0?N70(Q):[],B="off",T=null,q=Q!==void 0&&z!==void 0&&!W;if(q&&!V){if(T=G70(z,Y,G),T!==null)B="hit"}if(T===null){if(T=Sf(Y,U,K),q)B=H70(z,Y,G,T)?"miss":"off"}let j=await $.personalBlocks(X,U),O=T.find((E)=>E.key==="models");if(O!==void 0&&!O.text.includes(ff))N.push({code:"embed.model_absent",msg:"embedding model not installed, retrieval runs without vectors: myc models fetch"});let A=[],R=W70(N);if(R)A.push(R);A.push(K70(Y,U,j.length,z));let D=[...T,...A,...L,...j],F=Math.max(1,Math.round(performance.now()-Z)),P=If({blocks:D,budget:J,ws:Q?.slug??"-",fp:G,stats:{tookMs:F,cache:B}}),_=pT(D),M={text:P.text,chars:P.chars,body_chars:P.bodyChars,budget:P.budget,truncated:P.truncated,dropped:[...P.dropped],clipped:[...P.clipped],fp:G,cache:B,auto:_.filter((E)=>E.source==="auto").length,manual:_.filter((E)=>E.source==="manual").length,tiers:j.length>0?["project","personal"]:["project"],blocks:_.map((E)=>({key:E.key,source:E.source,tier:E.tier,chars:cT(E).length})),took_ms:F};return{ok:!0,data:M,meta:{chars:M.chars,budget:M.budget,cache:B,fp:G,truncated:M.truncated}}}finally{Q?.close()}},renderHuman:(X)=>X.text}}function F70($){return{name:"set",summary:"pin a manual bootstrap block (L3 note, survives compaction)",help:"myc bootstrap set [--global] <key> <text>; text '-' is read from stdin. Without --global the block goes to the project tier, with it to the personal one in ~/.myc.",flags:[pf],handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0)return{ok:!1,code:"usage.missing_arg",msg:"key required: myc bootstrap set <key> <text>",exit:2};if(!mf(Y))return L70(Y);let z=X.args.slice(1).join(" ");if(z.length===0)return{ok:!1,code:"usage.missing_arg",msg:"text required: myc bootstrap set <key> <text> (or '-' for stdin)",exit:2};let J=z==="-"?(await new Response(Bun.stdin.stream()).text()).trim():z;if(J.length===0)return{ok:!1,code:"usage.empty",msg:"empty block text",exit:2};let U=await cf(X,$,X.flags.global===!0);if(!U.ok)return U.failure;let K=U.handle;try{let W=G3(K).find((N)=>N.title===Y),V,G;if(W!==void 0)V=K.store.updateNode(W.id,{body:J}),G=!1;else{let N={topic:_f,source:"user",tags:["bootstrap"]};V=K.store.createNode({kind:"note",layer:Rf,scope:K.scope,title:Y,body:J,attrs:N}),G=!0}return{ok:!0,data:{key:Y,id:V.id,tier:U.tier,chars:J.length,created:G,took_ms:Math.max(1,Math.round(performance.now()-Z))}}}catch(W){return C0(W)}finally{K.close()}},renderHuman:(X)=>{let Z=X,Y=Z.created?"set":"updated",z=Z.tier==="personal"?"@personal":"";return`${Y} [manual:${Z.key}${z}] ${Z.id} \xB7 ${Z.chars} chars \xB7 ${Z.took_ms} ms
|
|
8043
|
+
`}}}function j70($){return{name:"rm",summary:"remove a manual bootstrap block",flags:[pf],handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0)return{ok:!1,code:"usage.missing_arg",msg:"key required: myc bootstrap rm <key>",exit:2};let z=await cf(X,$,X.flags.global===!0);if(!z.ok)return z.failure;let J=z.handle;try{let U=G3(J).find((W)=>W.title===Y);if(U===void 0)return{ok:!1,code:"notfound.block",msg:`no manual block '${Y}'`,exit:3,hint:"myc bootstrap list"};return J.store.deleteNode(U.id),{ok:!0,data:{key:Y,id:U.id,tier:z.tier,took_ms:Math.max(1,Math.round(performance.now()-Z))}}}catch(U){return C0(U)}finally{J.close()}},renderHuman:(X)=>{let Z=X,Y=Z.tier==="personal"?"@personal":"";return`removed [manual:${Z.key}${Y}] ${Z.id} \xB7 ${Z.took_ms} ms
|
|
8044
|
+
`}}}function O70($){return{name:"list",summary:"list manual bootstrap blocks",handler:async(X)=>{let Z=await $.store.openStore(X);if(!Z.ok)return Z.failure;let Y=Z.handle;try{let z=G3(Y).map((J)=>({key:J.title,id:J.id,tier:"project",chars:J.body.length,updated_at:J.updated_at}));for(let J of await $.personalBlocks(X,$.env))z.push({key:J.key,id:"-",tier:"personal",chars:J.text.length,updated_at:0});return{ok:!0,data:z,meta:{count:z.length}}}finally{Y.close()}},renderHuman:(X)=>{let Z=X;if(Z.length===0)return`no manual blocks \xB7 myc bootstrap set <key> <text>
|
|
8045
8045
|
`;return`${Z.map((z)=>`${z.key.padEnd(16)} ${z.tier.padEnd(8)} ${String(z.chars).padStart(5)} chars ${z.id}`).join(`
|
|
8046
8046
|
`)}
|
|
8047
|
-
`}}}function
|
|
8047
|
+
`}}}function C70($=lf){return{...q70($),subcommands:[F70($),j70($),O70($)]}}var mT=1,uT=3,Rf=3,_f="bootstrap",lT=2000,wT=200,bT=80,Of=120,e60=48,Cf,vf,ff="with manifest:",V70=8,wf,xf,Q70,hf,lf,pf,B70;var df=v(()=>{BH();K8();V0();v8();$X();j0();Cf={"auto:myc":10,"auto:degraded":20,"manual:project":30,"manual:personal":35,"auto:graft":40,"auto:mcp":50,"auto:skills":60,"auto:models":70,"auto:tiers":80};vf={home:jf(),mycHome:e$(),modelsDir:$70(jf()),path:process.env.PATH??"",which:($)=>{try{return Bun.which($)}catch{return null}}};wf=`SELECT id, title, coalesce(body,'') AS body, updated_at
|
|
8048
8048
|
FROM nodes
|
|
8049
8049
|
WHERE scope = ?1 AND kind = 'note'
|
|
8050
8050
|
AND layer >= 2 AND layer = 3
|
|
8051
8051
|
AND head_id IS NULL AND deleted_at IS NULL
|
|
8052
8052
|
AND g_topic = 'bootstrap'
|
|
8053
8053
|
AND ${k0("nodes")}
|
|
8054
|
-
AND ${Y7("nodes")}`,xf={bootstrap_list:{name:"bootstrap_list",sql:wf,params:["scope"]}},
|
|
8055
|
-
`,1)[0]??"").trim();if(Z.length<=iT&&Z.length===X.length)return{title:Z,body:null};return{title:Z.length<=iT?Z:`${Z.slice(0,iT-1).trimEnd()}\u2026`,body:X}}function
|
|
8054
|
+
AND ${Y7("nodes")}`,xf={bootstrap_list:{name:"bootstrap_list",sql:wf,params:["scope"]}},Q70=xf;hf=/^[a-z][a-z0-9_-]{0,31}$/;lf={store:$0,env:vf,commands:()=>E7.top.map(($)=>$.name).sort(),personalBlocks:uf},pf={name:"global",description:"act on the personal tier ~/.myc instead of the project one"};B70={name:"budget",value:"number",description:`output cap in chars (default ${lT}, env MYC_BOOTSTRAP_BUDGET)`}});var ef={};s(ef,{realRememberDeps:()=>IK,createRememberCommand:()=>E70,confirmCandidate:()=>_K});function rf($,X){let Z=[{kind:"embed",payload:{reason:X}}];if($)Z.push({kind:"absorb",payload:{reason:X}});return Z}function _K($,X,Z,Y,z){$.store.updateNode(X.id,{attrs:yz(Z,Y),...X.salience<cZ?{salience:cZ}:{}});let J=rf(z,"review_confirmed");try{return tf($,X.id,$.scope,J,Y),{queue:J.map((U)=>U.kind)}}catch(U){return{queue:[],queueError:U instanceof Error?U.message:String(U)}}}function tf($,X,Z,Y,z){if(Y.length===0)return;$.driver.tx("immediate",(J)=>{for(let U of Y)J.run(sf.job_enqueue,[U.kind,X,Z,A70[U.kind]??5,z,JSON.stringify(U.payload)])})}function H3($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function D70($){if($===void 0)return[];return $.split(",").map((X)=>X.trim()).filter((X)=>X.length>0)}function M70($){let X=/^L?([0-3])$/i.exec($.trim());return X?Number(X[1]):void 0}function R70($){let X=$.trim(),Z=(X.split(`
|
|
8055
|
+
`,1)[0]??"").trim();if(Z.length<=iT&&Z.length===X.length)return{title:Z,body:null};return{title:Z.length<=iT?Z:`${Z.slice(0,iT-1).trimEnd()}\u2026`,body:X}}function _70($){let X={source:"agent"};if($.tags.length>0)X.tags=[...$.tags];return{kind:"note",scope:$.scope,title:$.title,body:$.body,...$.layer!==void 0?{layer:$.layer}:{},attrs:X}}function I70($=process.env){for(let X of["ANTHROPIC_API_KEY","OPENAI_API_KEY","MYC_CHAT_API_KEY"]){let Z=$[X];if(typeof Z==="string"&&Z.trim().length>0)return!0}return!1}function of($){return $.queue.map((X)=>X==="absorb"&&$.absorb_heuristic?"absorb(heuristic \u2014 chat-LLM off)":X)}function af($){if($.reach==="project")return"reach project";if($.reach==="session")return`reach session ${$.session}`;return"reach UNKNOWN (session not determined)"}function k70($){let X=$;if(X.duplicate_of!==void 0){let U=X.reach_promoted===!0?", promoted to project":"",K=X.review_confirmed===!0?" of an unconfirmed compaction candidate \u2014 confirmed now, recall and prime return it":X.hidden_status!==void 0?` of a ${X.hidden_status} node \u2014 recall and prime do not return it`:"",W=X.queue.length>0?` \xB7 queue ${of(X).join(", ")}`:"";return`${X.id} duplicate \xB7 exact repeat${K}, seen_count ${X.seen_count??"?"}${U} \xB7 `+`${af(X)}${W} \xB7 ${X.took_ms} ms
|
|
8056
8056
|
`}let Z=[X.id,X.kind==="note"?"memory":X.kind,`L${X.layer}`],Y=[af(X)];if(X.tier==="personal")Y.push("tier personal (~/.myc)");if(X.tags.length>0)Y.push(`tags ${X.tags.join(",")}`);if(Y.push(`acl ${X.acl}`),X.source!==void 0)Y.push(`source ${X.source}`);let z=[`${Z.join(" ")} \xB7 ${Y.join(" \xB7 ")}`];for(let U of X.anchors)z.push(z9(U));let J=of(X);return z.push(`queue ${J.length>0?J.join(", "):"\u2014"}`),z.push(`${X.took_ms} ms`),`${z.join(`
|
|
8057
8057
|
`)}
|
|
8058
|
-
`}function
|
|
8058
|
+
`}function E70($=IK){return{name:"remember",summary:"record a fact into memory (project tier, or --global for ~/.myc)",flags:P70,help:"Writes one memory node. The fact is the positional argument; '-' reads stdin. Everything expensive (embedding, absorb classification) is queued in jobs, never done on the write path: the write itself is a single transaction under 5 ms.",handler:async(X)=>{let Z=performance.now(),Y=X.args.join(" ").trim(),z;if(Y==="-")z=(await new Response(Bun.stdin.stream()).text()).trim();else z=Y;if(z.length===0)return H3("usage.invalid","fact text required: myc remember <text> (or - for stdin)",2);let J,U=f(X,"layer");if(U!==void 0){if(J=M70(U),J===void 0)return H3("usage.invalid",`invalid layer '${U}'; allowed: L0..L3`,2)}let K=f(X,"reach");if(K!==void 0&&!OX.includes(K))return H3("usage.invalid",`invalid --reach '${K}'; allowed: ${OX.join("|")}`,2);let W=K??"session",V=z8(f(X,"session")),G=W==="project"||V.length>0,H,N=f(X,"anchor");if(N!==void 0){if(H=E8(N),H===void 0||H.path.length===0)return H3("usage.invalid",`invalid anchor '${N}'; format: file[:a-b]`,2)}let Q=X.flags.global===!0,L;if(Q){let B=S$(),T=await $.openPersonal(X);if(!T.ok)return T.failure;if(T.handle===void 0)return H3("ws.not_initialized",`personal tier not initialized: no ${B.dbPath}`,7,"myc init --global");L=T.handle}else{let B=await $.openStore(X);if(!B.ok)return B.failure;L=B.handle}try{if(H!==void 0){let y=await qY(L,H,X.globals.directory??process.cwd());if(y!==void 0)return y}let{title:B,body:T}=R70(z),q=D70(f(X,"tag")),j=f(X,"source"),O=f(X,"acl"),A=_70({scope:L.scope,title:B,body:T,tags:q,...J!==void 0?{layer:J}:{}}),R={...A.attrs};if(G)Object.assign(R,d4(W,V));else X.warn("degraded.reach","reach not recorded: session identity unknown \u2014 pass --session, "+"set MYC_SESSION_ID, or write with --reach project");if(j!==void 0)R.provenance=j;let D=L.driver.one(sf.exact_dup,[L.scope,A.kind,V6(A.kind,B,T)]);if(D!==void 0){let y;try{y=L.store.bumpCounter(D.id,"seen_count")}catch(r){return C0(r)}let g;try{g=JSON.parse(D.attrs)}catch{g=void 0}let S=C8(g),w=S,h=!1;if(K==="project"&&S.reach!=="project")try{L.store.updateNode(D.id,{attrs:d4("project","")}),w={reach:"project",session:"",by:"recorded"},h=!0}catch(r){return C0(r)}else if(S.reach==="session"&&(V.length===0||S.session!==V))X.warn("degraded.reach",`fact already recorded in another session (${S.session}) and stays there; `+"to promote it to project \u2014 myc remember \u2026 --reach project");let u=!1,d=[];if(l7(g,D.status))try{let r=_K(L,D,f(X,"as")??L.actor,Date.now(),X.flags["no-absorb"]!==!0);if(d=r.queue,r.queueError!==void 0)X.warn("degraded.queue",`background queue unavailable: ${r.queueError}`);u=!0}catch(r){return C0(r)}let a=u7(D.status)?D.status:void 0;if(a!==void 0)X.warn("degraded.hidden",`fact already recorded as ${D.id} and ${a}: recall and prime do not return it`+(a==="superseded"?` \u2014 its current version: myc show ${D.id}`:` \u2014 to restore it: myc update ${D.id} --status active`));let e={id:D.id,kind:A.kind,tier:Q?"personal":"project",reach:w.reach,session:w.session,...h?{reach_promoted:!0}:{},layer:J??1,acl:O??"team",tags:q,anchors:[],queue:d,absorb_heuristic:d.includes("absorb")&&!$.chatLlm(),duplicate_of:D.id,seen_count:y,...u?{review_confirmed:!0}:{},...a!==void 0?{hidden_status:a}:{},body_chars:z.length,took_ms:Math.round((performance.now()-Z)*10)/10};return{ok:!0,data:e,meta:{took_ms:e.took_ms,tier:e.tier,queue:d,duplicate_of:D.id,...u?{review_confirmed:!0}:{},reach:w.reach,session:w.session.length>0?w.session:null}}}let F;try{F=L.store.createNode({...A,attrs:R,actor:f(X,"as")??L.actor,...O!==void 0?{acl:O}:{}})}catch(y){return C0(y)}let P=Date.now(),_=rf(X.flags["no-absorb"]!==!0,"remember"),M=_.map((y)=>y.kind);try{tf(L,F.id,L.scope,_,P)}catch(y){M=[],X.warn("degraded.queue",`background queue unavailable: ${y instanceof Error?y.message:String(y)}`)}let E=H===void 0?[]:[await jY(L,F.id,H,X.globals.directory??process.cwd(),(y,g)=>X.warn(y,g))],b=M.includes("absorb")&&!$.chatLlm(),k={id:F.id,kind:F.kind,tier:Q?"personal":"project",reach:G?W:"unknown",session:G&&W==="session"?V:"",layer:F.layer,acl:F.acl,tags:q,...j!==void 0?{source:j}:{},anchors:E,queue:M,absorb_heuristic:b,body_chars:z.length,took_ms:Math.round((performance.now()-Z)*10)/10};return{ok:!0,data:k,meta:{took_ms:k.took_ms,tier:k.tier,queue:M,reach:k.reach,session:k.session.length>0?k.session:null}}}finally{L.close()}},renderHuman:k70}}var sf,A70,P70,iT=120,IK;var nT=v(()=>{o();K8();V0();k6();j0();sf=Z0({exact_dup:{name:"exact_dup",sql:`SELECT id, attrs, status, salience FROM nodes
|
|
8059
8059
|
WHERE scope = ?1 AND kind = ?2 AND content_hash = ?3 AND deleted_at IS NULL`,params:["scope","kind","content_hash"]},job_enqueue:{name:"job_enqueue",sql:`INSERT INTO jobs (kind, entity_id, scope, priority, run_after, payload, created_at)
|
|
8060
8060
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?5)
|
|
8061
|
-
ON CONFLICT DO NOTHING`,params:["kind","entity_id","scope","priority","now","payload"]}}),
|
|
8061
|
+
ON CONFLICT DO NOTHING`,params:["kind","entity_id","scope","priority","now","payload"]}}),A70={embed:3,absorb:5,anchor_check:6};P70=[{name:"tag",value:"string",list:!0,description:"comma-separated tags"},{name:"anchor",value:"string",description:"bind an anchor file[:<a>-<b>]; a directory, a binary or secret-named file is refused before anything is written; a missing file or a path outside the root stays an intent (WARN)"},{name:"layer",value:"string",description:"L0|L1|L2|L3 (default L1)"},{name:"acl",value:"string",description:"private|team|restricted|agent"},{name:"source",value:"string",description:"provenance: url or file"},{name:"no-absorb",description:"do not queue absorb classification"},{name:"global",description:"write to the personal tier ~/.myc instead of the project"},{name:"as",value:"string",description:"actor for the record (default $MYC_ACTOR/$USER)"},{name:"reach",value:"string",description:"session (default) | project \u2014 memory reach, S58"},{name:"session",value:"string",description:"session identity (default $MYC_SESSION_ID/$CLAUDE_SESSION_ID)"}];IK={openStore:$0.openStore,openPersonal:($)=>D6($),chatLlm:()=>I70()}});var KS={};s(KS,{realRecallDeps:()=>US,createRecallCommand:()=>o70});function x9($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function S70($){if($===void 0)return"hybrid";if($==="hybrid"||$==="vec"||$==="bm25")return $;return}function g70($,X,Z){let Y=$.replace(/\s+/g," ").trim();if(Y.length===0)return[];let z=[],J=Y;while(J.length>0&&z.length<Z){if(J.length<=X){z.push(J),J="";break}let K=J.slice(0,X+1).lastIndexOf(" "),W=K>X*0.5?K:X;z.push(J.slice(0,W).trimEnd()),J=J.slice(W).trimStart()}if(J.length>0&&z.length>0){let U=z[z.length-1];z[z.length-1]=`${U.slice(0,Math.max(0,X-1)).trimEnd()}\u2026`}return z}function b70($){return $.confidence===void 0?" \xB7":$.confidence.toFixed(2).padStart(4)}function h70($){if($.tier==="personal")return"\xB7me";if($.tier==="repo")return`@${$.source.slice(0,x70)}`;return""}function l70($){if($.anchor_state===void 0)return"";let X=$.anchor_weight!==void 0?` \xD7${$.anchor_weight}`:"";return`[${m70[$.anchor_state]}${X}] `}function zS($,X){let Z=b70($),Y=`L${$.layer}${h70($)}`,z=RV({reach:$.reach,session:$.reach_session,by:$.reach_by},X).padEnd(4),J=CV({repo:$.repo,state:$.repo_state,by:"recorded"}).slice(0,w70).padEnd(4);return`${$.rank}. ${Z} ${$.id} ${$.type} ${Y} ${z} ${J} ${d0($.updated_at)} ${l70($)}`}function p70($,X){return`${zS($,X)}${$.title}`}function i70($,X,Z){let Y=zS($,Z),z=Y.length+dT.length+1,J=`${Y}${$.title}${dT}`;if(J.length+1<=X)return J;let U=X-z-1;if(U<c70)return null;return`${Y}${$.title.slice(0,U).trimEnd()}\u2026${dT}`}function n70($){let X=$.excerpt.trim(),Z=$.title.trim();if(Z.length>0&&X.startsWith(Z))return X.slice(Z.length).trim();return X}function XS($){let X=0;for(let Z of $)X+=Z.length+1;return X}function JS($){let X=[],Z=[],Y=[],z=0;for(let J of $.rows){let U=[p70(J,$.session),...g70(n70(J),y70,f70).map((W)=>` ${W}`)];if(z+XS(U)<=$.budget){X.push(...U),z+=XS(U);continue}let K=i70(J,$.budget-z,$.session);if(K!==null)X.push(K),z+=K.length+1,Z.push(J.id);else Y.push(J.id)}return{lines:X,used:z,collapsed:Z,dropped:Y}}function d70($){let X=$,{lines:Z,used:Y,collapsed:z,dropped:J}=JS(X),U=[`${X.shown} of ${X.total}`,X.mode,`${X.took_ms} ms`,`${Y} chars of ${X.budget}`];if(X.tiers.personal)U.push("2 tiers");if(X.federation.total>1)U.push(`${X.federation.queried.length} of ${X.federation.total} sources`);if(X.federation.skipped.length>0){let K=new Map;for(let W of X.federation.skipped){let V=K.get(W.why);if(V===void 0)K.set(W.why,[W.id]);else V.push(W.id)}for(let[W,V]of K)U.push(`${V.length} ${V.length===1?"source":"sources"} skipped (${V.join(", ")}): ${W}`)}if(X.foreign>0)U.push(`${X.foreign} from other sessions`);if(X.unknown_reach>0)U.push(`${X.unknown_reach} without reach`);if(X.repo.length>0)U.push(`repo ${X.repo}`);if(X.unknown_repo>0)U.push(`${X.unknown_repo} without repo reach`);if(X.anchor_lost>0)U.push(`${X.anchor_lost} code gone \u2014 unbind: ${u70}`);if(X.deduped>0)U.push(`${X.deduped} ${X.deduped===1?"duplicate":"duplicates"} collapsed`);if(z.length>0)U.push(`${z.length} collapsed by budget`);if(J.length>0)U.push(`${J.length} not shown (budget)`);if(X.partial){let K=[];if(X.omitted>0)K.push(`${X.omitted} over budget`);if(X.budget_timed_out)K.push("assembly timeout");U.push(`partial: ${K.length>0?K.join(", "):"not everything returned"}`)}if(X.cursor!==void 0)U.push(`next: --offset ${X.cursor}`);if(X.pool_exhausted)U.push("pool exhausted, total is a lower bound");if(Z.push(U.join(" \xB7 ")),X.why!==void 0)Z.push(...X.why);return`${Z.join(`
|
|
8062
8062
|
`)}
|
|
8063
|
-
`}function
|
|
8063
|
+
`}function o70($=US){return{name:"recall",summary:"agent-facing memory search: character budget, dedup, collapsed output",flags:$S,help:"Same engine as `myc search`, different UX (decision D6). Reads BOTH tiers through federatedSearch and marks the personal tier as `me`. The footer always names the retrieval branches that actually produced the output; degradation is a WARN line, and exit 6 under --strict.",handler:async(X)=>{let Z=X.args.join(" ").trim();if(Z.length===0)return x9("usage.invalid","query required: myc recall <text>",2);let Y=S70(f(X,"mode"));if(Y===void 0)return x9("usage.invalid",`invalid --mode '${f(X,"mode")}'; allowed: hybrid, vec, bm25`,2);let z=_U(f(X,"kind"));if(!z.ok)return x9("usage.invalid",`unknown --kind '${z.bad}'; allowed: ${K9.join(", ")}`,2);let J=IU(f(X,"layer"));if(!J.ok)return x9("usage.invalid",`invalid --layer '${f(X,"layer")}'; format: L1 or L1..L3`,2);let U,K=f(X,"since");if(K!==void 0){let k=P$(K);if(k===void 0)return x9("usage.invalid",`invalid --since '${K}'; format: 30d, 12h, 90m`,2);U=Date.now()-k}let W=t(X,"limit"),V=W!==void 0&&Number.isFinite(W)&&W>0?Math.min(Math.floor(W),100):ZS,G=t(X,"offset"),H=G!==void 0&&Number.isFinite(G)&&G>0?Math.floor(G):0,N=t(X,"budget"),Q=N!==void 0&&Number.isFinite(N)&&N>0?Math.min(Math.floor(N),v70):YS,B=(f(X,"reach")??"").split(",").map((k)=>k.trim()).filter((k)=>k.length>0),T=[...OX,"unknown"],q=B.find((k)=>!T.includes(k));if(q!==void 0)return x9("usage.invalid",`invalid --reach '${q}'; allowed: ${T.join(", ")}`,2);let j=z8(f(X,"session")),O=(f(X,"tag")??"").split(",").map((k)=>k.trim()).filter((k)=>k.length>0),A=t(X,"embed-timeout"),R=A!==void 0&&Number.isFinite(A)&&A>=0?Math.floor(A):PU(),D=t(X,"sources"),F=D!==void 0&&Number.isFinite(D)&&D>=1?Math.floor(D):void 0,P=await kU(X,$,{text:Z,limit:V,offset:H,mode:Y,fullFields:!1,charBudget:Q,upgradeContent:!1,embedTimeoutMs:R,...F!==void 0?{maxSources:F}:{},knobs:$S.map((k)=>k.name),filters:{...z.kinds.length>0?{kinds:z.kinds}:{},...O.length>0?{tags:O}:{},...J.min!==void 0?{layerMin:J.min}:{},...J.max!==void 0?{layerMax:J.max}:{},...U!==void 0?{since:U}:{},...f(X,"anchor")!==void 0?{anchor:f(X,"anchor")}:{},...B.length>0?{reach:B}:{},...B.includes("session")&&j.length>0?{reachSession:j}:{},...f(X,"repo")!==void 0?{repo:f(X,"repo")}:{}}});if(!P.ok)return P.failure;let _=P.outcome,M={query:Z,rows:[..._.rows],collapsed:[],dropped:[],shown:_.rows.length,total:_.total,pool_exhausted:_.poolExhausted,deduped:_.deduped,budget:Q,used_chars:0,mode:_.modeLabel,mode_used:_.mode_used,tiers:_.tiers,federation:_.federation,personal_available:_.tiers.personal||MI(),session:j,foreign:_.rows.filter((k)=>k.reach==="session"&&k.reach_session!==j).length,unknown_reach:_.rows.filter((k)=>k.reach==="unknown").length,repo:_.repo,unknown_repo:_.rows.filter((k)=>k.repo_state==="unknown").length,anchor_lost:_.rows.filter((k)=>k.anchor_state==="lost"&&k.kind!=="anchor").length,drops:_.drops,why:X.flags.why===!0?RU(_.mode_used):void 0,took_ms:_.took_ms,partial:_.partial,omitted:_.omitted,cursor:_.cursor,budget_timed_out:_.budgetTimedOut},E=JS(M);return{ok:!0,data:{...M,collapsed:E.collapsed,dropped:E.dropped,shown:_.rows.length-E.dropped.length,used_chars:E.used},meta:{took_ms:_.took_ms,mode:_.modeLabel,mode_used:_.mode_used,budget:Q,used_chars:E.used,session:j.length>0?j:null,foreign:M.foreign,unknown_reach:M.unknown_reach,repo:_.repo.length>0?_.repo:null,federation:_.federation,unknown_repo:M.unknown_repo,anchor_lost:M.anchor_lost,partial:_.partial,omitted:_.omitted,..._.cursor!==void 0?{cursor:_.cursor}:{},budget_timed_out:_.budgetTimedOut,budget_chars:_.budgetChars,engine_used_chars:_.usedChars}}},renderHuman:d70}}var ZS=12,YS=2000,v70=64000,y70=92,f70=2,$S,w70=12,x70=10,m70,u70="myc anchor rm <id>",dT=" (collapsed)",c70=24,US;var WS=v(()=>{o();V0();j0();EU();$S=[{name:"limit",short:"n",value:"number",description:`max hits (default ${ZS})`},{name:"offset",value:"number",description:"skip N rows (continues a previous page's cursor)"},{name:"budget",value:"number",description:`output character budget (default ${YS})`},{name:"kind",value:"string",list:!0,description:`comma-separated kinds: ${K9.join(",")}`},{name:"tag",value:"string",list:!0,description:"comma-separated tags (any match)"},{name:"layer",value:"string",description:"L0..L3 or a range like L1..L3"},{name:"since",value:"string",description:"only nodes updated within, e.g. 30d, 12h"},{name:"anchor",value:"string",description:"only nodes anchored at this file: <file> or <file>:<line>, from the current directory or absolute \u2014 "+"nodes with a real anchor on it (whether bound from the workspace root or from inside the file's repo or worktree), plus unbound anchor intents (state pending) whose path as typed contains the argument"},{name:"mode",value:"string",description:"hybrid (default) | vec | bm25"},{name:"why",description:"print why each retrieval branch was or was not used"},{name:"reach",value:"string",list:!0,description:"comma-separated: session,project,unknown (S58)"},{name:"repo",value:"string",description:"repository scope (S59): a repo name, or `all` to drop the filter"},{name:"session",value:"string",description:"session identity: marks own rows as `ses`, filters with --reach session"},{name:"embed-timeout",value:"number",description:"ms to wait for the embedder to warm up (default 0 = skip the vector branch)"},{name:"sources",value:"number",description:"max workspaces to query (R3); higher raises latency, the footer names the skipped"}];m70=Object.freeze({drifted:"code moved",stale:"code unverified",lost:"code gone"});US={openStore:$0.openStore,...MU}});var QS={};s(QS,{realSearchDeps:()=>HS,createSearchCommand:()=>$40,FIELD_NAMES:()=>s70});function j4($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function oT($){if($===void 0)return[];return $.split(",").map((X)=>X.trim()).filter((X)=>X.length>0)}function r70($){if($===void 0)return"hybrid";if($==="hybrid"||$==="vec"||$==="bm25")return $;return}function t70($){if($===void 0)return"score";if($==="score"||$==="updated"||$==="created")return $;return}function e70($,X){let Z=$,Y=[];if(Z.full)for(let J of Z.rows){let U=J.tier==="personal"?" \xB7me":"";Y.push(`${J.id} ${J.type} L${J.layer}${U} ${d0(J.updated_at)} ${J.title}`);let K=[];if((J.tags??[]).length>0)K.push(`tags ${(J.tags??[]).join(",")}`);if(J.acl!==void 0)K.push(`acl ${J.acl}`);if((J.author??"").length>0)K.push(`by ${J.author}`);if(K.push(`src ${J.sources.join("+")}`),Y.push(` ${K.join(" \xB7 ")}`),J.content_kind==="crux")Y.push(" (truncated by budget)");let W=(J.body??J.excerpt).trim(),V=J.title.trim();if(V.length>0&&W.startsWith(V))W=W.slice(V.length).trim();if(W.length>0)Y.push(` ${W.replace(/\n/g,`
|
|
8064
8064
|
`)}`);for(let G of J.anchors??[])Y.push(` \u2316 ${G}`)}else{let J=Z.fields,U=Z.rows.map((K)=>Z.fields.map((W)=>(Q3[W]??(()=>""))(K)));if(U.length>0)Y.push(hJ(J,U,X.globals.color).trimEnd())}let z=[`${Z.shown} of ${Z.total}`,Z.mode,`${Z.took_ms} ms`];if(Z.offset>0)z.push(`offset ${Z.offset}`);if(Z.tiers.personal)z.push("2 tiers");if(Z.deduped>0)z.push(`${Z.deduped} ${Z.deduped===1?"duplicate":"duplicates"} collapsed`);if(Z.partial){let J=[];if(Z.omitted>0)J.push(`${Z.omitted} over budget`);if(Z.budget_timed_out)J.push("assembly timeout");z.push(`partial: ${J.length>0?J.join(", "):"not everything returned"}`)}if(Z.cursor!==void 0)z.push(`next: --offset ${Z.cursor}`);if(Z.pool_exhausted)z.push("pool exhausted, total is a lower bound");if(Y.push(z.join(" \xB7 ")),Z.why!==void 0)Y.push(...Z.why);return`${Y.join(`
|
|
8065
8065
|
`)}
|
|
8066
|
-
`}function
|
|
8067
|
-
`);let z=
|
|
8068
|
-
${Z}`}function
|
|
8066
|
+
`}function $40($=HS){return{name:"search",summary:"human-facing memory search: full fields, filters, sorting, paging",flags:VS,help:"Same engine as `myc recall` (decision D6), different UX. Reads BOTH tiers through federatedSearch; the `tier` column marks where a hit came from. The footer names the retrieval branches that actually produced the output.",handler:async(X)=>{let Z=X.args.join(" ").trim();if(Z.length===0)return j4("usage.invalid","query required: myc search <text>",2);let Y=r70(f(X,"mode"));if(Y===void 0)return j4("usage.invalid",`invalid --mode '${f(X,"mode")}'; allowed: hybrid, vec, bm25`,2);let z=t70(f(X,"sort"));if(z===void 0)return j4("usage.invalid",`invalid --sort '${f(X,"sort")}'; allowed: score, updated, created`,2);let J=_U(f(X,"kind"));if(!J.ok)return j4("usage.invalid",`unknown --kind '${J.bad}'; allowed: ${K9.join(", ")}`,2);let U=IU(f(X,"layer"));if(!U.ok)return j4("usage.invalid",`invalid --layer '${f(X,"layer")}'; format: L1 or L1..L3`,2);let K=oT(f(X,"fields")),W=K.length>0?K:[...a70];for(let M of W)if(Q3[M]===void 0)return j4("usage.invalid",`unknown field '${M}'; allowed: ${Object.keys(Q3).join(", ")}`,2);let V,G=f(X,"since");if(G!==void 0){let M=P$(G);if(M===void 0)return j4("usage.invalid",`invalid --since '${G}'`,2);V=Date.now()-M}let H,N=f(X,"until");if(N!==void 0){let M=P$(N);if(M===void 0)return j4("usage.invalid",`invalid --until '${N}'`,2);H=Date.now()-M}let Q=t(X,"limit"),L=Q!==void 0&&Number.isFinite(Q)&&Q>0?Math.min(Math.floor(Q),100):GS,B=t(X,"offset"),T=B!==void 0&&Number.isFinite(B)&&B>0?Math.floor(B):0,q=oT(f(X,"tag")),j=oT(f(X,"acl")),O=f(X,"author"),A=t(X,"embed-timeout"),R=A!==void 0&&Number.isFinite(A)&&A>=0?Math.floor(A):PU(),D=await kU(X,$,{text:Z,limit:L,offset:T,mode:Y,fullFields:!0,embedTimeoutMs:R,knobs:VS.map((M)=>M.name),filters:{...J.kinds.length>0?{kinds:J.kinds}:{},...q.length>0?{tags:q}:{},...j.length>0?{acl:j}:{},...O!==void 0?{author:O}:{},...U.min!==void 0?{layerMin:U.min}:{},...U.max!==void 0?{layerMax:U.max}:{},...V!==void 0?{since:V}:{},...H!==void 0?{until:H}:{}}});if(!D.ok)return D.failure;let F=D.outcome,P=[...F.rows];if(z==="updated")P.sort((M,E)=>E.updated_at-M.updated_at);else if(z==="created")P.sort((M,E)=>(E.created_at??0)-(M.created_at??0));return{ok:!0,data:{query:Z,rows:P,fields:W,full:X.flags.full===!0,shown:P.length,total:F.total,offset:T,pool_exhausted:F.poolExhausted,deduped:F.deduped,mode:F.modeLabel,mode_used:F.mode_used,tiers:F.tiers,why:X.flags.why===!0?RU(F.mode_used):void 0,took_ms:F.took_ms,partial:F.partial,omitted:F.omitted,cursor:F.cursor,budget_timed_out:F.budgetTimedOut},meta:{took_ms:F.took_ms,mode:F.modeLabel,mode_used:F.mode_used,sort:z,offset:T,partial:F.partial,omitted:F.omitted,...F.cursor!==void 0?{cursor:F.cursor}:{},budget_timed_out:F.budgetTimedOut}}},renderHuman:e70}}var GS=20,a70,Q3,s70,VS,HS;var NS=v(()=>{V0();j0();EU();a70=["id","kind","updated","acl","title"],Q3={id:($)=>$.id,score:($)=>$.confidence===void 0?"\xB7":$.confidence.toFixed(2),rank:($)=>String($.rank),kind:($)=>$.type,layer:($)=>`L${$.layer}`,tier:($)=>$.tier,updated:($)=>d0($.updated_at),created:($)=>$.created_at!==void 0?d0($.created_at):"",acl:($)=>$.acl??"",author:($)=>$.author??"",status:($)=>$.status??"",tags:($)=>($.tags??[]).join(","),anchors:($)=>($.anchors??[]).join(" "),sources:($)=>$.sources.join("+"),title:($)=>$.title,excerpt:($)=>$.excerpt},s70=Object.keys(Q3),VS=[{name:"kind",value:"string",list:!0,description:`comma-separated kinds: ${K9.join(",")}`},{name:"tag",value:"string",list:!0,description:"comma-separated tags (any match)"},{name:"author",value:"string",description:"actor that recorded the node"},{name:"acl",value:"string",list:!0,description:"comma-separated acl modes"},{name:"layer",value:"string",description:"L0..L3 or a range like L1..L3"},{name:"since",value:"string",description:"updated within, e.g. 30d, 12h"},{name:"until",value:"string",description:"updated no later than, e.g. 1d"},{name:"sort",value:"string",description:"score (default) | updated | created"},{name:"fields",value:"string",description:`columns: ${Object.keys(Q3).join(",")}`},{name:"limit",value:"number",description:`page size (default ${GS})`},{name:"offset",value:"number",description:"skip N rows"},{name:"full",description:"print title, excerpt and anchors per row instead of a table"},{name:"mode",value:"string",description:"hybrid (default) | vec | bm25"},{name:"why",description:"print why each retrieval branch was or was not used"},{name:"embed-timeout",value:"number",description:"ms to wait for the embedder to warm up (default 0 = skip the vector branch)"}];HS={openStore:$0.openStore,...MU}});var OS={};s(OS,{createReindexCommand:()=>j40,WATCH_POLL_MS:()=>qS,WATCH_DEBOUNCE_MS:()=>TS,REINDEX_LEASE_MS:()=>FS,REINDEX_BATCH_SIZE:()=>eT,F32_CACHE_LIMIT:()=>tT});import{createHash as X40}from"crypto";import{appendFileSync as Z40,watch as Y40}from"fs";import{dirname as z40,join as J40,resolve as U40}from"path";function sT($,X,Z){let Y=$[X];if(Y===void 0||Y.trim().length===0)return Z;let z=Number(Y);return Number.isFinite(z)&&z>=10?Math.floor(z):Z}function W40($){if($.MYC_EMBED_FAKE!=="1")return null;let X=$.MYC_EMBED_FAKE_LOG,Z=Math.max(0,Number($.MYC_EMBED_FAKE_DELAY_MS??0)||0);return{fingerprint:y2(K40),async embed(Y){if(Z>0)await new Promise((W)=>setTimeout(W,Z));if(X!==void 0&&X.length>0)Z40(X,`${JSON.stringify({text:Y})}
|
|
8067
|
+
`);let z=X40("sha256").update(Y).digest(),J=new Float32Array(aT),U=0;for(let W=0;W<aT;W++){let G=(z[(W*7+Math.floor(W/32))%32]^W*31&255)/255*2-1;J[W]=G,U+=G*G}let K=1/Math.sqrt(U>0?U:1);for(let W=0;W<aT;W++)J[W]=J[W]*K;return J},destroy:()=>Promise.resolve()}}async function V40(){try{let $=await Promise.resolve().then(() => (dX(),zY));if(!await $.isModelPresent($.DEFAULT_MODEL_ID))return{ok:!1,failure:{ok:!1,code:"precond.model_absent",msg:`model ${$.DEFAULT_MODEL_ID} is not downloaded`,exit:5,hint:"myc models fetch"}};let X=$.createLocalEmbedder({}),Z=await X.warmup();if(Z!=="ok")return await X.destroy(),{ok:!1,failure:{ok:!1,code:"embed.warmup_failed",msg:`embedder is in state ${Z} \u2014 indexing cancelled`,exit:5}};return{ok:!0,embedder:{fingerprint:X.fingerprint,embed:async(Y)=>(await X.embed(Y,"passage")).vec,destroy:()=>X.destroy()}}}catch($){return{ok:!1,failure:{ok:!1,code:"embed.load_failed",msg:`embedder failed to load: ${$ instanceof Error?$.message:String($)}`,exit:1}}}}function kK($){let X=($.title??"").trim().replace(/[.\u2026]+$/u,"").trim(),Z=($.body??$.excerpt??"").trim();if(X.length===0)return Z;if(Z.length===0)return X;if(Z.startsWith(X))return Z;return`${X}
|
|
8068
|
+
${Z}`}function G40($){let X=0;for(let z=0;z<$.length;z++)X=Math.max(X,Math.abs($[z]));let Z=X>0?X:1,Y=new Int8Array($.length);for(let z=0;z<$.length;z++)Y[z]=Math.max(-127,Math.min(127,Math.round(127*$[z]/Z)));return Buffer.from(Y.buffer,Y.byteOffset,Y.byteLength)}function LS($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}function jS($){return $.query(a0.metaTableExists).get()!==null}function BS($,X){let Z=$.query(a0.eligible).all(),Y=new Set($.query(a0.vecRowids).all().map((W)=>Number(W.r))),z=new Map;if(jS($))for(let W of $.query(a0.metaAll).all())z.set(W.id,W.h);let J=0,U=0,K=Z.filter((W)=>W.deleted_at===null&&W.head_id===null&&W.status!=="superseded"&&W.layer>=1&&kK(W).length>0&&(!Y.has(W.rowid)||z.get(W.id)!==W.content_hash));if(J=K.length,X&&K.length>0){$.exec("BEGIN IMMEDIATE");try{for(let W of K)if(f0.enqueue($,"embed",{entityId:W.id,scope:W.scope,payload:{reason:Y.has(W.rowid)?"changed":"missing"}}).inserted)U++;$.exec("COMMIT")}catch(W){throw $.exec("ROLLBACK"),W}}return{candidates:J,enqueued:U}}function H40($){try{let X=JSON.parse($.payload);return typeof X==="object"&&X!==null?X:{}}catch{return{}}}function Q40($){return $.f32===!0||$.reason==="rerank_miss"}async function N40($,X,Z){let Y=Z.entity_id;if(Y===null)return{kind:"complete",job:Z};let z=$.query(a0.nodeById).get(Y);if(z===null)return{kind:"complete",job:Z};if(!(!(z.deleted_at!==null||z.status==="superseded")&&z.head_id===null&&z.layer>=1&&kK(z).length>0))return{kind:"cleanup",job:Z,node:z};let K=jS($)?$.query("SELECT content_hash AS h FROM vec_embed_meta WHERE node_id = ?1").get(z.id)?.h:void 0,V=$.query(a0.hasVec).get(z.rowid)!==null&&K===z.content_hash,G=H40(Z),H=$.query(a0.f32Get).get(z.id),N=!V,Q=Q40(G)&&H===null;if(!N&&!Q)return{kind:"complete",job:Z};let L=Q||N&&H!==null?$.query(a0.donorF32).get(z.content_hash,z.id):null,B=L===null?null:Buffer.from(L.f32.buffer,L.f32.byteOffset,L.f32.byteLength);if(!N){if(B!==null)return{kind:"write",job:Z,node:z,int8:null,f32:B,via:"donor"};let O=await X.embed(kK(z));if(O===null)return{kind:"fail",job:Z,error:"embedder returned no vector"};return{kind:"write",job:Z,node:z,int8:null,f32:LS(O),via:"embed"}}let T=$.query(a0.donorVec).get(z.content_hash,z.id);if(T!==null&&!(Q&&B===null))return{kind:"write",job:Z,node:z,int8:Buffer.from(T.embedding.buffer,T.embedding.byteOffset,T.embedding.byteLength),f32:B,via:"donor"};let q=await X.embed(kK(z));if(q===null)return{kind:"fail",job:Z,error:"embedder returned no vector"};let j=Q||H!==null?LS(q):null;return{kind:"write",job:Z,node:z,int8:G40(q),f32:j,via:"embed"}}function L40($,X,Z,Y){let z=$.prepare(a0.vecDelete),J=$.prepare(a0.vecInsert),U=$.prepare(a0.metaUpsert),K=$.prepare(a0.metaDelete),W=$.prepare(a0.f32Upsert),V=$.prepare(a0.f32Delete);$.exec("BEGIN IMMEDIATE");try{for(let H of Z)switch(H.kind){case"complete":f0.complete($,H.job.id,X);break;case"cleanup":z.run(H.node.rowid),K.run(H.node.id),V.run(H.node.id),f0.complete($,H.job.id,X);break;case"fail":f0.fail($,H.job.id,H.error,{holder:X});break;case"write":if(H.int8!==null)z.run(H.node.rowid),J.run(H.node.rowid,H.node.scope,H.node.layer,H.node.kind,H.int8),U.run(H.node.id,H.node.content_hash,Y);if(H.f32!==null)W.run(H.node.id,H.f32,Y);f0.complete($,H.job.id,X);break}let G=Number($.query(a0.f32Count).get().n);if(G>tT)$.query(a0.f32Evict).run(G-tT);$.exec("COMMIT")}catch(G){throw $.exec("ROLLBACK"),G}}async function B40($,X,Z){let Y={claimed:0,embedded:0,copied:0,skipped:0,cleaned:0,failed:0,batches:0},z=0;for(;;){let J=f0.claim($,["embed"],Z.holder,{leaseMs:Z.leaseMs,limit:Z.batchSize});if(J.length===0){let K=$.query(a0.earliestLease).get(Date.now()).t;if(K===null||z>2*Z.leaseMs)break;let W=Math.max(0,Number(K)-Date.now())+50;if(z+=W,await new Promise((V)=>setTimeout(V,W)),J=f0.claim($,["embed"],Z.holder,{leaseMs:Z.leaseMs,limit:Z.batchSize}),J.length===0)continue}z=0,Y.claimed+=J.length;let U=[];for(let K of J)U.push(await N40($,X,K));L40($,Z.holder,U,Date.now()),Y.batches++;for(let K of U)if(K.kind==="write")if(K.via==="embed")Y.embedded++;else Y.copied++;else if(K.kind==="complete")Y.skipped++;else if(K.kind==="cleanup")Y.cleaned++;else if(K.kind==="fail")Y.failed++}return Y}async function T40($,X,Z,Y){let z,J=!1,U=!1,K=async()=>{if(J){U=!0;return}J=!0;try{await Y()}finally{if(J=!1,U)U=!1,W()}},W=()=>{if(z!==void 0)clearTimeout(z);z=setTimeout(()=>void K(),X)},V=Y40(z40($),()=>W()),G=setInterval(()=>void K(),Z);try{await new Promise((H)=>{process.once("SIGTERM",H),process.once("SIGINT",H)})}finally{if(V.close(),clearInterval(G),z!==void 0)clearTimeout(z)}}function rT($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,...Y!==void 0?{hint:Y}:{}}}function q40($){let X=U40($.globals.directory??process.cwd());return $.globals.db??J40(X,".myc","myc.db")}function j40($=$0){return{name:"reindex",summary:"index the corpus via the shared jobs queue: batches of 50, checkpoints, content-hash skip",flags:F40,help:"Turns corpus indexing into the `embed` job class of the shared jobs queue (S7): a scan enqueues nodes whose vector is missing or whose text changed, then batches of "+"50 are taken via jobs.claim and committed per batch \u2014 a killed run resumes from the "+"last checkpoint instead of the beginning. Nodes whose content hash is unchanged are never re-embedded, and a node whose text matches an already-indexed node (any branch) reuses that vector. The embed_fingerprint check is mandatory: a mismatch is a refusal "+"(exit 5), not a warning \u2014 full space rebuilds stay with scripts/reindex-vectors.ts --force. "+"--watch keeps the worker alive, re-draining 2s after each write to the db.",handler:async(X)=>{let Z=performance.now(),Y=await $.openStore(X,H7);if(!Y.ok)return Y.failure;let z=Y.handle;try{if(!z.vec0)return rT("precond.vec0_unavailable",`vec0 is not loaded \u2014 the vector index is unavailable (${z.vec0Reason??"no reason given"})`,3,"myc doctor");let J=z.driver.database;try{J.query(a0.vecCount).get()}catch{return rT("precond.vec_schema","the vector schema was never applied: no nodes_vec",5,"myc doctor")}let U=W40(process.env),K;if(U!==null)K=U;else{let W=await V40();if(!W.ok)return W.failure;K=W.embedder}try{let W=J.query(a0.fpGet).get()?.value,V=W5(W,K.fingerprint);if(!V.compatible)return rT("embed.fingerprint_mismatch",V.mismatch??"the vector space fingerprint does not match",5,"full rebuild: bun run scripts/reindex-vectors.ts --force");if(K0(X,"dry-run"))return{ok:!0,data:{dry_run:!0,candidates:BS(J,!1).candidates,fingerprint:f$(K.fingerprint)}};let H=sT(process.env,"MYC_REINDEX_LEASE_MS",FS),N=t(X,"batch"),Q=N!==void 0&&Number.isFinite(N)&&N>0?Math.floor(N):eT,L=`reindex-${process.pid}`,B={scans:0,enqueued:0,claimed:0,embedded:0,copied:0,skipped:0,cleaned:0,failed:0,batches:0},T=async()=>{let j=BS(J,!0),O=await B40(J,K,{batchSize:Q,leaseMs:H,holder:L});B.scans++,B.enqueued+=j.enqueued,B.claimed+=O.claimed,B.embedded+=O.embedded,B.copied+=O.copied,B.skipped+=O.skipped,B.cleaned+=O.cleaned,B.failed+=O.failed,B.batches+=O.batches};if(await T(),J.prepare(a0.fpSet).run(f$(K.fingerprint)),K0(X,"watch")){let j=sT(process.env,"MYC_REINDEX_WATCH_DEBOUNCE_MS",TS),O=sT(process.env,"MYC_REINDEX_WATCH_POLL_MS",qS);await T40(q40(X),j,O,T)}let q=Number(J.query(a0.vecCount).get().n);return{ok:!0,data:{...B,vectors:q,fingerprint:f$(K.fingerprint),took_ms:Math.round(performance.now()-Z)},...B.failed>0?{meta:{degraded:[`embedder refusals: ${B.failed}`]}}:{}}}finally{await K.destroy()}}finally{z.close()}}}}var eT=50,TS=2000,qS=30000,FS=60000,tT=1e4,aT=384,K40="local:onnx:fake-embed:384:l2",a0,F40;var CS=v(()=>{o();n0();G5();V0();j0();a0={metaTableExists:"SELECT name FROM sqlite_master WHERE type='table' AND name='vec_embed_meta'",fpGet:"SELECT value FROM myc_meta WHERE key = 'embed_fingerprint'",fpSet:`INSERT INTO myc_meta (key, value) VALUES ('embed_fingerprint', ?1)
|
|
8069
8069
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,eligible:`SELECT rowid, id, scope, layer, kind, title, excerpt, body, content_hash,
|
|
8070
8070
|
deleted_at, head_id, status
|
|
8071
8071
|
FROM nodes
|
|
@@ -8092,48 +8092,48 @@ ${Z}`}function J40($){let X=0;for(let z=0;z<$.length;z++)X=Math.max(X,Math.abs($
|
|
|
8092
8092
|
WHERE n2.content_hash = ?1 AND n2.id <> ?2
|
|
8093
8093
|
AND n2.deleted_at IS NULL${I0("follow","n2")} AND n2.status <> 'superseded'
|
|
8094
8094
|
LIMIT 1`,earliestLease:`SELECT min(lease_expires) AS t FROM jobs
|
|
8095
|
-
WHERE kind = 'embed' AND lease_expires > ?1 AND attempts < max_attempts`,vecCount:"SELECT count(*) AS n FROM nodes_vec"};
|
|
8096
|
-
`);break}catch{z=null}X.set(Z,z)}if(z===null)return;let J=z[Y-1];if(J===void 0)return;let U=J.trim();return U.length>140?`${U.slice(0,139)}\u2026`:U},files:()=>[...X.values()].filter((Z)=>Z!==null).length}}function
|
|
8095
|
+
WHERE kind = 'embed' AND lease_expires > ?1 AND attempts < max_attempts`,vecCount:"SELECT count(*) AS n FROM nodes_vec"};F40=[{name:"batch",value:"number",description:`jobs per claim/checkpoint (default ${eT})`},{name:"dry-run",description:"count what would be enqueued and done, write nothing"},{name:"watch",description:"keep running: re-drain 2s after each db write"}]});var PS={};s(PS,{createCallersCommand:()=>_40,REF_KINDS:()=>p5});import{readFileSync as O40}from"fs";import{join as C40}from"path";function l5($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function P40($){if($===void 0||$.trim().length===0)return 1;let X=$.trim().toLowerCase();if(X==="all")return Number.POSITIVE_INFINITY;let Z=Number(X);if(!Number.isFinite(Z)||!Number.isInteger(Z)||Z<1)return"bad";return Z}function M40($,X){if($===void 0||$.trim().length===0)return X==="out"?[...D40]:[...p5];if($.trim().toLowerCase()==="all")return[...p5];let Z=$.split(",").map((Y)=>Y.trim().toLowerCase()).filter((Y)=>Y.length>0);if(Z.length===0||Z.some((Y)=>!p5.includes(Y)))return"bad";return Z}function R40($){let X=new Map;return{line(Z,Y){let z=X.get(Z);if(z===void 0){z=null;for(let K of $)try{z=O40(C40(K,Z),"utf8").split(`
|
|
8096
|
+
`);break}catch{z=null}X.set(Z,z)}if(z===null)return;let J=z[Y-1];if(J===void 0)return;let U=J.trim();return U.length>140?`${U.slice(0,139)}\u2026`:U},files:()=>[...X.values()].filter((Z)=>Z!==null).length}}function _40($=$0){return{name:"callers",summary:"who calls a symbol (and, with --direction out, what it calls): callers <name>",help:"Reads code_ref_sites built by `myc code index`: every syntactic occurrence of <name> in a USE position, grouped by the symbol that owns the line. A group is one edge of the call "+"graph \u2014 caller, file, and every line inside it \u2014 not a list of matches. `--direction out` "+"walks the other way (what this symbol references, closures included); `--depth N` or `--depth all` walks transitively and prints what that cost and how far it leaked. The graph is BY NAME: same-named methods of different classes are one node, import aliases are "+"not resolved, and a local variable shadowing a global is not told apart from it \u2014 a name "+"with more than one definition is reported as ambiguous instead of being picked at random. Comments and string literals are not in the index at all, so a mention that lives only in "+"a comment will not be found here \u2014 and neither is the HEAD of a generic type: `Foo<T>` in "+"type position records `T` and loses `Foo` (measured: zero type refs to Promise/Map/Record in this repo against 504 textual `Promise<`).",flags:A40,handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0||Y.trim().length===0)return l5("usage.invalid","usage: myc callers <name>",2);let z=Y.trim(),J=(f(X,"direction")??"in").trim().toLowerCase();if(J!=="in"&&J!=="out")return l5("usage.invalid",`--direction takes in or out, not "${J}"`,2);let U=P40(f(X,"depth"));if(U==="bad")return l5("usage.invalid",`--depth takes an integer from 1, or all, not "${f(X,"depth")}"`,2);let K=M40(f(X,"kind"),J);if(K==="bad")return l5("usage.invalid",`--kind takes all, or comma-separated kinds from: ${p5.join(", ")}`,2);let W=X.flags.limit,V=typeof W==="number"&&W>0?Math.floor(W):AS,G=X.flags["max-nodes"],H=typeof G==="number"&&G>0?Math.floor(G):5000,N=await $.openStore(X);if(!N.ok)return N.failure;let Q=N.handle;try{let L=await f6(Q,f(X,"repo"),X.globals.directory??process.cwd()),{repoId:B,view:T}=L,{ambiguousNames:q,callGraph:j,definedNames:O,indexScope:A,refsIndexed:R,symbolDefs:D}=await Promise.resolve().then(() => (v6(),E6)),F=Q.driver.database,P=A(F,T);if(L.missing||P.files===0)return await y6(Q,L,"nothing to build the call graph from","the code index of this repo (workspace root) is not built: code_files has zero rows \u2014 nothing to build the call graph from");S6(X,L,"source lines are read from the main copy, so they match the line numbers");let _=R(F,T);if(_===0)return l5("precond.no_refs",`the index has zero references across ${Y0(P.files,"file")} and ${Y0(P.defs,"symbol")}: `+'the code_ref_sites table is empty \u2014 "nobody calls it" and "references were never built" look the same here',5,"myc code index");let M=D(F,T,z);if(J==="out"&&M.length===0)return l5("notfound.symbol",`symbol ${z} is not in code_defs: its body is not in this repo, so there is nothing to ask what it calls (scanned ${Y0(P.files,"file")}, ${Y0(P.defs,"symbol")})`,3,"myc callers "+z+" # who calls it: works for an external name too");let E=j(F,T,z,{direction:J,depth:U,kinds:K,maxNodes:H}),b=[];if(E.nodes.length>0&&U>1){let c=q(F,T);for(let l of E.nodes){let m=c.get(l);if(m!==void 0)b.push({name:l,defs:m})}b.sort((l,m)=>m.defs-l.defs||l.name.localeCompare(m.name))}let k=!K0(X,"no-source"),y=R40([L.repoRoot]),g=E.edges.slice(0,V),{fileDefs:S}=await Promise.resolve().then(() => (v6(),E6)),w=new Map,h=new Set;for(let c of g){if(c.callerStart===0||h.has(c.path))continue;h.add(c.path);for(let l of S(F,T,c.path))w.set(`${c.path}:${l.spanStart}:${l.name}`,l.spanEnd)}let u=J==="out"?O(F,T):null,d=g.map((c)=>({depth:c.depth,caller:c.caller,callee:c.callee,path:c.path,caller_start:c.callerStart,caller_end:w.get(`${c.path}:${c.callerStart}:${c.caller}`)??0,callee_defined:u===null?void 0:u.has(c.callee),sites:c.sites.map((l)=>{let m=k?y.line(c.path,l.line):void 0;return m===void 0?{line:l.line,kind:l.kind}:{line:l.line,kind:l.kind,text:m}})})),a={};for(let c of E.edges)for(let l of c.sites)a[l.kind]=(a[l.kind]??0)+1;let e={repo:B,name:z,direction:J,depth:U===Number.POSITIVE_INFINITY?"all":U,kinds:K,defs:M.map((c)=>({path:c.path,kind:c.kind,lang:c.lang,span_start:c.spanStart,span_end:c.spanEnd,exported:c.exported})),ambiguous:M.length>1,edges:d,shown:d.length,total_edges:E.edges.length,nodes:E.nodes.length,levels:[...E.levels],sites:E.sites,kind_counts:a,ambiguous_nodes:b.slice(0,10),stopped:E.stopped,searched:{files:P.files,defs:P.defs,refs:_},queries:E.queries,files_read:y.files(),took_ms:0};e.took_ms=Math.round(performance.now()-Z);let r=j7(L,L.repoRoot);if(r!==void 0)e.source=r;if(E.edges.length===0&&M.length===0)return l5("notfound.symbol",`name ${z} is in neither definitions nor references: scanned ${Y0(P.files,"file")}, ${Y0(P.defs,"symbol")}, ${Y0(_,"reference")}`,3,"the index may be behind: myc code index");if(M.length===0)X.warn("callers.external",`${z} has no definition in this repo \u2014 the name is external (an import) or declared `+"in a language without symbol parsing; only occurrences are shown");if(e.ambiguous)X.warn("callers.ambiguous",`name ${z} is defined ${M.length} times (${M.map((c)=>`${c.path}:${c.spanStart}`).slice(0,4).join(", ")}${M.length>4?", \u2026":""}) \u2014 references by name are NOT split between them`);if(E.stopped!==null)X.warn("callers.truncated",`the walk stopped at the cap of ${E.stopped.limit} symbols \u2014 the radius is INCOMPLETE`);return{ok:!0,data:e,meta:{took_ms:e.took_ms,count:e.total_edges}}}finally{Q.close()}},renderHuman:(X)=>{let Z=X,Y=[],z=Z.defs.length>0?Z.defs.map((W)=>`${Z.name} \xB7 ${W.kind} \xB7 ${W.path}:${W.span_start}-${W.span_end}${W.exported?" \xB7 exported":""}`).join(`
|
|
8097
8097
|
`):`${Z.name} \xB7 no definition in the index (external name)`;Y.push(z);let J=Z.kinds.length===p5.length?"all kinds":Z.kinds.join(",");Y.push(`${Z.direction==="in"?"callers":"callees"} \xB7 depth ${Z.depth} \xB7 ${J}`,"");let U=0;for(let W of Z.edges){if(Z.depth!==1&&W.depth!==U){let L=Z.levels[W.depth-1]??0;Y.push(`step ${W.depth} (+${Y0(L,"symbol")})`),U=W.depth}let V=W.caller.length>0?W.caller:"top level",G=W.caller_start>0?`${W.path}:${W.caller_start}${W.caller_end>0?`-${W.caller_end}`:""}`:W.path,H=Z.direction==="in"?"\u2190":"\u2192",N=Z.direction==="in"?V:W.callee,Q=Z.direction==="out"?`${W.callee_defined===!1?" [external]":""}${V!==Z.name&&V.length>0?` (in ${V})`:""}`:"";Y.push(`${H} ${N} ${G}${Q}`);for(let L of W.sites)Y.push(` ${String(L.line).padStart(5)} ${L.kind.padEnd(6)} ${L.text??""}`.trimEnd())}if(Z.edges.length===0)Y.push(Z.direction==="in"?"nobody calls it: the index has no occurrences of this name":"this symbol references nothing: its span has no occurrences");if(Z.shown<Z.total_edges)Y.push("",`shown ${Z.shown} of ${Z.total_edges} groups \u2014 the rest is past --limit`);let K=Object.entries(Z.kind_counts).sort((W,V)=>V[1]-W[1]).map(([W,V])=>`${W} ${V}`).join(", ");if(Y.push("",`symbols ${Z.nodes}, groups ${Z.total_edges}, occurrences ${Z.sites}${K.length>0?` [${K}]`:""}`),Z.levels.length>1)Y.push(`growth per step ${Z.levels.join(" \u2192 ")}`);if(Z.ambiguous_nodes.length>0)Y.push("the walk went through ambiguous names: "+Z.ambiguous_nodes.map((W)=>`${W.name} (${W.defs})`).join(", ")+" \u2014 their subtrees are merged");if(Z.stopped!==null)Y.push(`WALK CUT OFF: cap of ${Z.stopped.limit} symbols, the radius is incomplete`);return Y.push(`scanned ${Y0(Z.searched.files,"file")}, ${Y0(Z.searched.defs,"symbol")}, ${Y0(Z.searched.refs,"reference")}; queries ${Z.queries}, files read ${Z.files_read} ${Z.took_ms} ms`),Y.push(...O7(Z.source)),`${Y.join(`
|
|
8098
8098
|
`)}
|
|
8099
|
-
`}}}var p5,AS=40,
|
|
8099
|
+
`}}}var p5,AS=40,A40,D40;var DS=v(()=>{V0();j0();PY();p5=["call","new","type","import","read","prop"],A40=[{name:"direction",value:"string",description:"in \u2014 who calls the symbol (default), out \u2014 what the symbol calls"},{name:"depth",value:"string",description:"hops to walk: 1 (default), N, or all (the full blast radius)"},{name:"kind",value:"string",list:!0,description:`ref kinds to keep, comma-separated or all: ${p5.join(",")} (default: every kind for --direction in, call,new for out)`},{name:"limit",value:"number",description:`groups to print (default ${AS})`},{name:"no-source",description:"do not read files for the source line of each site"},{name:"max-nodes",value:"number",description:"stop the walk after this many symbols (default 5000) and say so"},{name:"repo",value:"string",description:"repo id to search (default: derived from cwd)"}];D40=["call","new"]});var RS={};s(RS,{createSkeletonCommand:()=>k40});function MS($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function k40($=$0){return{name:"skeleton",summary:"the API of one file: every declaration, its signature and span, in a fraction of the bytes",help:"Reads code_defs built by `myc code index` and the file itself, and prints one line per declaration: nesting, kind, span and the signature cut at the start of the body. Answers 'what does this file offer' without spending the context of reading it, and says by how much: file bytes, skeleton bytes and their ratio are in the output. Spans come from the "+"index, signatures from disk \u2014 if the two disagree (the file changed after indexing) that "+`is reported, not smoothed over. Only L1 languages (${U8}) have declarations; a file registered at L0 has a row in the index and no symbols, and says so. The body of an `+"interface or object type alias is NOT printed \u2014 a skeleton is signatures, and the span is "+"right there for whoever needs the fields.",flags:I40,handler:async(X)=>{let Z=performance.now(),Y=X.args[0];if(Y===void 0||Y.trim().length===0)return MS("usage.invalid","usage: myc skeleton <path>",2);let z=await $.openStore(X);if(!z.ok)return z.failure;let J=z.handle;try{let U=await f6(J,f(X,"repo"),X.globals.directory??process.cwd()),{repoId:K,view:W}=U,{fileSkeleton:V,indexScope:G}=await Promise.resolve().then(() => (v6(),E6)),H=J.driver.database,N=G(H,W);if(U.missing||N.files===0)return await y6(J,U,"nowhere to take a skeleton from","the code index of this repo (workspace root) is not built: code_files has zero rows \u2014 nowhere to take a skeleton from");S6(X,U,"signatures are read from the copy whose content the index saw");let Q=Y.trim().replace(/^\.\//,"").replaceAll("\\","/");if(H.query("SELECT lang FROM code_files WHERE repo_id = ?1 AND path = ?2").get(W.repoId,W.prefix+Q)===null)return MS("notfound.file",`file ${Q} is not in this repo's index: scanned ${Y0(N.files,"file")}`,3,"the path is relative to the repo root; the index may be behind: myc code index");let B=V(H,W,Q,U.fileRoot,U.fallbackRoot),T=U.fileRoot;if(B.stale&&U.fallbackRoot!==void 0){let F=V(H,W,Q,U.fallbackRoot);if(F.onDisk&&!F.stale)B=F,T=U.fallbackRoot,X.warn("skeleton.main_copy",`your worktree copy of ${Q} differs from what the index saw \u2014 shown: the declarations and `+`signatures of the MAIN copy ${U.fallbackRoot}, not of your file`)}let q=f(X,"kind"),j=q===void 0||q.trim().length===0?null:new Set(q.split(",").map((F)=>F.trim().toLowerCase()).filter((F)=>F.length>0)),O=X.flags.exported===!0,A=B.entries.filter((F)=>(j===null||j.has(F.kind))&&(!O||F.exported)),R={repo:K,path:B.path,lang:B.lang,entries:A.map((F)=>({name:F.name,kind:F.kind,span_start:F.spanStart,span_end:F.spanEnd,exported:F.exported,nesting:F.nesting,signature:F.signature})),hidden:B.entries.length-A.length,file_bytes:B.fileBytes,file_lines:B.fileLines,skeleton_bytes:B.skeletonBytes,cheaper:B.skeletonBytes>0?Math.round(B.fileBytes/B.skeletonBytes*10)/10:0,on_disk:B.onDisk,stale:B.stale,took_ms:0};R.took_ms=Math.round(performance.now()-Z);let D=j7(U,T);if(D!==void 0)R.source=D;if(!B.onDisk)X.warn("skeleton.gone",`file ${Q} is in the index but not on disk \u2014 no signatures, spans come from the index`);else if(B.stale)X.warn("skeleton.stale",`the content of ${Q} differs from the index: spans and signatures may point to the wrong place`);if(B.entries.length===0)X.warn("skeleton.no_defs",`no declarations found in ${Q} (${B.lang}): either an L0 language (the index holds only path and hash) or the file really is empty`);return{ok:!0,data:R,meta:{took_ms:R.took_ms,count:R.entries.length}}}finally{J.close()}},renderHuman:(X)=>{let Z=X,Y=[`${Z.path} ${Z.lang} ${Y0(Z.file_lines,"line")}, ${Z.file_bytes} B`];for(let z of Z.entries){let J=" ".repeat(z.nesting),U=`${z.span_start}-${z.span_end}`.padEnd(11);Y.push(`${U} ${J}${z.exported?"+":" "} ${z.signature.length>0?z.signature:`${z.kind} ${z.name}`}`)}if(Z.entries.length===0)Y.push("no declarations");if(Z.hidden>0)Y.push(`hidden by filter: ${Z.hidden}`);if(Z.stale)Y.push("WARNING: the file changed after indexing \u2014 spans may not match");return Y.push(`skeleton ${Z.skeleton_bytes} B vs file ${Z.file_bytes} B${Z.cheaper>0?` \u2014 ${Z.cheaper}\xD7 cheaper`:""} ${Z.took_ms} ms`),Y.push(...O7(Z.source)),`${Y.join(`
|
|
8100
8100
|
`)}
|
|
8101
|
-
`}}}var
|
|
8101
|
+
`}}}var I40;var _S=v(()=>{O6();V0();j0();PY();I40=[{name:"repo",value:"string",description:"repo id (default: derived from cwd)"},{name:"kind",value:"string",list:!0,description:"keep only these kinds, comma-separated"},{name:"exported",description:"only exported declarations \u2014 the API as others see it"}]});import{existsSync as Xq,mkdirSync as E40,readdirSync as kS,readFileSync as v40,renameSync as y40,rmSync as f40,statSync as $q,writeFileSync as IS}from"fs";import{join as D7}from"path";function g40($){try{return{data:Bun.zstdCompressSync(Buffer.from($,"utf8"),{level:S40}),ext:".jsonl.zst",how:"zstd"}}catch{return{data:$,ext:".jsonl",how:"none"}}}function ES($){let X=performance.now(),Z=D7($.mycDir,N3);if(!Xq(Z))E40(Z,{recursive:!0}),IS(D7(Z,".gitignore"),`# raw L0 episodes are private (D22) and stay out of git
|
|
8102
8102
|
*
|
|
8103
8103
|
`);let Y=n$($.handle.slug),z={v:1,id:Y,...$.header},J=`${JSON.stringify(z)}
|
|
8104
|
-
${$.redacted}`,{data:U,ext:K,how:W}=
|
|
8105
|
-
`)),z=JSON.parse(Y);return z.v===1&&typeof z.id==="string"?z:null}catch{return null}}function yS($,X){let Z=D7($,N3);if(!Xq(Z))return{adopted:[],unreadable:0};let Y=[],z=0,J;try{J=kS(Z).filter((U)=>!U.startsWith(".")).map((U)=>{try{return{name:U,mtime:$q(D7(Z,U)).mtimeMs}}catch{return{name:U,mtime:0}}}).sort((U,K)=>K.mtime-U.mtime).slice(0,
|
|
8106
|
-
`}var gS=v(()=>{j0()});function bS($,X=8){try{return $.driver.all(
|
|
8104
|
+
${$.redacted}`,{data:U,ext:K,how:W}=g40(J),V=D7(Z,`${Y}${K}`),G=D7(Z,`.${Y}${K}.tmp`);IS(G,U),y40(G,V);let H=typeof U==="string"?Buffer.byteLength(U,"utf8"):U.byteLength;return $.handle.store.createNode({id:Y,kind:"session",layer:0,acl:"private",scope:$.handle.scope,title:`episode ${Y} \xB7 ${$.header.reason} \xB7 ${$.header.agent}`,actor:$.handle.actor,attrs:{...$.attrs,episode_path:`${N3}/${Y}${K}`,episode_bytes:H,compression:W}}),{id:Y,path:V,storedBytes:H,compression:W,tookMs:performance.now()-X}}function vS($,X=3600000,Z=Date.now()){let Y=D7($,N3);if(!Xq(Y))return 0;let z=0;try{for(let J of kS(Y)){if(!J.startsWith(".")||!J.endsWith(".tmp"))continue;let U=D7(Y,J);try{if(Z-$q(U).mtimeMs<X)continue;f40(U,{force:!0}),z++}catch{}}}catch{return z}return z}function w40($){try{let X=v40($),Z=$.endsWith(".zst")?new TextDecoder().decode(Bun.zstdDecompressSync(X)):X.toString("utf8"),Y=Z.slice(0,Z.indexOf(`
|
|
8105
|
+
`)),z=JSON.parse(Y);return z.v===1&&typeof z.id==="string"?z:null}catch{return null}}function yS($,X){let Z=D7($,N3);if(!Xq(Z))return{adopted:[],unreadable:0};let Y=[],z=0,J;try{J=kS(Z).filter((U)=>!U.startsWith(".")).map((U)=>{try{return{name:U,mtime:$q(D7(Z,U)).mtimeMs}}catch{return{name:U,mtime:0}}}).sort((U,K)=>K.mtime-U.mtime).slice(0,b40)}catch{return{adopted:[],unreadable:0}}for(let{name:U}of J){let K=U.split(".")[0];if(K===void 0||K.length===0)continue;try{if(X.store.getNode(K,!0)!==void 0)continue}catch{continue}let W=D7(Z,U),V=w40(W);if(V===null||V.id!==K){z++;continue}try{X.store.createNode({id:K,kind:"session",layer:0,acl:"private",scope:X.scope,title:`episode ${K} \xB7 ${V.reason} \xB7 ${V.agent}`,actor:X.actor,attrs:{reason:V.reason,agent:V.agent,raw_bytes:V.raw_bytes,secrets_masked:V.secrets_masked,episode_path:`${N3}/${U}`,episode_bytes:$q(W).size,compression:U.endsWith(".zst")?"zstd":"none",adopted:!0}}),Y.push(K)}catch{z++}}return{adopted:Y,unreadable:z}}var N3="episodes",S40=1,b40=50;var fS=v(()=>{o()});function Zq($){return f($,"hook-output")==="json"}function SS($,X,Z){return`${JSON.stringify({hookSpecificOutput:{hookEventName:$,additionalContext:X},warn:Z.items.map((Y)=>({code:Y.code,msg:Y.msg}))})}
|
|
8106
|
+
`}var gS=v(()=>{j0()});function bS($,X=8){try{return $.driver.all(x40.rescue_active,[X])}catch{return[]}}function h40($){return $>=1024?`${Math.round($/1024)} KB`:`${$} B`}function m40($){return`P${$}`}function u40($){let X=$.assignee.length>0?` @${$.assignee}`:"",Z=$.status==="in_progress"?"":` [${$.status}]`;return`${$.id} ${m40($.priority)} ${$.title}${X}${Z}`}function l40($){return $.count>1?`${$.path} (${$.count}\xD7)`:$.path}function p40($,X,Z){if(X.length===0)return"";let Y=Z>0?[`\u2026${Z} more`]:[],z=[...X,...Y],J=" ".repeat(Yq),U=$.join===`
|
|
8107
8107
|
`?z.map((K,W)=>W===0?K:`${J}${K}`).join(`
|
|
8108
|
-
`):z.join(" \xB7 ");return`${$.label.padEnd(Yq)}${U}`}function wS($,X){let Z=$.secretsMasked>0?`, ${$.secretsMasked} secret${$.secretsMasked===1?"":"s"} masked`:"",Y=["# myc: context is being compacted \u2014 here is what must not be lost",`episode ${$.episodeId} saved (${
|
|
8109
|
-
`),z=[`myc show ${$.episodeId}`,...$.tasks[0]?[`myc show ${$.tasks[0].id}`]:[],"myc ready --claim"],J=[{label:"ACTIVE",items:$.tasks.map(
|
|
8110
|
-
`},{label:"FILES",items:$.files.map(
|
|
8108
|
+
`):z.join(" \xB7 ");return`${$.label.padEnd(Yq)}${U}`}function wS($,X){let Z=$.secretsMasked>0?`, ${$.secretsMasked} secret${$.secretsMasked===1?"":"s"} masked`:"",Y=["# myc: context is being compacted \u2014 here is what must not be lost",`episode ${$.episodeId} saved (${h40($.rawBytes)}${Z})`,...($.degraded??[]).map((L)=>`WARN ${L}`),""].join(`
|
|
8109
|
+
`),z=[`myc show ${$.episodeId}`,...$.tasks[0]?[`myc show ${$.tasks[0].id}`]:[],"myc ready --claim"],J=[{label:"ACTIVE",items:$.tasks.map(u40),join:`
|
|
8110
|
+
`},{label:"FILES",items:$.files.map(l40),join:" \xB7 "},{label:"DECIDED",items:[...$.mycCalls,...$.decisions],join:`
|
|
8111
8111
|
`},{label:"OPEN",items:$.open,join:`
|
|
8112
|
-
`},{label:"NEXT",items:z,join:" \xB7 "}],U=["DECIDED","ACTIVE","OPEN","NEXT","FILES"],K=new Map(J.map((L)=>[L.label,[]])),W={},V=$.budget-Y.length-24;for(let L of U){let B=J.find((j)=>j.label===L);if(!B)continue;let T=K.get(L),q=0;for(let j of B.items){let O=j.length+Yq+1;if(O<=V)T.push(j),V-=O;else q++}if(q>0)W[L]=q}let G=J.map((L)=>
|
|
8112
|
+
`},{label:"NEXT",items:z,join:" \xB7 "}],U=["DECIDED","ACTIVE","OPEN","NEXT","FILES"],K=new Map(J.map((L)=>[L.label,[]])),W={},V=$.budget-Y.length-24;for(let L of U){let B=J.find((j)=>j.label===L);if(!B)continue;let T=K.get(L),q=0;for(let j of B.items){let O=j.length+Yq+1;if(O<=V)T.push(j),V-=O;else q++}if(q>0)W[L]=q}let G=J.map((L)=>p40(L,K.get(L.label),W[L.label]??0)).filter((L)=>L.length>0),H=`${Y}${G.join(`
|
|
8113
8113
|
`)}`,N=H.length,Q=X===void 0?"":`
|
|
8114
8114
|
${N} chars \xB7 ${Math.round(X)} ms`;return{text:`${H}${Q}
|
|
8115
|
-
`,chars:N,dropped:W}}var
|
|
8115
|
+
`,chars:N,dropped:W}}var x40,Yq=9;var xS=v(()=>{o();x40=Z0({rescue_active:{name:"rescue_active",sql:`SELECT id, title, status, priority, assignee
|
|
8116
8116
|
FROM nodes
|
|
8117
8117
|
WHERE kind = 'task' AND deleted_at IS NULL
|
|
8118
8118
|
AND status IN ('in_progress', 'blocked', 'open')
|
|
8119
8119
|
ORDER BY CASE status WHEN 'in_progress' THEN 0 WHEN 'blocked' THEN 1 ELSE 2 END,
|
|
8120
8120
|
priority ASC, updated_at DESC
|
|
8121
|
-
LIMIT ?1`,params:["limit"]}})});function
|
|
8121
|
+
LIMIT ?1`,params:["limit"]}})});function c40($){return $==="user"||$==="assistant"||$==="tool"||$==="system"?$:"system"}function i40($,X){if(typeof X!=="string")return;let Z=X.trim();if(Z.length===0||Z.length>512)return;$.push(Z)}function mS($,X){if($===null||typeof $!=="object")return;let Z=$;for(let z of["file_path","filePath","path","notebook_path","notebookPath"])i40(X,Z[z]);let Y=Z.edits;if(Array.isArray(Y))for(let z of Y)mS(z,X)}function L3($,X){if(typeof $==="string")return{all:$,prose:$};if(!Array.isArray($))return{all:"",prose:""};let Z=[],Y=[];for(let z of $){if(typeof z==="string"){Z.push(z),Y.push(z);continue}if(z===null||typeof z!=="object")continue;let J=z,U=J.type;if((U==="text"||U==="input_text"||U==="output_text")&&typeof J.text==="string")Z.push(J.text),Y.push(J.text);else if(U==="tool_use"){let K=typeof J.name==="string"?J.name:"tool";if(n40.test(K))mS(J.input,X);let W=J.input?.command;Z.push(typeof W==="string"?`$ ${W}`:`[${K}]`)}else if(U==="tool_result"){let K=J.content;if(typeof K==="string")Z.push(K);else if(Array.isArray(K))Z.push(L3(K,X).all)}}return{all:Z.join(`
|
|
8122
8122
|
`),prose:Y.join(`
|
|
8123
|
-
`)}}function
|
|
8124
|
-
`)){if(z.length>=5000)break;let H=G.trim();if(H.length===0)continue;if(W++,H.startsWith("{"))try{let Q=JSON.parse(H);if(Q!==null&&typeof Q==="object"){K++;let L=
|
|
8125
|
-
`)){if(K.length<8)continue;if(K.startsWith("$ "))continue;if(
|
|
8123
|
+
`)}}function d40($,X){if(X.cwd===void 0&&typeof $.cwd==="string")X.cwd=$.cwd;if(X.sessionId===void 0&&typeof $.sessionId==="string")X.sessionId=$.sessionId;if(X.sessionId===void 0&&typeof $.session_id==="string")X.sessionId=$.session_id;let Z=$.message;if(X.model===void 0&&Z!==null&&typeof Z==="object"){let Y=Z.model;if(typeof Y==="string")X.model=Y}}function o40($){let X=$.payload;if(X===null||typeof X!=="object"||Array.isArray(X))return $;return X}function r40($,X){let Z=$.type;if(typeof Z!=="string")return null;if(a40.test(Z)){let Y=typeof $.name==="string"?$.name:"tool",z=$.input??$.arguments,J=z;if(typeof z==="string")try{J=JSON.parse(z)}catch{J=void 0}let U={type:"tool_use",name:Y,...J!==void 0?{input:J}:{}},K=L3([U],X),W=typeof z==="string"&&z.length>0?`[${Y}] ${z}`:K.all;if(W.trim().length===0)return null;return{role:"assistant",text:W.slice(0,20000),prose:""}}if(s40.test(Z)){let Y=$.output,z=typeof Y==="string"?Y:L3(Y,X).all;if(z.trim().length===0)return null;return{role:"tool",text:z.slice(0,20000),prose:""}}return null}function t40($,X){let Z=r40($,X);if(Z!==null)return Z;let Y=$.message,z=Y!==null&&typeof Y==="object"?Y:null,J=z!==null?L3(z.content,X):L3($.content??$.text,X);if(J.all.trim().length===0)return null;return{role:c40(z?.role??$.role??$.type),text:J.all.slice(0,20000),prose:J.prose.slice(0,20000)}}function uS($){let X=Buffer.byteLength($,"utf8"),Z=X>4194304?$.slice(0,4194304):$,Y=Z.length<$.length,z=[],J=[],U={},K=0,W=0;for(let G of Z.split(`
|
|
8124
|
+
`)){if(z.length>=5000)break;let H=G.trim();if(H.length===0)continue;if(W++,H.startsWith("{"))try{let Q=JSON.parse(H);if(Q!==null&&typeof Q==="object"){K++;let L=o40(Q);d40(L,U);let B=t40(L,J);if(B)z.push(B);continue}}catch{}let N=H.slice(0,20000);z.push({role:"system",text:N,prose:N})}return{format:W>0&&K*2>=W?"jsonl":"text",turns:z,toolFiles:J,bytes:X,truncated:Y,...U.cwd!==void 0?{cwd:U.cwd}:{},...U.sessionId!==void 0?{sessionId:U.sessionId}:{},...U.model!==void 0?{model:U.model}:{}}}function K50($){let X=$.replace(/^[\s>#*\-\u2022\u00B7]+/,"").replace(/\s+/g," ").trim();return X.length>hS?`${X.slice(0,hS-1)}\u2026`:X}function W50($){return $.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}class EK{limit;#$=new Set;#X=[];constructor($){this.limit=$}add($){if(this.#X.length>=this.limit)return;let X=K50($);if(X.length<8)return;let Z=W50(X);if(Z.length===0||this.#$.has(Z))return;this.#$.add(Z),this.#X.push(X)}get items(){return this.#X}}function lS($){let X=new EK(Y50),Z=new EK(z50),Y=new EK(U50),z=new Map;for(let U of $.toolFiles)z.set(U,(z.get(U)??0)+1);for(let U of $.turns){for(let K of U.text.matchAll(X50))if(K[1]!==void 0)Y.add(K[1]);for(let K of U.text.matchAll(Z50)){let W=K[1];if(W!==void 0)z.set(W,(z.get(W)??0)+1)}if(U.role!=="assistant"&&U.role!=="user")continue;for(let K of U.prose.split(`
|
|
8125
|
+
`)){if(K.length<8)continue;if(K.startsWith("$ "))continue;if(e40.test(K))X.add(K);else if($50.test(K))Z.add(K)}}let J=[...z.entries()].sort((U,K)=>K[1]-U[1]||U[0].localeCompare(K[0])).slice(0,J50).map(([U,K])=>({path:U,count:K}));return{decisions:X.items,open:Z.items,mycCalls:Y.items,files:J}}var n40,a40,s40,e40,$50,X50,Z50,Y50=40,z50=20,J50=30,U50=40,hS=240;var pS=v(()=>{n40=/^(?:write|edit|multiedit|notebookedit|patch|apply_patch|str_replace\w*)$/i;a40=/^(?:custom_tool_call|function_call|local_shell_call)$/,s40=/^(?:custom_tool_call_output|function_call_output|local_shell_call_output)$/;e40=/(?<![\p{L}\p{N}])(?:\u0440\u0435\u0448(?:\u0438\u043B\u0438|\u0435\u043D\u043E|\u0438\u043B|\u0430\u0435\u043C)|\u0432\u044B\u0431\u0440\u0430\u043B[\u0438\u0430]|\u0432\u044B\u0431\u0438\u0440\u0430\u0435\u043C|\u0431\u0435\u0440\u0451\u043C|\u0431\u0435\u0440\u0435\u043C|\u043E\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u043B\u0438\u0441\u044C \u043D\u0430|\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C|\u043E\u0442\u043A\u0430\u0437\u0430\u043B(?:\u0438\u0441\u044C|\u0441\u044F)|\u043E\u0442\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C\u0441\u044F|\u043D\u0435 \u0442\u044F\u043D\u0435\u043C|\u0434\u043E\u0433\u043E\u0432\u043E\u0440\u0438\u043B\u0438\u0441\u044C|\u043F\u043E\u0442\u043E\u043C\u0443 \u0447\u0442\u043E|decided|we chose|chose|going with|settled on)(?![\p{L}\p{N}])/iu,$50=/(?<![\p{L}\p{N}])(?:TODO|FIXME|\u043D\u0435 \u043F\u0440\u043E\u0433\u043D\u0430\u043D|\u043D\u0435 \u043F\u0440\u043E\u0433\u043E\u043D\u044F\u043B\u0438|\u043D\u0435 \u0441\u0434\u0435\u043B\u0430\u043D|\u043D\u0435 \u0434\u043E\u0434\u0435\u043B\u0430\u043D|\u043E\u0441\u0442\u0430\u043B\u043E\u0441\u044C|\u043E\u0441\u0442\u0430\u0451\u0442\u0441\u044F|\u043E\u0441\u0442\u0430\u0435\u0442\u0441\u044F|\u043F\u0430\u0434\u0430\u0435\u0442|\u043D\u0435 \u0440\u0430\u0431\u043E\u0442\u0430\u0435\u0442|\u043D\u0430\u0434\u043E \u0435\u0449\u0451|\u043D\u0430\u0434\u043E \u0435\u0449\u0435|\u043E\u0442\u043A\u0440\u044B\u0442\u044B\u0439 \u0432\u043E\u043F\u0440\u043E\u0441|open question|still failing|blocked on)(?![\p{L}\p{N}])/iu,X50=/(?:^|\$\s|&&\s|;\s|\|\s)(myc\s+(?:remember|absorb|close|link|create|task|bug|epic|claim|update|dep)\s+[^\n`]{1,200})/gim,Z50=/^(?:\+\+\+|---)\s+[ab]\/(\S+)/gm});var dS={};s(dS,{realAbsorbDeps:()=>nS,episodeBudgetMs:()=>iS,createAbsorbSessionCommand:()=>O50,HOOK_TIMEOUT_MS:()=>zq,EPISODE_BUDGET_MS_PER_MB:()=>Uq,EPISODE_BUDGET_MS:()=>Jq});import{existsSync as V50,readFileSync as G50}from"fs";import{resolve as H50}from"path";function iS($){return Jq+Uq*$/1e6}function q50($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}async function F50($,X){let Z=$.flags["stdin-transcript"]===!0,Y=f($,"transcript");if(Z||Y==="-"||Y===void 0&&!process.stdin.isTTY)return{text:await X.readStdin(),origin:"stdin"};if(Y===void 0)return{text:"",origin:"none"};let z=H50(Y);if(!V50(z))return{text:"",origin:`missing:${z}`};try{return{text:G50(z,"utf8"),origin:z}}catch(J){return q50("io.read",`cannot read transcript ${z}: ${J instanceof Error?J.message:String(J)}`,1)}}function cS($,X,Z,Y,z,J){$.driver.run(B50.job_enqueue,[X,Z,$.scope,z,J,JSON.stringify(Y)])}function j50($,X,Z,Y,z){let J=0,U=0,K;for(let W of Z.slice(0,L50)){let V=W.length>120?`${W.slice(0,119)}\u2026`:W;try{let G=$.store.createNode({kind:"note",layer:2,acl:"private",salience:0,scope:$.scope,title:V,body:W.length>120?W:null,actor:$.actor,attrs:{[CX]:AX,extracted_by:"precompact",episode_id:X,agent:Y,...d4("session",z.length>0?z:h7(X))}});$.store.addEdge(G.id,"derived_from",X),J++}catch(G){let H=G instanceof Error?G.message:String(G);if(/UNIQUE constraint failed: nodes\.scope, nodes\.kind, nodes\.content_hash/.test(H))U++;else K??=H}}return{written:J,known:U,...K!==void 0?{error:K}:{}}}function O50($=nS){return{name:"absorb-session",summary:"save the session episode before context is compacted (pre-compact hook)",flags:T50,help:"Writes the raw episode first (L0, private, secrets masked), then builds the rescue packet, then queues distillation. The whole hook is bounded by --timeout; exceeding it skips later steps but never cancels the episode that is already on disk.",handler:async(X)=>{let Z=performance.now(),Y=t(X,"timeout")??zq,z=f(X,"reason")??"auto",J=f(X,"agent")??process.env.MYC_HOOK_AGENT??"unknown",U=t(X,"budget")??(z==="manual"?N50:Q50),K=z8(f(X,"session")),W=()=>performance.now()-Z>Y,V={},G=(F,P)=>{V[F]=Math.round((performance.now()-P)*100)/100},H=performance.now(),N=await F50(X,$);if("ok"in N&&N.ok===!1)return N;let{text:Q,origin:L}=N;if(G("read",H),L.startsWith("missing:"))X.warn("degraded.transcript",`the host named a transcript that does not exist: ${L.slice(8)}`);let B=K.length>0?"":MV(L),T=K.length>0?K:B,q=K.length>0?"host":T.length>0?"transcript":"episode",j=performance.now(),O=Q.length>0?SV(Q):{text:"",findings:[]};G("redact",j);let A=await $.openStore(X);if(!A.ok)return A.failure;let R=A.handle,D=R.mycDir;try{let F=null,P=0,_="none";if(Q.length>0)try{let c=ES({mycDir:D,handle:R,redacted:O.text,header:{reason:z,agent:J,created_at:Date.now(),raw_bytes:Buffer.byteLength(Q,"utf8"),secrets_masked:O.findings.length},attrs:{reason:z,agent:J,origin:L,raw_bytes:Buffer.byteLength(Q,"utf8"),secrets_masked:O.findings.length,...T.length>0?d4("session",T):{}}});F=c.id,P=c.storedBytes,_=c.compression,V.episode=Math.round(c.tookMs*100)/100;let l=iS(Buffer.byteLength(Q,"utf8"));if(c.tookMs>l)X.warn("degraded.budget",`raw episode written in ${c.tookMs.toFixed(1)} ms against a budget of ${l.toFixed(1)} ms (${Jq} ms + ${Uq} ms/MB for ${(Buffer.byteLength(Q,"utf8")/1e6).toFixed(1)} MB)`)}catch(c){X.warn("degraded.episode",`raw episode NOT written: ${c instanceof Error?c.message:String(c)}`)}else X.warn("degraded.transcript","empty transcript: no episode written, the packet was built from the graph");let M=performance.now(),E={decisions:[],open:[],mycCalls:[],files:[]},b=0,k=0,y=0,g=[];if(Q.length>0&&!W()){let c=uS(O.text);b=c.turns.length;let l=lS(c);if(E={decisions:[...l.decisions],open:[...l.open],mycCalls:[...l.mycCalls],files:[...l.files]},F!==null){try{R.store.updateNode(F,{attrs:{turns:b,transcript_format:c.format,decisions:E.decisions.length,files:E.files.length,...c.truncated?{parse_truncated:!0}:{}}})}catch{}if(X.flags["no-candidates"]!==!0&&!W()){let n=j50(R,F,E.decisions,J,T);if(k=n.written,y=n.known,n.error!==void 0)X.warn("degraded.candidates",`candidates only partly written: ${n.error}`)}let m=Date.now();try{if(cS(R,"distill",F,{reason:z,agent:J,candidates:k},4,m),g.push("distill"),E.files.length>0)cS(R,"anchor_check",F,{paths:E.files.map((n)=>n.path)},6,m),g.push("anchor_check")}catch(n){X.warn("degraded.queue",`background queue unavailable: ${n instanceof Error?n.message:String(n)}`)}}}else if(Q.length>0)X.warn("degraded.timeout",`budget of ${Y} ms spent before parsing: episode saved, atoms deferred`);G("extract",M);let S=performance.now(),w=bS(R),h=q==="episode"&&F!==null?`reach derived from the episode (${h7(F)}): no --session and no uuid in the transcript name; the next compaction of the same session will get a different key`:void 0,u=wS({episodeId:F??"\u2014",rawBytes:Buffer.byteLength(Q,"utf8"),secretsMasked:O.findings.length,decisions:E.decisions,open:E.open,files:E.files,mycCalls:E.mycCalls,tasks:w,budget:U,degraded:[...X.diagnostics.items.map((c)=>c.msg),...h!==void 0?[h]:[]]},performance.now()-Z);G("packet",S);let d=[];if(!W()){if(vS(D),d=yS(D,R).adopted,d.length>0)X.warn("degraded.adopted",`recovered ${d.length} episode${d.length===1?"":"s"} after the previous hook was cut off: ${d.join(", ")}`)}let a=Math.round((performance.now()-Z)*10)/10;jN(D,`${J}:pre-compact`,a,F===null?"empty":"ok");let e=T.length>0?T:F!==null?h7(F):"",r={episode:F,reason:z,agent:J,session:e,session_source:q,session_derived:K.length===0,raw_bytes:Buffer.byteLength(Q,"utf8"),stored_bytes:P,compression:_,secrets_masked:O.findings.length,turns:b,decisions:E.decisions.length,candidates:k,candidates_known:y,files:E.files.length,queue:g,adopted:d,packet:u.text,packet_chars:u.chars,dropped:u.dropped,stages:V,took_ms:a,budget_exceeded:a>Y};if(r.budget_exceeded)X.warn("degraded.timeout",`hook took ${a} ms against a budget of ${Y} ms`);return{ok:!0,data:r,meta:{took_ms:a,episode:F,stages:V}}}finally{R.close()}},machineStdout:(X)=>Zq(X),renderHuman:(X,Z)=>{let Y=X;return Zq(Z)?SS("PreCompact",Y.packet,Z.diagnostics):Y.packet}}}var zq=8000,Jq=12,Uq=2,Q50=1200,N50=2000,L50=20,B50,T50,nS;var oS=v(()=>{o();B4();K8();o();V0();j0();fS();LY();gS();xS();pS();B50=Z0({job_enqueue:{name:"job_enqueue",sql:`INSERT INTO jobs (kind, entity_id, scope, priority, run_after, payload, created_at)
|
|
8126
8126
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?5)
|
|
8127
|
-
ON CONFLICT DO NOTHING`,params:["kind","entity_id","scope","priority","now","payload"]}}),
|
|
8128
|
-
`;let Y=[`PENDING REVIEW ${X.total} \xB7 ${X.here} in this session's prime \xB7 ${X.other} from other sessions \xB7 ${Z}`],z=X.items.map((U)=>
|
|
8127
|
+
ON CONFLICT DO NOTHING`,params:["kind","entity_id","scope","priority","now","payload"]}}),T50=[{name:"transcript",value:"string",description:"transcript path, or - for stdin"},{name:"stdin-transcript",description:"read the transcript from stdin (same as --transcript -)"},{name:"reason",value:"string",description:"compact|auto|manual|stop (default auto)"},{name:"budget",value:"number",description:"rescue packet size in characters"},{name:"hook-output",value:"string",description:"json|text (default text)"},{name:"timeout",value:"number",description:`whole-hook budget in ms (default ${zq})`},{name:"agent",value:"string",description:`host that fired the hook: ${o0.join("|")}`},{name:"no-candidates",description:"do not write pending_review candidates"},{name:"session",value:"string",description:"host session id (payload.session_id): owns the memory written here, S58"}];nS={openStore:$0.openStore,readStdin:()=>new Response(Bun.stdin.stream()).text()}});var Jg={};s(Jg,{reviewQueries:()=>tS,realReviewDeps:()=>zg,listCandidates:()=>eS,createReviewCommand:()=>k50});function O4($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function C50($){try{let X=JSON.parse($);return typeof X==="object"&&X!==null&&!Array.isArray(X)?X:{}}catch{return{}}}function sS($,X){let Z=$[X];return typeof Z==="string"?Z:""}function eS($,X){let Y=$.driver.all(tS.review_awaiting,[$.scope]).map((z)=>{let J=C50(z.attrs),U=C8(J),K=A$(J);return{id:z.id,layer:z.layer,title:z.title,created_at:z.created_at,reach:U.reach,session:U.session,here:pZ(U,X),repo:K.repo,repo_state:K.state,agent:sS(J,"agent"),episode:sS(J,"episode_id")}});return[...Y.filter((z)=>z.here),...Y.filter((z)=>!z.here)]}function A50($,X){if($.reach==="project")return"project";if($.reach==="unknown")return"no reach";if(X.length>0&&$.session===X)return"this session";if($.session.startsWith(P50))return`episode \u2026${$.session.slice(-Kq)}`;return`session ${$.session.slice(0,Kq)}`}function Wq($){let X=$.replace(/\s+/g," ").trim();return X.length<=aS?X:`${X.slice(0,aS-1)}\u2026`}function D50($){let X=$,Z=X.session.length>0?`session ${X.session.slice(0,Kq)}`:"session not specified";if(X.total===0)return`nothing awaits review \xB7 ${Z} \xB7 compaction candidates appear after a context compaction \xB7 ${X.took_ms} ms
|
|
8128
|
+
`;let Y=[`PENDING REVIEW ${X.total} \xB7 ${X.here} in this session's prime \xB7 ${X.other} from other sessions \xB7 ${Z}`],z=X.items.map((U)=>A50(U,X.session)),J=Math.max(...z.map((U)=>U.length));if(X.items.forEach((U,K)=>{let W=U.repo_state==="repo"?` repo ${U.repo}`:"";Y.push(`${U.id} L${U.layer} ${d0(U.created_at)} ${z[K].padEnd(J)}${W} ${Wq(U.title)}`)}),X.shown<X.listed)Y.push(`\u2026 ${X.listed-X.shown} more (--limit)`);return Y.push("confirm `myc review confirm <id>` \u2014 becomes knowledge: recall and prime return it",'reject `myc review reject <id> --reason "<why>"` \u2014 retracted, out of this list'),Y.push(`${X.took_ms} ms`),`${Y.join(`
|
|
8129
8129
|
`)}
|
|
8130
|
-
`}function $g($){return $.args.flatMap((X)=>X.split(",")).map((X)=>X.trim()).filter((X)=>X.length>0)}function Xg($,X){let Z=$[X];return typeof Z==="number"?Z:0}function Vq($,X){let Z=$[X];return typeof Z==="string"?Z:""}function Zg($,X,Z){let Y=[],z=new Set;for(let J of X){let U=R0($,J);if(!U.ok)return{ok:!1,failure:U.failure};let K=U.node;if(z.has(K.id))continue;z.add(K.id);let W=K.attrs[CX]===kz;if(!A8(K.attrs)&&!W)return{ok:!1,failure:O4("precond.not_candidate",`${K.id} is not a compaction candidate: nothing to review`,5,"myc review")};let V=l7(K.attrs,K.status);if(Z==="confirm"){if(W){Y.push({node:K,already:!0});continue}if(!V)return{ok:!1,failure:K.status===s4?O4("precond.rejected",`${K.id} was rejected (status ${K.status}): confirming it takes lifting the rejection first \u2014 `+"it then returns to the review list",5,`myc update ${K.id} --status active`):O4("precond.rejected",`${K.id} is out of review (status ${K.status}): its current version is the one to read`,5,`myc show ${K.id}`)};Y.push({node:K,already:!1})}else{if(W)return{ok:!1,failure:O4("precond.confirmed",`${K.id} is already confirmed knowledge, not a candidate: withdrawing knowledge is a retraction`,5,`myc update ${K.id} --status ${s4}`)};Y.push({node:K,already:!V})}}return{ok:!0,plan:Y}}function
|
|
8130
|
+
`}function $g($){return $.args.flatMap((X)=>X.split(",")).map((X)=>X.trim()).filter((X)=>X.length>0)}function Xg($,X){let Z=$[X];return typeof Z==="number"?Z:0}function Vq($,X){let Z=$[X];return typeof Z==="string"?Z:""}function Zg($,X,Z){let Y=[],z=new Set;for(let J of X){let U=R0($,J);if(!U.ok)return{ok:!1,failure:U.failure};let K=U.node;if(z.has(K.id))continue;z.add(K.id);let W=K.attrs[CX]===kz;if(!A8(K.attrs)&&!W)return{ok:!1,failure:O4("precond.not_candidate",`${K.id} is not a compaction candidate: nothing to review`,5,"myc review")};let V=l7(K.attrs,K.status);if(Z==="confirm"){if(W){Y.push({node:K,already:!0});continue}if(!V)return{ok:!1,failure:K.status===s4?O4("precond.rejected",`${K.id} was rejected (status ${K.status}): confirming it takes lifting the rejection first \u2014 `+"it then returns to the review list",5,`myc update ${K.id} --status active`):O4("precond.rejected",`${K.id} is out of review (status ${K.status}): its current version is the one to read`,5,`myc show ${K.id}`)};Y.push({node:K,already:!1})}else{if(W)return{ok:!1,failure:O4("precond.confirmed",`${K.id} is already confirmed knowledge, not a candidate: withdrawing knowledge is a retraction`,5,`myc update ${K.id} --status ${s4}`)};Y.push({node:K,already:!V})}}return{ok:!0,plan:Y}}function R50($,X){return X.map((Z)=>Z==="absorb"&&$.absorb_heuristic?"absorb(heuristic \u2014 chat-LLM off)":Z).join(", ")}function Yg($){let X=$,Z=X.items.map((Y)=>{switch(Y.outcome){case"confirmed":return`${Y.id} confirmed \xB7 recall and prime return it now \xB7 `+`queue ${Y.queue.length>0?R50(X,Y.queue):"\u2014"} \xB7 ${Wq(Y.title)}`;case"already_confirmed":return`${Y.id} already confirmed by ${Y.by||"?"} ${Y.at>0?d0(Y.at):""} \xB7 nothing to do`;case"rejected":return`${Y.id} rejected \xB7 status ${s4} \xB7 reason: ${Y.reason??""} \xB7 ${Wq(Y.title)}`;case"already_rejected":return`${Y.id} already rejected by ${Y.by||"?"} \xB7 nothing to do`}});return Z.push(`${X.changed} changed \xB7 ${X.took_ms} ms`),`${Z.join(`
|
|
8131
8131
|
`)}
|
|
8132
|
-
`}function
|
|
8132
|
+
`}function _50($){return{name:"confirm",summary:"confirm compaction candidates: knowledge from now on, embed and absorb queued",help:"Turns each candidate into knowledge the way a new note is born: attrs.state = confirmed with who and when, the salience of a new note, and embed + absorb jobs queued. Every id is checked before the first write; a rejected candidate is refused (lift the rejection first).",handler:async(X)=>{let Z=performance.now(),Y=$g(X);if(Y.length===0)return O4("usage.missing_arg","id required: myc review confirm <id>[,<id>\u2026]",2,"myc review");let z=await $.openStore(X);if(!z.ok)return z.failure;let J=z.handle;try{let U=Zg(J,Y,"confirm");if(!U.ok)return U.failure;let K=Date.now(),W=[],V=0;for(let H of U.plan){if(H.already){W.push({id:H.node.id,title:H.node.title,outcome:"already_confirmed",by:Vq(H.node.attrs,Ez),at:Xg(H.node.attrs,vz),queue:[]});continue}let N=_K(J,H.node,J.actor,K,!0);if(N.queueError!==void 0)X.warn("degraded.queue",`background queue unavailable for ${H.node.id}: ${N.queueError}`);V++,W.push({id:H.node.id,title:H.node.title,outcome:"confirmed",by:J.actor,at:K,queue:N.queue})}let G={action:"confirm",items:W,changed:V,absorb_heuristic:W.some((H)=>H.queue.includes("absorb"))&&!$.chatLlm(),took_ms:Math.round((performance.now()-Z)*10)/10};return{ok:!0,data:G,meta:{took_ms:G.took_ms,changed:V}}}catch(U){return C0(U)}finally{J.close()}},renderHuman:Yg}}function I50($){return{name:"reject",summary:"reject compaction candidates: retracted, with the reason in the node",help:"Marks each candidate retracted and records who, when and why in its attrs. Retracted nodes are out of recall, search, prime and this list; the candidate state stays, so lifting the rejection (`myc update <id> --status active`) returns it to review, not to the agent as knowledge.",flags:[{name:"reason",value:"string",description:"why this is not a decision (required)"}],handler:async(X)=>{let Z=performance.now(),Y=$g(X);if(Y.length===0)return O4("usage.missing_arg",'id required: myc review reject <id>[,<id>\u2026] --reason "<why>"',2,"myc review");let z=f(X,"reason")?.trim()??"";if(z.length===0)return O4("usage.missing_arg","--reason required: a rejection is a judgment, and whoever meets this candidate again reads why",2);let J=await $.openStore(X);if(!J.ok)return J.failure;let U=J.handle;try{let K=Zg(U,Y,"reject");if(!K.ok)return K.failure;let W=Date.now(),V=[],G=0;for(let N of K.plan){if(N.already){V.push({id:N.node.id,title:N.node.title,outcome:"already_rejected",by:Vq(N.node.attrs,iZ),at:Xg(N.node.attrs,nZ),queue:[],reason:Vq(N.node.attrs,m7)});continue}U.store.updateNode(N.node.id,{status:s4,attrs:fz(U.actor,W,z)}),G++,V.push({id:N.node.id,title:N.node.title,outcome:"rejected",by:U.actor,at:W,queue:[],reason:z})}let H={action:"reject",items:V,changed:G,absorb_heuristic:!1,took_ms:Math.round((performance.now()-Z)*10)/10};return{ok:!0,data:H,meta:{took_ms:H.took_ms,changed:G}}}catch(K){return C0(K)}finally{U.close()}},renderHuman:Yg}}function k50($=zg){return{name:"review",summary:"compaction candidates awaiting review: list them, confirm or reject",help:'The pre-compact hook writes "we decided / because" lines as candidates (state pending_review); recall, search, prime and MCP do not return them until they are confirmed. Lists every candidate '+"of the workspace with its session and repo reach \u2014 this session's first (they are the `pending "+"review hidden` of its prime footer); --this-session narrows to them. Confirm with `myc review confirm <id>`, reject with `myc review reject <id> --reason`.",flags:M50,subcommands:[_50($),I50($)],handler:async(X)=>{let Z=performance.now(),Y=t(X,"limit");if(Y!==void 0&&(!Number.isFinite(Y)||Y<1))return O4("usage.invalid",`--limit must be >= 1, got ${Y}`,2);let z=Math.floor(Y??rS),J=z8(f(X,"session")),U=await $.openStore(X);if(!U.ok)return U.failure;let K=U.handle;try{let W=eS(K,J),V=W.filter((Q)=>Q.here).length,G=K0(X,"this-session")?W.filter((Q)=>Q.here):W,H=G.slice(0,z),N={session:J,total:W.length,here:V,other:W.length-V,listed:G.length,shown:H.length,items:H,took_ms:Math.round((performance.now()-Z)*10)/10};return{ok:!0,data:N,meta:{took_ms:N.took_ms,total:N.total,here:V,session:J.length>0?J:null}}}finally{K.close()}},renderHuman:D50}}var Kq=8,rS=50,aS=100,tS,P50,M50,zg;var Ug=v(()=>{o();K8();V0();nT();j0();tS=Z0({review_awaiting:{name:"review_awaiting",sql:`SELECT id, layer, title, created_at, updated_at, attrs
|
|
8133
8133
|
FROM nodes INDEXED BY ix_nodes_kind_upd
|
|
8134
8134
|
WHERE nodes.scope = ?1 AND nodes.kind = 'note' AND nodes.deleted_at IS NULL${I0("follow","nodes")}
|
|
8135
8135
|
AND ${PX("nodes")}
|
|
8136
|
-
ORDER BY nodes.updated_at DESC`,params:["scope"]}});
|
|
8136
|
+
ORDER BY nodes.updated_at DESC`,params:["scope"]}});P50=h7("");M50=[{name:"this-session",description:"list: only candidates this session's prime counts (its `pending review hidden`)"},{name:"limit",value:"number",description:`list: rows to print (default ${rS}); counts cover all`},{name:"session",value:"string",description:"list: session identity for the reach marks (default $MYC_SESSION_ID/$CLAUDE_SESSION_ID)"}];zg={openStore:$0.openStore,chatLlm:()=>IK.chatLlm()}});var Gq;var Kg=v(()=>{Gq=[{version:1,name:"run-queue",sql:`
|
|
8137
8137
|
CREATE TABLE IF NOT EXISTS run_queue (
|
|
8138
8138
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
8139
8139
|
lane TEXT NOT NULL,
|
|
@@ -8155,11 +8155,11 @@ CREATE TABLE IF NOT EXISTS run_queue (
|
|
|
8155
8155
|
child_pid INTEGER
|
|
8156
8156
|
);
|
|
8157
8157
|
CREATE INDEX IF NOT EXISTS ix_run_queue_lane ON run_queue (lane, id);
|
|
8158
|
-
`}]});var Bg={};s(Bg,{withHeldLane:()=>Fq,tryGrant:()=>Bq,timingsFromEnv:()=>SK,ticketInput:()=>Lq,staleWindowMs:()=>Qg,slotsFor:()=>fK,slotsEnvName:()=>yK,setChild:()=>Tq,renew:()=>mK,release:()=>m9,reap:()=>B3,queueDbPath:()=>bK,pidAlive:()=>qq,openQueueIfExists:()=>Nq,openQueue:()=>wK,mintHolder:()=>xK,liveness:()=>lK,listLane:()=>uK,listAll:()=>Lg,isValidLane:()=>vK,heldLanes:()=>cK,heartbeatMs:()=>gK,getTicket:()=>
|
|
8158
|
+
`}]});var Bg={};s(Bg,{withHeldLane:()=>Fq,tryGrant:()=>Bq,timingsFromEnv:()=>SK,ticketInput:()=>Lq,staleWindowMs:()=>Qg,slotsFor:()=>fK,slotsEnvName:()=>yK,setChild:()=>Tq,renew:()=>mK,release:()=>m9,reap:()=>B3,queueDbPath:()=>bK,pidAlive:()=>qq,openQueueIfExists:()=>Nq,openQueue:()=>wK,mintHolder:()=>xK,liveness:()=>lK,listLane:()=>uK,listAll:()=>Lg,isValidLane:()=>vK,heldLanes:()=>cK,heartbeatMs:()=>gK,getTicket:()=>a50,enqueue:()=>hK,StaleWatch:()=>pK,QUEUE_SCHEMA_VERSION:()=>h9,HELD_ENV:()=>u9,DEFAULT_SLOTS:()=>Hq,DEFAULT_POLL_MS:()=>Hg,DEFAULT_LEASE_MS:()=>Gg,DEFAULT_LANE:()=>c5});import{Database as E50}from"bun:sqlite";import{existsSync as v50,mkdirSync as y50}from"fs";import{hostname as Vg}from"os";import{dirname as f50,join as S50}from"path";function vK($){return g50.test($)}function yK($){return`MYC_${$.toUpperCase().replace(/-/g,"_")}_SLOTS`}function fK($,X){let Z=yK($),Y=(X[Z]??"").trim();if(Y==="")return{slots:Hq,source:"default"};let z=Number(Y);if(!Number.isInteger(z)||z<1||z>256)return{slots:Hq,source:"default",invalid:`${Z}=${Y}`};return{slots:z,source:"env"}}function Wg($,X,Z){let Y=Number(($[X]??"").trim());return($[X]??"").trim()!==""&&Number.isFinite(Y)&&Y>0?Y:Z}function SK($){return{leaseMs:Wg($,"MYC_RUN_LEASE_MS",Gg),pollMs:Wg($,"MYC_RUN_POLL_MS",Hg)}}function gK($){return Math.max(10,Math.floor($/6))}function Qg($){return Math.max(20,Math.floor($/3))}function bK($=e$()){return S50($,".myc","queue.db")}function Ng($){return $.query("PRAGMA user_version").get().user_version}function b50($){$.transaction(()=>{let X=Ng($);for(let Z of Gq)if(Z.version>X)$.exec(Z.sql);if(h9>X)$.exec(`PRAGMA user_version = ${h9}`)}).immediate()}function wK($,X={}){let Z=X.create!==!1;if(Z)y50(f50($),{recursive:!0});try{K6()}catch{}let Y=Date.now()+w50;for(let z=1;;z++){let J=new E50($,Z?{create:!0}:{readwrite:!0});try{J.exec("PRAGMA busy_timeout = 5000"),J.exec("PRAGMA journal_mode = WAL"),J.exec("PRAGMA synchronous = NORMAL");let U=Ng(J);if(U>h9)throw Error(`${$} was created by a newer myc (queue schema ${U}, this build knows ${h9}); upgrade myc or remove the file when no \`myc run\` is active`);if(U<h9)b50(J);return J}catch(U){if(J.close(),U.code!=="SQLITE_BUSY"||Date.now()>=Y)throw U;Bun.sleepSync(5+Math.random()*20*Math.min(z,5))}}}function Nq($){return v50($)?wK($,{create:!1}):void 0}function xK($,X){return`${$}:${X}:${Math.random().toString(36).slice(2,10)}`}function x50($,X){for(let Z of X){let Y=($[Z]??"").trim();if(/^\d+$/.test(Y)&&Number(Y)>0)return Number(Y)}return null}function Lq($,X,Z,Y){return{lane:$,argv:X,cwd:Z,pid:process.pid,host:Vg(),session:z8(void 0,Y),terminal:(Y.ORCA_TERMINAL_HANDLE??"").trim(),agentPid:x50(Y,["MYC_AGENT_PID","CLAUDE_PID"]),actor:(Y.MYC_ACTOR??"").trim()}}function hK($,X,Z,Y,z,J=Date.now()){return $.query(h50).get(J,z,o50,Z,X.lane,Y,X.pid,X.host,JSON.stringify(X.argv),X.cwd,X.session,X.terminal,X.agentPid,X.actor)}function Bq($,X,Z,Y,z=Date.now()){return $.query(m50).get(z,Y,X.id,X.holder,X.lane,Z)??void 0}function mK($,X,Z=Date.now()){return Number($.query(u50).run(Z,X.id,X.holder).changes)>0}function Tq($,X,Z){return Number($.query(p50).run(X.id,X.holder,Z).changes)>0}function m9($,X){return Number($.query(l50).run(X.id,X.holder).changes)>0}function a50($,X){return $.query(d50).get(X.id,X.holder)??void 0}function uK($,X){return $.query(i50).all(X)}function Lg($){return $.query(n50).all()}function qq($){if(!Number.isSafeInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch(X){return X.code==="EPERM"}}function lK($,X,Z,Y=qq){if($.host===Z&&!Y($.pid))return"dead";return $.lease_expires>X?"alive":"stale"}class pK{clock;#$=new Map;constructor($=()=>performance.now()){this.clock=$}expired($){let X=this.clock(),Z=this.#$.get($.id);if(Z===void 0||Z.leaseExpires!==$.lease_expires)return this.#$.set($.id,{leaseExpires:$.lease_expires,since:X}),!1;return X-Z.since>=Qg($.lease_ms)}retain($){for(let X of this.#$.keys())if(!$.has(X))this.#$.delete(X)}}function B3($,X,Z={}){let Y=Z.now??Date.now(),z=Z.host??Vg(),J=Z.probe??qq,U=X===void 0?Lg($):uK($,X),K=[],W=[],V=(G)=>G.host===z&&G.child_pid!==null&&J(G.child_pid);for(let G of U){if(G.id===Z.selfId){K.push(G);continue}let H=lK(G,Y,z,J);if(H==="dead"){if(m9($,G))W.push({...G,reason:"dead",orphan:V(G)});continue}if(H==="stale"&&Z.watch?.expired(G)===!0){if(Number($.query(c50).run(G.id,G.holder,G.lease_expires).changes)>0){W.push({...G,reason:"stale",orphan:V(G)});continue}}K.push(G)}return Z.watch?.retain(new Set(K.map((G)=>G.id))),{rows:K,removed:W}}function cK($){return new Set(($[u9]??"").split(",").map((X)=>X.trim()).filter((X)=>X.length>0))}function Fq($,X){let Z=cK($);return Z.add(X),{...$,[u9]:[...Z].join(",")}}var c5="heavy",Hq=1,Gg=30000,Hg=200,h9,g50,w50=5000,Qq=`(SELECT count(*) FROM run_queue AS q
|
|
8159
8159
|
WHERE q.lane = ?5 AND q.id <> ?3
|
|
8160
|
-
AND (q.state = 'running' OR q.id < ?3))`,
|
|
8160
|
+
AND (q.state = 'running' OR q.id < ?3))`,h50,m50,u50=`
|
|
8161
8161
|
UPDATE run_queue SET lease_expires = ?1 + lease_ms, renewed_at = ?1
|
|
8162
|
-
WHERE id = ?2 AND holder = ?3`,
|
|
8162
|
+
WHERE id = ?2 AND holder = ?3`,l50="DELETE FROM run_queue WHERE id = ?1 AND holder = ?2",p50="UPDATE run_queue SET child_pid = ?3 WHERE id = ?1 AND holder = ?2",c50="DELETE FROM run_queue WHERE id = ?1 AND holder = ?2 AND lease_expires = ?3",i50="SELECT * FROM run_queue WHERE lane = ?1 ORDER BY id",n50="SELECT * FROM run_queue ORDER BY lane, id",d50="SELECT * FROM run_queue WHERE id = ?1 AND holder = ?2",o50,u9="MYC_RUN_HELD";var iK=v(()=>{o();VZ();R8();Kg();h9=Gq.reduce(($,X)=>Math.max($,X.version),0),g50=/^[a-z][a-z0-9-]{0,31}$/;h50=`
|
|
8163
8163
|
INSERT INTO run_queue (lane, holder, pid, host, state, enqueued_at, started_at,
|
|
8164
8164
|
lease_ms, lease_expires, renewed_at, argv, cwd,
|
|
8165
8165
|
session, terminal, agent_pid, actor)
|
|
@@ -8168,13 +8168,13 @@ SELECT ?5, ?4, ?7, ?8,
|
|
|
8168
8168
|
?1,
|
|
8169
8169
|
CASE WHEN ${Qq} < ?6 THEN ?1 END,
|
|
8170
8170
|
?2, ?1 + ?2, ?1, ?9, ?10, ?11, ?12, ?13, ?14
|
|
8171
|
-
RETURNING *`,
|
|
8171
|
+
RETURNING *`,m50=`
|
|
8172
8172
|
UPDATE run_queue
|
|
8173
8173
|
SET state = 'running', started_at = ?1, lease_expires = ?1 + ?2, renewed_at = ?1
|
|
8174
8174
|
WHERE id = ?3 AND holder = ?4 AND state = 'waiting'
|
|
8175
8175
|
AND ${Qq} < ?6
|
|
8176
|
-
RETURNING *`,
|
|
8177
|
-
`)}async function Tg($,X,Z,Y,z){let J=performance.now(),U;try{U=Bun.spawn({cmd:[...$],cwd:X,env:Object.fromEntries(Object.entries(Z).filter((W)=>W[1]!==void 0)),stdio:["inherit","inherit","inherit"]})}catch(W){let V=W;return{exit:V.code==="EACCES"?126:127,signal:null,ranMs:performance.now()-J,spawnError:V.message}}if(Y.child=U,z?.(U.pid),Y.received!==null)try{U.kill(Y.received)}catch{}await U.exited,Y.child=null;let K=U.signalCode??null;return{exit:K!==null?128+Mg(K):U.exitCode??1,signal:K,ranMs:performance.now()-J}}function qg($,X,Z){let Y=l6($,60);if(X.spawnError!==void 0)return{ok:!1,code:X.exit===126?"run.not_executable":"run.not_found",msg:`cannot start '${Y}': ${X.spawnError}`,exit:X.exit};if(X.signal!==null)return{ok:!1,code:"run.signal",msg:`'${Y}' was killed by ${X.signal} after ${B8(X.ranMs)}`,exit:X.exit};if(X.exit!==0)return{ok:!1,code:"run.exit",msg:`'${Y}' exited with code ${X.exit} after ${B8(X.ranMs)}`,exit:X.exit};return{ok:!0,data:{...Z,exit:0,ran_ms:Math.round(X.ranMs)}}}async function
|
|
8176
|
+
RETURNING *`,o50=Number.MAX_SAFE_INTEGER});var Cq={};s(Cq,{parseWait:()=>Pg,fmtDuration:()=>B8,describeTicket:()=>Oq,createRunCommand:()=>KX0,createQueueCommand:()=>HX0,commandLine:()=>l6,callerEnv:()=>_g,DEFAULT_PROGRESS_MS:()=>Ag,DEFAULT_MAX_WAIT_MS:()=>Cg,BUN_DOTENV_FILES:()=>Rg});import{existsSync as jg}from"fs";import{constants as s50,homedir as r50,hostname as Og}from"os";import{join as t50,resolve as e50}from"path";function Pg($){let X=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec($.trim());if(X===null)return;let Z=Number(X[1]),Y=X[2]??"s";return Math.round(Z*(Y==="ms"?1:Y==="s"?1000:Y==="m"?60000:3600000))}function B8($){let X=Math.max(0,$);if(X<1000)return`${(X/1000).toFixed(1)}s`;let Z=Math.floor(X/1000);if(Z<60)return`${Z}s`;let Y=Math.floor(Z/60);if(Y<60)return Z%60===0?`${Y}m`:`${Y}m${String(Z%60).padStart(2,"0")}s`;return`${Math.floor(Y/60)}h${String(Y%60).padStart(2,"0")}m`}function p9($){let X=r50();return $===X||$.startsWith(`${X}/`)?`~${$.slice(X.length)}`:$}function XX0($,X){let Z=$.lastIndexOf("/");if(Z<0||$.endsWith("/"))return $;if(X===0)return $.slice(Z+1);return $.length>24&&!$.startsWith("-")?`\u2026/${$.slice(Z+1)}`:$}function l6($,X=80){let Z=$.map(XX0).map((Y)=>/^[\w@%+=:,./\u2026-]+$/.test(Y)?Y:`'${Y.replace(/'/g,"'\\''")}'`).join(" ");return Z.length>X?`${Z.slice(0,X-1)}\u2026`:Z}function jq($){try{let X=JSON.parse($.argv);return Array.isArray(X)?X.map(String):[$.argv]}catch{return[$.argv]}}function Oq($,X){let Z=[`'${l6(jq($),60)}' in ${p9($.cwd)}`];if($.session!=="")Z.push(`session ${$.session.slice(0,8)}`);if($.terminal!=="")Z.push(`orca ${$.terminal.slice(0,13)}`);return Z.push(`pid ${$.pid}`),Z.push($.state==="running"&&$.started_at!==null?`running ${B8(X-$.started_at)}`:`waiting ${B8(X-$.enqueued_at)}`),Z.join(", ")}class Dg{received=null;child=null;#$=null;#X=new Map;constructor(){for(let $ of $X0){let X=()=>this.#Z($);this.#X.set($,X),process.on($,X)}}#Z($){this.received??=$;let X=this.child;if(X!==null&&X.exitCode===null&&X.signalCode===null)try{X.kill($)}catch{}this.#$?.()}sleep($){return new Promise((X)=>{let Z=setTimeout(()=>{this.#$=null,X()},Math.max(1,$));this.#$=()=>{clearTimeout(Z),this.#$=null,X()}})}dispose(){for(let[$,X]of this.#X)process.off($,X);this.#X.clear()}}function Mg($){return s50.signals[$]??1}async function _g($={}){let X=$.env??process.env;if(($.execArgv??process.execArgv).includes("--no-env-file")||Bun.main.startsWith("/$bunfs/"))return{env:X,dotenv:[],dropped:[]};let Z=$.cwd??process.cwd(),Y=Rg.filter((J)=>jg(t50(Z,J)));if(Y.length===0)return{env:X,dotenv:Y,dropped:[]};let z=await ZX0(X);if(z===null)return{env:X,dotenv:Y,dropped:null};try{let J={},U=[];for(let[K,W]of Object.entries(X)){if(W===void 0)continue;if(z.has(K))J[K]=W;else U.push(K)}return{env:J,dotenv:Y,dropped:U.sort()}}finally{z.close()}}async function ZX0($){let X=process.platform==="darwin"?["/usr/lib/libSystem.B.dylib"]:process.platform==="linux"?["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`]:[],Z;try{Z=await import("bun:ffi")}catch{return null}for(let Y of X){let z=YX0(Z,Y);if(z===null)continue;let J=(W)=>z.symbols.getenv(Buffer.from(`${W}\x00`))!==null,U=`MYC_ENVIRON_CANARY_${process.pid}`;process.env[U]="1";let K=J(U);if(delete process.env[U],!K&&Object.keys($).some(J))return{has:J,close:()=>z.close()};return z.close(),null}return null}function YX0($,X){try{return $.dlopen(X,{getenv:{args:[$.FFIType.cstring],returns:$.FFIType.ptr}})}catch{return null}}function zX0($){let Z=`this myc process was started without Bun's --no-env-file, so Bun loaded ${`${$.dotenv.join(", ")} in ${p9(process.cwd())}`} into its own environment`,Y="start myc through its launcher (`myc`), or run bun with --no-env-file --config=/dev/null";if($.dropped===null)return`${Z}; here they cannot be told apart from the caller's variables, and the command gets them too \u2014 ${"start myc through its launcher (`myc`), or run bun with --no-env-file --config=/dev/null"}`;let z=$.dropped.length;if(z===0)return`${Z}; they changed nothing, and the command gets the caller's environment \u2014 ${"start myc through its launcher (`myc`), or run bun with --no-env-file --config=/dev/null"}`;let J=z>8?`${$.dropped.slice(0,8).join(", ")}, \u2026`:$.dropped.join(", ");return`${Z}; the command gets the caller's environment only \u2014 ${z} variable${z===1?"":"s"} the caller did not have ${z===1?"is":"are"} not passed: ${J} \u2014 ${"start myc through its launcher (`myc`), or run bun with --no-env-file --config=/dev/null"}`}function nK($,X){return{ok:!1,code:"usage.run",msg:$,exit:2,...X!==void 0?{hint:X}:{}}}function l9($){process.stderr.write(`myc run: ${$}
|
|
8177
|
+
`)}async function Tg($,X,Z,Y,z){let J=performance.now(),U;try{U=Bun.spawn({cmd:[...$],cwd:X,env:Object.fromEntries(Object.entries(Z).filter((W)=>W[1]!==void 0)),stdio:["inherit","inherit","inherit"]})}catch(W){let V=W;return{exit:V.code==="EACCES"?126:127,signal:null,ranMs:performance.now()-J,spawnError:V.message}}if(Y.child=U,z?.(U.pid),Y.received!==null)try{U.kill(Y.received)}catch{}await U.exited,Y.child=null;let K=U.signalCode??null;return{exit:K!==null?128+Mg(K):U.exitCode??1,signal:K,ranMs:performance.now()-J}}function qg($,X,Z){let Y=l6($,60);if(X.spawnError!==void 0)return{ok:!1,code:X.exit===126?"run.not_executable":"run.not_found",msg:`cannot start '${Y}': ${X.spawnError}`,exit:X.exit};if(X.signal!==null)return{ok:!1,code:"run.signal",msg:`'${Y}' was killed by ${X.signal} after ${B8(X.ranMs)}`,exit:X.exit};if(X.exit!==0)return{ok:!1,code:"run.exit",msg:`'${Y}' exited with code ${X.exit} after ${B8(X.ranMs)}`,exit:X.exit};return{ok:!0,data:{...Z,exit:0,ran_ms:Math.round(X.ranMs)}}}async function JX0($,X){let{leaseMs:Z,pollMs:Y}=SK(X.env),z=Og(),J=Lq(X.lane,X.argv,X.cwd,X.env),U=new pK,K=gK(Z),W=(L)=>{for(let B of L){if(!B.orphan)continue;l9(`the previous holder of the '${X.lane}' slot (pid ${B.pid}) is gone, but its command '${l6(jq(B),60)}' (pid ${B.child_pid}) is still running outside the queue`)}};W(B3($,X.lane,{host:z,watch:U}).removed);let V=hK($,J,xK(z,process.pid),X.slots,Z);if(V.state==="running")return{kind:"slot",ticket:V,waitedMs:0,queued:!1};let G=performance.now(),H=Date.now(),N=G,Q=!1;for(;;){let L=performance.now()-G;if(X.relay.received!==null)return m9($,V),{kind:"signal",signal:X.relay.received,waitedMs:L};let B=Date.now(),{rows:T,removed:q}=B3($,X.lane,{now:B,host:z,watch:U,selfId:V.id});W(q);let j=Bq($,V,X.slots,Z,B);if(j!==void 0){let O=performance.now()-G;if(Q)l9(`slot acquired after ${B8(O)}; starting '${l6(X.argv,60)}'`);return{kind:"slot",ticket:j,waitedMs:O,queued:!0}}if(!T.some((O)=>O.id===V.id)){if(l9("this process was stalled past its lease and lost its place; re-queued at the tail"),V=hK($,J,xK(z,process.pid),X.slots,Z,B),V.state==="running")return{kind:"slot",ticket:V,waitedMs:L,queued:!0};H=B}else if(B-H>=K)mK($,V,B),H=B;if(L>=X.maxWaitMs){let O=uK($,X.lane).filter((A)=>A.id!==V.id&&(A.state==="running"||A.id<V.id));return m9($,V),{kind:"timeout",waitedMs:L,ahead:O}}if(performance.now()>=N){let O=T.filter((D)=>D.state==="running"),A=T.filter((D)=>D.state==="waiting"&&D.id<V.id).length,R=O.map((D)=>Oq(D,B)).join("; ");l9(`waiting for a '${X.lane}' slot (${O.length}/${X.slots} busy, ${A} waiting ahead), waited ${B8(L)} of max ${B8(X.maxWaitMs)}`+(R!==""?` \u2014 held by ${R}`:"")),Q=!0,N=performance.now()+X.progressMs}await X.relay.sleep(Math.min(Y,Math.max(1,X.maxWaitMs-L)))}}async function UX0($){let X=$.args;if(X.length===0)return nK("no command to run","myc run [--lane heavy] [--max-wait 5m] -- <command> [args...]");let Z=$.flags.lane,Y=typeof Z==="string"?Z.trim():c5;if(!vK(Y))return nK(`bad lane '${Y}'`,"a lane is a lowercase name: letters, digits, '-', up to 32 chars");let z=$.flags["max-wait"],J=typeof z==="string"?Pg(z):Cg;if(J===void 0)return nK(`bad --max-wait '${String(z)}'`,"a duration: 90s, 5m, 1h, 500ms; a bare number is seconds; 0 = do not wait");let U=e50($.globals.directory??process.cwd());if(!jg(U))return{ok:!1,code:"notfound.dir",msg:`directory does not exist: ${U}`,exit:3};let K=await _g(),W=K.env;if(K.dotenv.length>0)$.warn("run.dotenv",zX0(K));let V=fK(Y,W);if(V.invalid!==void 0)$.warn("run.slots_invalid",`${V.invalid} is not a whole number 1..256 \u2014 using ${V.slots} slot`);let G=Number((W.MYC_RUN_PROGRESS_MS??"").trim()),H=Number.isFinite(G)&&G>0?G:Ag,N=new Dg;try{if(cK(W).has(Y)){let B=await Tg(X,U,W,N);return qg(X,B,{lane:Y,command:l6(X),ticket:null,slots:V.slots,queued:!1,waited_ms:0,reentrant:!0})}let Q=bK(),L;try{L=wK(Q)}catch(B){return{ok:!1,code:"run.queue_unavailable",msg:`the queue at ${Q} cannot be opened: ${B instanceof Error?B.message:String(B)}`,hint:"the command was NOT started; run it directly, or fix or remove the queue file when no `myc run` is active",exit:1}}try{let B=await JX0(L,{lane:Y,argv:X,cwd:U,env:W,slots:V.slots,maxWaitMs:J,progressMs:H,relay:N});if(B.kind==="signal")return{ok:!1,code:"run.interrupted",msg:`${B.signal} while waiting for a '${Y}' slot (waited ${B8(B.waitedMs)}); the command was not started`,exit:128+Mg(B.signal)};if(B.kind==="timeout"){let F=Date.now(),P=B.ahead.map((_)=>`#${_.id} ${Oq(_,F)}`).join("; ");return{ok:!1,code:"timeout.queue",msg:`no '${Y}' slot within ${B8(J)}; ${B.ahead.length} ahead`+(P!==""?`: ${P}`:""),hint:"retry later, raise --max-wait (e.g. --max-wait 15m), or see the queue: myc queue",exit:9}}let T=B.ticket,q=!1,j=null,{leaseMs:O}=SK(W),A=setInterval(()=>{if(q)return;try{if(!mK(L,T)){q=!0;let F="the slot lease was lost (this process was stalled past it and a waiter took the slot); the command keeps running outside the queue";l9(F),$.warn("run.slot_lost",F)}}catch(F){if(j===null)j=F instanceof Error?F.message:String(F),l9(`cannot renew the slot lease (${j}); will retry`),$.warn("run.renew_failed",`cannot renew the slot lease: ${j}`)}},gK(O)),R=(F,P)=>{try{P()}catch(_){$.warn("run.queue_write_failed",`${F}: ${_ instanceof Error?_.message:String(_)}`)}},D;try{D=await Tg(X,U,Fq(W,Y),N,(F)=>R("recording the command pid",()=>Tq(L,T,F)))}finally{clearInterval(A),R("releasing the slot",()=>m9(L,T))}return qg(X,D,{lane:Y,command:l6(X),ticket:T.id,slots:V.slots,queued:B.queued,waited_ms:Math.round(B.waitedMs),reentrant:!1})}finally{L.close()}}finally{N.dispose()}}function KX0(){return{name:"run",summary:"run a heavy command through the machine-wide queue: wait for a slot, then run it",flags:[{name:"lane",value:"string",description:`queue lane (default ${c5}); slots per lane: MYC_<LANE>_SLOTS, default 1`},{name:"max-wait",value:"string",description:"give up waiting after this long: 90s, 5m, 1h; 0 = do not wait (default 5m)"}],help:`Usage: myc run [--lane heavy] [--max-wait 5m] -- <command> [args...]
|
|
8178
8178
|
|
|
8179
8179
|
Several agents on one machine running full test suites, builds and benchmarks at once slow each other down and break latency budgets. \`myc run\` puts the command into a queue shared by every repository and agent of this machine user (~/.myc/queue.db), waits for a free slot (first come, first served), then runs it with inherited stdin/stdout/stderr and exits with ITS exit code. SIGINT/SIGTERM/SIGHUP are forwarded to the command. The slot is released on any outcome: exit, signal, crash.
|
|
8180
8180
|
|
|
@@ -8190,10 +8190,10 @@ Exit codes: the command's own; 128+N when it died of signal N; 127 not found; 12
|
|
|
8190
8190
|
|
|
8191
8191
|
Tuning (tests): MYC_RUN_LEASE_MS (30000), MYC_RUN_POLL_MS (200), MYC_RUN_PROGRESS_MS (10000).
|
|
8192
8192
|
|
|
8193
|
-
See also: myc queue.`,machineStdout:()=>!0,handler:
|
|
8193
|
+
See also: myc queue.`,machineStdout:()=>!0,handler:UX0,renderHuman:()=>""}}function Fg($,X,Z,Y,z=!1){let J=jq($);return{id:$.id,lane:$.lane,state:$.state,liveness:Z,position:Y,command:l6(J),argv:J,cwd:$.cwd,pid:$.pid,host:$.host,session:$.session,terminal:$.terminal,agent_pid:$.agent_pid,actor:$.actor,child_pid:$.child_pid,orphan:z,enqueued_at:$.enqueued_at,started_at:$.started_at,waited_ms:Math.max(0,($.started_at??X)-$.enqueued_at),running_ms:$.started_at!==null?Math.max(0,X-$.started_at):null,heartbeat_ms:Math.max(0,X-$.renewed_at)}}function WX0($){let X=process.env,Z=$.flags.lane,Y=typeof Z==="string"?Z.trim():void 0;if(Y!==void 0&&!vK(Y))return nK(`bad lane '${Y}'`,"a lane is a lowercase name: letters, digits, '-', up to 32 chars");let z=bK(),J=Nq(z);if(J===void 0)return{ok:!0,data:{db:z,exists:!1,lanes:[],removed:[]}};try{let U=Date.now(),K=Og(),{rows:W,removed:V}=B3(J,Y,{now:U,host:K}),G=new Map;for(let Q of W)G.set(Q.lane,[...G.get(Q.lane)??[],Q]);let H=[...G.entries()].map(([Q,L])=>{let B=0,T=L.map((q)=>Fg(q,U,lK(q,U,K),q.state==="waiting"?++B:null));return{lane:Q,slots:fK(Q,X).slots,running:T.filter((q)=>q.state==="running").length,waiting:T.filter((q)=>q.state==="waiting").length,entries:T}});return{ok:!0,data:{db:z,exists:!0,lanes:H,removed:V.map((Q)=>Fg(Q,U,"dead",null,Q.orphan))}}}finally{J.close()}}function VX0($){let X=$.state==="running"?B8($.running_ms??0):B8($.waited_ms),Z=[$.session!==""?`session ${$.session.slice(0,8)}`:"",$.terminal!==""?`orca ${$.terminal.slice(0,13)}`:"",`pid ${$.pid}`,$.child_pid!==null?`command pid ${$.child_pid}`:""].filter((J)=>J!=="").join(" \xB7 "),Y=$.position!==null?` (#${$.position} in line)`:"",z=$.liveness==="stale"?` STALE: no heartbeat for ${B8($.heartbeat_ms)}, process still exists`:"";return` ${$.state.padEnd(7)} #${$.id} ${X.padStart(6)} ${l6($.argv,50)} ${p9($.cwd)} ${Z}${Y}${z}`}function GX0($){let X=$,Z=[];if(X.lanes.length===0)Z.push(`queue is empty \xB7 ${p9(X.db)}`);else for(let Y of X.lanes){Z.push(`${Y.lane} \xB7 slots ${Y.slots} \xB7 ${Y.running} running \xB7 ${Y.waiting} waiting \xB7 ${p9(X.db)}`);for(let z of Y.entries)Z.push(VX0(z))}for(let Y of X.removed)Z.push(`removed dead #${Y.id} '${l6(Y.argv,50)}' in ${p9(Y.cwd)}, pid ${Y.pid}: the process is gone`+(Y.orphan?`; its command (pid ${Y.child_pid}) is still running outside the queue`:""));return`${Z.join(`
|
|
8194
8194
|
`)}
|
|
8195
|
-
`}function
|
|
8196
|
-
${Z}`:$).replaceAll("\\","/");return["sh","cmd","ps1"].some((z)=>Y.includes(`agent-hooks/${sK}.${z}`))}function
|
|
8195
|
+
`}function HX0(){return{name:"queue",summary:"who runs and who waits in the machine-wide queue of myc run",flags:[{name:"lane",value:"string",description:"only this lane (default: all lanes)"}],help:`Shows the queue of \`myc run\` shared by this machine user (~/.myc/queue.db): per lane, the running commands and the waiting ones in line order, with directory, session, orca terminal, pid and how long each has run or waited. Tickets whose process is gone are shown as removed and deleted. A ticket whose lease expired while its process still exists is marked STALE; a waiting \`myc run\` removes it after watching it not renew. Slots per lane: ${yK(c5)} (MYC_<LANE>_SLOTS), default 1. --json for machines.`,handler:WX0,renderHuman:GX0}}var Cg=300000,Ag=1e4,$X0,Rg;var Aq=v(()=>{V0();iK();$X0=["SIGINT","SIGTERM","SIGHUP"];Rg=[".env",".env.local",".env.development",".env.production",".env.test",".env.development.local",".env.production.local",".env.test.local"]});function QX0($,X,Z){let Y=Z!==null&&Z.count>0;if($===null)return Y?"never":"idle";if(!Y||Z.last-Z.first<X)return"ok";return"frozen"}function NX0($,X){return $===null?Number.NEGATIVE_INFINITY:$+dK*X}function M7($){let X=Math.max(0,Math.round($/1000));if(X<90)return`${X}s`;let Z=Math.round(X/60);if(Z<90)return`${Z}m`;let Y=Math.round(Z/60);if(Y<48)return`${Y}h`;return`${Math.round(Y/24)}d`}function LX0($,X){let Z=$.query("SELECT value FROM myc_meta WHERE key = ?1").get(X),Y=Number(Z?.value);return Z===null||!Number.isFinite(Y)||Y<=0?null:Y}function BX0($){return $.query("SELECT ts_ms FROM oplog WHERE origin = 1 ORDER BY seq DESC LIMIT 1").get()?.ts_ms??null}function TX0($,X){let Z=$.query("SELECT min(ts_ms) AS first, max(ts_ms) AS last, count(*) AS n FROM oplog WHERE origin = 1 AND ts_ms > ?1").get(Number.isFinite(X)?X:-1);return Z.n===0||Z.first===null||Z.last===null?null:{first:Z.first,last:Z.last,count:Z.n}}function Ig($,X,Z){let Y=LX0($,X.key),z=BX0($),J=TX0($,NX0(Y,X.periodMs)),U=QX0(Y,X.periodMs,J),K={name:X.name,key:X.key,stampMs:Y,periodMs:X.periodMs,lastLocalWriteMs:z,overdue:J,verdict:U},W=[`${X.key} ${Y===null?"none":new Date(Y).toISOString()}`,`period ${M7(X.periodMs)}, overdue after ${dK} periods`,`last local write ${z===null?"none":new Date(z).toISOString()}`,...J!==null?[`${J.count} local writes after it was overdue, ${new Date(J.first).toISOString()} \u2026 ${new Date(J.last).toISOString()}`]:[]],V=z===null?"":`, last local write ${M7(Z-z)} ago`,G=U==="frozen"||U==="never"?X.extra?.()??null:null,H=`${qX0}; ${X.cure}${G!==null?`; ${G}`:""}`,N;if(U==="frozen")N={name:X.name,verdict:"drift",detail:`${X.key} is ${M7(Z-Y)} old, yet local writes kept coming for ${M7(J.last-J.first)} after it was ${dK} periods (${M7(dK*X.periodMs)}) overdue${V}: `+`commands run, the background after them does not \u2014 ${H}`,items:W};else if(U==="never")N={name:X.name,verdict:"unknown",detail:`no ${X.key}: the background has never done this here, yet there are ${J.count} local writes over ${M7(J.last-J.first)}${V} (just upgraded myc? any command sets it) \u2014 ${H}`,items:W};else if(U==="idle")N={name:X.name,verdict:"n/a",detail:`no ${X.key} and no local writes yet: nothing has asked for it`,items:W};else{let Q=J!==null?`; ${J.count} local writes since it went overdue span ${M7(J.last-J.first)}, under one period \u2014 not yet a frozen background`:"";N={name:X.name,verdict:"ok",detail:`${X.key} ${M7(Z-Y)} ago (period ${M7(X.periodMs)})${V}${Q}`,items:W}}return{check:N,mark:K}}function kg($,X){let Z=X.processEnv??process.env,Y=X.env,z=(W)=>({checks:[{name:"anchor_sweep",verdict:"n/a",detail:W},{name:"code_index",verdict:"n/a",detail:W}],marks:[]});if(Z.NODE_ENV==="test")return z("the background is off in this process: test runner (NODE_ENV=test)");if(!vU(Y))return z(`the background is off in this environment: MYC_DRAIN=${Y.MYC_DRAIN??""}`);let J=[],U=[],K=(W,V)=>{try{let G=V();if("check"in G)J.push(G.check),U.push(G.mark);else J.push(G)}catch(G){J.push({name:W,verdict:"unknown",detail:`not checked: ${G instanceof Error?G.message:String(G)}`})}};return K("anchor_sweep",()=>SU(Y)?Ig($,{name:"anchor_sweep",key:_Y,periodMs:yU(Y),cure:"check MYC_DRAIN and MYC_ANCHOR_CHECK in their environment; `myc anchor check` sweeps by hand"},X.now):{name:"anchor_sweep",verdict:"n/a",detail:`the anchor sweep is off in this environment: MYC_ANCHOR_CHECK=${Y.MYC_ANCHOR_CHECK??""}`}),K("code_index",()=>{if(!fU(Y))return{name:"code_index",verdict:"n/a",detail:`the code-index refresh is off in this environment: MYC_CODE_INDEX=${Y.MYC_CODE_INDEX??""}`};let W=$.query("SELECT 1 AS x FROM anchors LIMIT 1").get()!==null,V=$.query("SELECT 1 AS x FROM code_files LIMIT 1").get()!==null;if(!W&&!V)return{name:"code_index",verdict:"n/a",detail:"no code index and no anchors: the background does not index this workspace (\xA74.3)"};return Ig($,{name:"code_index",key:t7,periodMs:K5(Y),cure:"check MYC_DRAIN and MYC_CODE_INDEX in their environment; `myc code index` refreshes by hand",extra:()=>{let G=lJ($,X.now);if(G===null)return null;if(G.state==="failed")return`the refresh job gave up after ${G.attempts} attempts (${G.lastError??"the worker died without a word"}) \u2014 \`myc code index\` shows why and clears it`;return`a refresh job is ${G.state}`}},X.now)}),{checks:J,marks:U}}var dK=2,qX0="the binary may carry its test-mode guard folded in by the bundler (memory-h5zp5mqcdbay): rebuild it with `bun run build` (the build now refuses such an artifact) and restart what runs it (the MCP server, hooks)";var Eg=v(()=>{TL()});import{existsSync as FX0,readFileSync as vg}from"fs";import{homedir as jX0}from"os";import{join as Pq}from"path";function C4($){return OX0.test($)}function Y6($){let X=Z8($);return X!==null&&C4(X)}function Z8($){if($===null||typeof $!=="object"||Array.isArray($))return null;let X=$;if(X.type!=="command")return null;let Z=X.command;return typeof Z==="string"&&Z.trim().length>0?Z:null}function i5($){if(/^[A-Za-z0-9_./:@%+=,-]+$/.test($))return $;return`'${$.replaceAll("'","'\\''")}'`}function yg($,X){let Z;if($.source==="repo")Z=`"\${CLAUDE_PROJECT_DIR:-.}/${$.command.replace(/^\.\//,"")}"`;else Z=i5($.command);let Y=X!==void 0?` ${Dq} ${i5(X)}`:"";return`${Z} ${n5}${Y}`}function aK($){return`${i5($.command)} ${n5} ${CX0} user`}function rK($){let X=/\s-EncodedCommand\s+(\S+)/i.exec($),Z="";if(X!==null)try{Z=Buffer.from(X[1],"base64").toString("utf16le")}catch{Z=""}let Y=(Z.length>0?`${$}
|
|
8196
|
+
${Z}`:$).replaceAll("\\","/");return["sh","cmd","ps1"].some((z)=>Y.includes(`agent-hooks/${sK}.${z}`))}function AX0($=process.env){let X=$.CLAUDE_CONFIG_DIR;if(X!==void 0&&X.length>0)return X;let Z=$.HOME!==void 0&&$.HOME.length>0?$.HOME:jX0();return Pq(Z,".claude")}function c9($=process.env){return Pq(AX0($),"settings.json")}function T3($){if(!FX0($))return{value:void 0,broken:!1};try{let X=JSON.parse(vg($,"utf8"));if(X===null||typeof X!=="object"||Array.isArray(X))return{value:void 0,broken:!0};return{value:X.statusLine,broken:!1}}catch{return{value:void 0,broken:!0}}}function eK($){let X=(Y)=>Y!==void 0&&Y.length>0?Y:void 0,Z=X($.MYC_HOME)??X($.HOME)??X($.USERPROFILE);return Z===void 0?null:Pq(Z,".myc",tK)}function $W($){let X=eK($);if(X===null)return;try{let Z=JSON.parse(vg(X,"utf8"));if(Z===null||typeof Z!=="object"||Z.scope!=="user")return;let Y=Z.status_line;if(Y===null||typeof Y!=="object"||Array.isArray(Y))return;return{previous:Y.previous??null}}catch{return}}var n5="statusline",Dq="--then",oK="MYC_STATUSLINE_NESTED",OX0,CX0="--scope",sK="claude-statusline",tK="wire-user.json";var q3=v(()=>{OX0=/(?:^|[\s/"'])myc(?:\.exe|\.cmd|\.bat)?["']?\s+statusline(?:\s|$)/});function EX0(){return{builtin:DX0,valueFlags:MX0,lane:c5,heldEnv:u9,envName:O3,managed:IX0}}function Mq(){return`#!/usr/bin/env node
|
|
8197
8197
|
// ${F3} \u2014 generated by \`myc wire --queue-hook\`; edits will be overwritten.
|
|
8198
8198
|
//
|
|
8199
8199
|
// Claude Code PreToolUse hook on Bash. A heavy command (a full test run, a
|
|
@@ -8216,7 +8216,7 @@ ${Z}`:$).replaceAll("\\","/");return["sh","cmd","ps1"].some((z)=>Y.includes(`age
|
|
|
8216
8216
|
import { existsSync, readFileSync } from "node:fs";
|
|
8217
8217
|
import { delimiter, join, resolve } from "node:path";
|
|
8218
8218
|
|
|
8219
|
-
${
|
|
8219
|
+
${kX0}
|
|
8220
8220
|
|
|
8221
8221
|
const read = (path) => {
|
|
8222
8222
|
try {
|
|
@@ -8225,7 +8225,7 @@ const read = (path) => {
|
|
|
8225
8225
|
return null;
|
|
8226
8226
|
}
|
|
8227
8227
|
};
|
|
8228
|
-
const Q = makeQueueClassifier(${JSON.stringify(
|
|
8228
|
+
const Q = makeQueueClassifier(${JSON.stringify(EX0())}, { exists: existsSync, read, join, resolve, delimiter });
|
|
8229
8229
|
|
|
8230
8230
|
let out = "";
|
|
8231
8231
|
try {
|
|
@@ -8234,7 +8234,7 @@ try {
|
|
|
8234
8234
|
} catch {}
|
|
8235
8235
|
if (out) process.stdout.write(out);
|
|
8236
8236
|
process.exit(0);
|
|
8237
|
-
`}function
|
|
8237
|
+
`}function vX0($){return/^[A-Za-z0-9_/.,:@%+=-]+$/.test($)?$:`'${$.replace(/'/g,"'\\''")}'`}function Rq($){let X=[...RX0.map((Z)=>`*${Z}*`),_X0].join("|");return[`f="\${CLAUDE_PROJECT_DIR:-.}/${F3}"`,"IFS= read -r p",`c=\${p#*'"command":"'}`,`case \${c%%'","'*} in ${X}) ;; *) [ -n "\${${O3}+x}" ] || exit 0;; esac`,'[ -f "$f" ] || exit 0',"r=node","command -v bun >/dev/null 2>&1 && r=bun",`printf '%s\\n' "$p" | "$r" "$f" ${vX0($)}`].join("; ")}function _q($){return{matcher:"Bash",hooks:[{type:"command",command:Rq($),timeout:PX0}]}}var F3=".claude/helpers/myc-queue.mjs",j3="myc-queue.mjs",O3="MYC_QUEUE_HEAVY",PX0=5,DX0,MX0,RX0,_X0="*myc*run*",IX0,kX0;var fg=v(()=>{iK();DX0=["bun test $","bun run test","bun run build","bun run typecheck","npm test","npm run test","npm run build","pnpm test","pnpm run test","pnpm build","pnpm run build","yarn test","yarn build","cargo test","cargo build","go test ./...","go build ./...","pytest $","python -m pytest $","python3 -m pytest $","make"],MX0=["--timeout","-t","--test-name-pattern","--preload","--rerun-each","--seed","--max-concurrency","--reporter","--reporter-outfile","--coverage-reporter","--coverage-dir","--env-file","--cwd","--tsconfig-override","-k","-m","-p","-c","-o","-n","-W","--maxfail","--rootdir","--basetemp","--junitxml","--junit-xml","--durations","--tb","--ignore","--ignore-glob","--deselect","--log-level","--capture","--import-mode","--dist","--confcutdir"],RX0=["test","build","typecheck","make"],IX0=["/Library/Application Support/ClaudeCode/managed-settings.json","/etc/claude-code/managed-settings.json"],kX0=String.raw`function makeQueueClassifier(o, host) {
|
|
8238
8238
|
var BQ = String.fromCharCode(96);
|
|
8239
8239
|
var META = " \t\n;&|()<>";
|
|
8240
8240
|
var SKIP = { "!": 1, "{": 1, "}": 1, "if": 1, "then": 1, "else": 1, "elif": 1, "fi": 1,
|
|
@@ -8738,8 +8738,8 @@ process.exit(0);
|
|
|
8738
8738
|
|
|
8739
8739
|
return { scan: scan, plan: plan, insert: insert, patterns: patterns, held: held, parsePattern: parsePattern,
|
|
8740
8740
|
mycWord: mycWord, loadRules: loadRules, matchRule: matchRule, ruleOf: ruleOf, hook: hook };
|
|
8741
|
-
}`});var rq={};s(rq,{wireHash:()=>D4,userPaths:()=>R3,userGeneratedFiles:()=>s9,resolveUserMycBin:()=>Wb,resolveMycBin:()=>tg,readWireJournal:()=>VW,readUserMcp:()=>dq,readUserJournal:()=>_3,readOpencodeMcp:()=>aq,probeUserStatusLineBin:()=>Gb,probeUserMcpBin:()=>Vb,probeStatusLineBin:()=>Yb,probeQueueBin:()=>zb,mycPermissions:()=>M3,isUserHookEntry:()=>nq,isOpencodeServerOurs:()=>sq,generatedFiles:()=>cq,createWireCommand:()=>
|
|
8742
|
-
`}function G$($){return Array.isArray($)?$:[]}function Q0($){return $!==null&&typeof $==="object"&&!Array.isArray($)?{...$}:{}}function KW($,X){return JSON.stringify($)===JSON.stringify(X)}function ag($){return $.includes(ig)||$.includes(j3)}function lq($){return G$(Q0($).hooks).some((Z)=>{let Y=Q0(Z).command;return typeof Y==="string"&&ag(Y)})}function
|
|
8741
|
+
}`});var rq={};s(rq,{wireHash:()=>D4,userPaths:()=>R3,userGeneratedFiles:()=>s9,resolveUserMycBin:()=>Wb,resolveMycBin:()=>tg,readWireJournal:()=>VW,readUserMcp:()=>dq,readUserJournal:()=>_3,readOpencodeMcp:()=>aq,probeUserStatusLineBin:()=>Gb,probeUserMcpBin:()=>Vb,probeStatusLineBin:()=>Yb,probeQueueBin:()=>zb,mycPermissions:()=>M3,isUserHookEntry:()=>nq,isOpencodeServerOurs:()=>sq,generatedFiles:()=>cq,createWireCommand:()=>Y90,createUnwireCommand:()=>J90,WIRE_JOURNAL:()=>P4,USER_JOURNAL:()=>tK,ASK_SUBCOMMANDS:()=>mq});import{createHash as yX0}from"crypto";import{copyFileSync as ZW,existsSync as i6,mkdirSync as i9,mkdtempSync as ug,readdirSync as fX0,readFileSync as SX0,renameSync as gX0,rmdirSync as lg,rmSync as z6,writeFileSync as R7}from"fs";import{tmpdir as pg}from"os";import{dirname as m$,isAbsolute as kq,join as H0,relative as cg,resolve as _7}from"path";function M3($){return $.top.map((X)=>X.name).filter((X)=>!mq.has(X)).sort().map((X)=>`Bash(myc ${X}:*)`)}function ng($){return typeof $==="string"&&($===o5||/^Bash\(myc [a-z][a-z0-9-]*:\*\)$/.test($))}function og(){return{actions:[],conflicts:[],evicted:[],untouched:[],notes:[],trackedAbsolute:[]}}function uq($){return`${$} ${$===1?"node":"nodes"}`}function c6($){return yX0("sha256").update($).digest("hex").slice(0,16)}function m0($){try{return i6($)?SX0($,"utf8"):null}catch{return null}}function J6($,X,Z,Y){let z=H0(X,Z),J=m0(z);if(J===Y){$.actions.push({path:Z,kind:"unchanged",detail:"up to date",content:Y,nodes:[],backup:!1});return}$.actions.push({path:Z,kind:J===null?"new":"rewrite",detail:`${(Buffer.byteLength(Y,"utf8")/1024).toFixed(1)} KB`,content:Y,nodes:[],backup:J!==null,created:J===null})}function o9($){let X=m0($);if(X===null)return{exists:!1,value:{},indent:" ",broken:!1};let Y=/\n([ \t]+)"/.exec(X)?.[1]??" ";try{let z=JSON.parse(X);if(z===null||typeof z!=="object"||Array.isArray(z))return{exists:!0,value:{},indent:Y,broken:!0};return{exists:!0,value:z,indent:Y,broken:!1}}catch{return{exists:!0,value:{},indent:Y,broken:!0}}}function yq($,X){return`${JSON.stringify($,null,X)}
|
|
8742
|
+
`}function G$($){return Array.isArray($)?$:[]}function Q0($){return $!==null&&typeof $==="object"&&!Array.isArray($)?{...$}:{}}function KW($,X){return JSON.stringify($)===JSON.stringify(X)}function ag($){return $.includes(ig)||$.includes(j3)}function lq($){return G$(Q0($).hooks).some((Z)=>{let Y=Q0(Z).command;return typeof Y==="string"&&ag(Y)})}function bX0($){for(let X of G$(Q0($.hooks).PreToolUse))if(G$(Q0(X).hooks).some((z)=>{let J=Q0(z).command;return typeof J==="string"&&J.includes(j3)}))return Q0(X);return null}function wX0($){return fq($)[0]??null}function fq($){let X=G$(Q0($).hooks),Z=[];for(let Y of X){let z=Q0(Y).command;if(typeof z==="string"&&!ag(z))Z.push(z)}return Z}function xX0($){let X=Q0($).matcher;return typeof X==="string"&&X.length>0?X:void 0}function pq($){return Math.max(1,Math.ceil($.timeoutMs/1000))}function hX0($){let X=`node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/myc-hooks.mjs" ${$.event}`;return{...$.matcher!==void 0?{matcher:$.matcher}:{},hooks:[{type:"command",command:X,timeout:pq($)}]}}function mX0($){return{...$.matcher!==void 0?{matcher:$.matcher}:{},hooks:[{type:"command",command:uM($.event),timeout:pq($)}]}}function sg($,X,Z,Y){let z={...$.value},J=Q0(z.hooks),U=[],K=[],W=[],V=[],G=[];for(let{event:H,entry:N}of X){let Q=G$(J[H]),L=Q.filter((j)=>!lq(j)),B=`hooks.${H}`;if(L.length>0&&Z===void 0){W.push({path:Y,node:B,command:wX0(L[0])??"(unknown)"});continue}if(L.length>0&&Z==="skip")continue;if(Z==="replace")for(let j of L){let O=xX0(j),A=fq(j);for(let R of A.length>0?A:["(command not readable)"])V.push({path:Y,event:H,...O!==void 0?{matcher:O}:{},command:R})}else if(L.length>0){let j=L.filter((O,A)=>Q.indexOf(O)!==A);if(j.length>0)G.push(`${Y}: ${B} \u2014 myc's hook moved to the end of the array, foreign hooks moved up and `+`will run before it: ${j.map((O)=>fq(O).join(", ")||"(command not readable)").join("; ")}`)}let q=[...Z==="replace"?[]:L,N];if(J[H]=q,U.push(B),!KW(Q,q))K.push(B)}if(W.length>0)return{nodes:U,changedNodes:K,conflicts:W,evicted:V,notes:G,value:z};if(U.length>0)z.hooks=J;return{nodes:U,changedNodes:K,conflicts:W,evicted:V,notes:G,value:z}}function uX0($,X,Z,Y,z,J){let U=[...X.map((T)=>({event:T.claudeEvent,entry:hX0(T)})),...z],K=sg($,U,Z,Y);if(K.conflicts.length>0)return K;let W={...K.value},V=[...K.nodes],G=[...K.changedNodes??[]],H=[...K.notes??[]],N=Q0(W.permissions),Q=G$(N.allow),L=!1;if(Q.includes(o5))if(J.legacyOurs)Q=Q.filter((T)=>T!==o5),L=!0,H.push(`${Y}: removed the old permissions.allow[${o5}] \u2014 it let \`myc run -- <any command>\` `+`run without asking; myc subcommands are now allowed one by one, and ${[...mq.keys()].join(", ")} ask`);else H.push(`${Y}: permissions.allow has ${o5}, which lets \`myc run -- <any command>\` run without `+"asking \u2014 wire did not write it and leaves it alone; remove it by hand");let B=J.rules.filter((T)=>!Q.includes(T));if(B.length>0||L)N.allow=[...Q,...B],W.permissions=N;if(B.length>0){let T=`permissions.allow[${B.length===1?B[0]:`Bash(myc <command>:*) \xD7${B.length}`}]`;V.push(T),G.push(T)}return{...K,nodes:V,changedNodes:G,notes:H,value:W}}function lX0($,X,Z,Y){return sg($,X.map((z)=>({event:z.claudeEvent,entry:mX0(z)})),Z,Y)}function a9($,X,Z,Y){let z=H0(X,Z),J=o9(z);if(J.broken){$.conflicts.push({path:Z,node:"(file)",command:"not valid JSON"});return}let U=Y(J);if($.conflicts.push(...U.conflicts),U.conflicts.length>0)return;if($.evicted.push(...U.evicted??[]),$.notes.push(...U.notes??[]),U.statusLine!==void 0)$.statusLine=U.statusLine;let K=m0(z);if(K!==null&&yq(J.value,J.indent)!==K)$.notes.push(`${Z}: will be reformatted (line breaks change), content is kept; backup \u2014 ${Z}${d5}`);let W=yq(U.value,J.indent),V=m0(z),G=J.exists?pX0(J.value):[];if(V===W){$.actions.push({path:Z,kind:"unchanged",detail:"up to date",content:W,nodes:U.nodes,backup:!1,preexisting:G});return}let H=U.changedNodes??U.nodes;$.actions.push({path:Z,kind:J.exists?"merge":"new",detail:H.length>0?`+${uq(H.length)}: ${H.join(", ")}`:"no node changes",content:W,nodes:U.nodes,backup:J.exists,preexisting:G,created:!J.exists})}function $$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function pX0($){let X=[],Z=$.hooks;if($$(Z)){let z=!1;for(let[J,U]of Object.entries(Z)){let K=G$(U).some(lq);if(z=z||K,Array.isArray(U)&&!K)X.push(`hooks.${J}`)}if(!z)X.push("hooks")}let Y=$.permissions;if($$(Y)){let z=Y.allow,J=Array.isArray(z)&&z.some(ng);if(Array.isArray(z)&&!J)X.push("permissions.allow");if(!J)X.push("permissions")}for(let z of["mcpServers","mcp"]){let J=$[z];if($$(J)&&J.myc===void 0)X.push(z)}return X}function rg($,X,Z,Y){let z=$.indexOf(X),J=$.indexOf(Z);if(z===-1||J===-1||J<z){let U=$.length===0||$.endsWith(`
|
|
8743
8743
|
|
|
8744
8744
|
`)?"":$.endsWith(`
|
|
8745
8745
|
`)?`
|
|
@@ -8747,24 +8747,24 @@ process.exit(0);
|
|
|
8747
8747
|
|
|
8748
8748
|
`;return`${$}${U}${Y}
|
|
8749
8749
|
`}return`${$.slice(0,z)}${Y}${$.slice(J+Z.length)}`}function gg($,X,Z){let Y=$.indexOf(X);return Y!==-1&&$.indexOf(Z)>Y}function JW($,X,Z){let Y=$.indexOf(X),z=$.indexOf(Z);if(Y===-1||z===-1||z<Y)return $;return`${$.slice(0,Y).replace(/\n+$/,`
|
|
8750
|
-
`)}${$.slice(z+Z.length).replace(/^\n+/,"")}`}function tg($,X=process.env,Z=i6,Y=process.platform){let z=X.MYC_BIN;if(z!==void 0&&z.length>0&&Z(z))return{command:z,source:"env"};for(let H of["node_modules/.bin/myc","dist/myc",".myc/bin/myc"])if(Z(H0($,H)))return{command:`./${H}`,source:"repo"};let J=X.HOME!==void 0&&X.HOME.length>0?X.HOME:X.USERPROFILE??"",U=H0(J,".myc/bin/myc");if(J.length>0&&Z(U))return{command:U,source:"home"};let K=Y==="win32",W=K?["myc.exe","myc.cmd","myc.bat","myc"]:["myc"],V=K?";":":",G=X.PATH??X.Path??"";for(let H of G.split(V)){if(H.length===0)continue;for(let N of W)if(Z(H0(H,N)))return{command:"myc",source:"path"}}return{command:"myc",source:"none"}}function
|
|
8751
|
-
`),K=[],W=J;if(!gg(W,YW,zW)&&/^\s*\[mcp_servers\.myc\]/m.test(W))$.conflicts.push({path:".codex/config.toml",node:"[mcp_servers.myc]",command:"the section already exists outside the myc markers"});else W=rg(W,YW,zW,U),K.push("[mcp_servers.myc]");if(gg(W,Eq,vq))W=JW(W,Eq,vq),$.notes.push(`${".codex/config.toml"}: removed our old notify on .codex/myc-notify.mjs \u2014 ${mM}. The .codex/myc-notify.mjs file itself is removed by \`myc unwire\``);let V=Y$.filter((G)=>X.events.includes(G.event)&&BN.has(G.event));if(V.length>0)J6($,X.root,GY,lM({events:X.events,hookOutput:X.hookOutput})),a9($,X.root,Sg,(G)=>
|
|
8752
|
-
`+oM(X.events))}function
|
|
8750
|
+
`)}${$.slice(z+Z.length).replace(/^\n+/,"")}`}function tg($,X=process.env,Z=i6,Y=process.platform){let z=X.MYC_BIN;if(z!==void 0&&z.length>0&&Z(z))return{command:z,source:"env"};for(let H of["node_modules/.bin/myc","dist/myc",".myc/bin/myc"])if(Z(H0($,H)))return{command:`./${H}`,source:"repo"};let J=X.HOME!==void 0&&X.HOME.length>0?X.HOME:X.USERPROFILE??"",U=H0(J,".myc/bin/myc");if(J.length>0&&Z(U))return{command:U,source:"home"};let K=Y==="win32",W=K?["myc.exe","myc.cmd","myc.bat","myc"]:["myc"],V=K?";":":",G=X.PATH??X.Path??"";for(let H of G.split(V)){if(H.length===0)continue;for(let N of W)if(Z(H0(H,N)))return{command:"myc",source:"path"}}return{command:"myc",source:"none"}}function cX0($,X){try{return Bun.spawnSync(["git","ls-files","--error-unmatch",X],{cwd:$,stdin:"ignore",stdout:"ignore",stderr:"ignore"}).exitCode===0}catch{return!1}}function eg($,X,Z,Y){let z={command:X.mycBin.command,args:["mcp","--profile","agent"]};if(!kq(X.mycBin.command))return z;if(!cX0(X.root,Z))return z;let J=Q0(Y).command;if(typeof J==="string"&&J.length>0&&!kq(J))return $.trackedAbsolute.push({path:Z,bin:X.mycBin.command,command:J,kept:!0}),Q0(Y);return $.trackedAbsolute.push({path:Z,bin:X.mycBin.command,command:"(no relative command in the file)",kept:!1}),z}function $b($,X){if($.actions.some((Z)=>Z.path===".mcp.json"))return;a9($,X.root,".mcp.json",(Z)=>{let Y={...Z.value},z=Q0(Y.mcpServers);return z.myc=eg($,X,".mcp.json",z.myc),Y.mcpServers=z,{nodes:["mcpServers.myc"],conflicts:[],value:Y}})}function iX0($,X){let Z=Y$.filter((V)=>X.events.includes(V.event)),Y=".claude/settings.json";J6($,X.root,".claude/helpers/myc-hooks.mjs",fM({events:X.events,hookOutput:X.hookOutput})),J6($,X.root,".claude/skills/myc/SKILL.md",X9());let z=nX0($,X,".claude/settings.json"),J={rules:X.permissions,legacyOurs:X.previousJournal?.entries.some((V)=>V.path===".claude/settings.json")??!1};a9($,X.root,".claude/settings.json",(V)=>{let G=z===null?[]:[{event:"PreToolUse",entry:z}],H=uX0(V,Z,X.mode,".claude/settings.json",G,J);return H.conflicts.length>0?H:dX0(H,X,".claude/settings.json")});let U=c9(X.env),W=G$(Q0(o9(U).value.permissions).allow).find((V)=>V===o5||V==="Bash(myc run:*)");if(W!==void 0)$.notes.push(`${U}: permissions.allow has ${String(W)}, so \`myc run -- <any command>\` runs without asking in every project; with --queue-hook the hook asks instead, otherwise remove it by hand (wire does not write there)`);if($b($,X),$.untouched.push("CLAUDE.md"),X.statusLine)$.untouched.push(".claude/settings.local.json","~/.claude/settings.json (read only)");else if($.statusLine===void 0)$.untouched.push(".claude/settings.json:statusLine (needs --status-line)")}function nX0($,X,Z){let Y=bX0(o9(H0(X.root,Z)).value);if(X.queueBin!==null)Y=_q(X.queueBin.command),$.notes.push(`${Z}: hooks.PreToolUse[Bash] \u2014 a heavy command (a full test run, a build) goes through `+`\`myc run -- \u2026\` with ${X.queueBin.command} (${X.queueBin.source}); it is approved without asking only when your own rules allow the original command (e.g. Bash(bun test:*)), otherwise Claude Code asks and shows the whole command; the built-in patterns can be replaced with ${O3}`);if(Y===null)return $.untouched.push(`${Z}:hooks.PreToolUse (needs --queue-hook)`),null;return J6($,X.root,F3,Mq()),Y}function a5($){let X=$.replace(/\s+/g," ").trim();return X.length<=60?X:`${X.slice(0,59)}\u2026`}function dX0($,X,Z){let Y=$.value.statusLine,z=Y6(Y),J=X.previousJournal?.status_line,U=[...$.notes??[]],K=`${Z}: our statusLine is set with no record of the previous one (no journal) \u2014 unwire will remove it, and there is nothing to restore`;if(!X.statusLine){if(!z)return $;if(J===void 0)U.push(K);return{...$,notes:U,statusLine:J??{path:Z,previous:null,passthrough:"none"}}}let W;if(z){if(W=J?.previous??null,J===void 0)U.push(K)}else W=Y===void 0?null:Y;let V=Z8(W),G="none",H=null,N=W,Q=!1;if(V!==null&&!Y6(W))G="project",H=V;else{let O=c9(X.env),A=T3(O);if(A.broken)return{...$,conflicts:[{path:O,node:"statusLine",command:"not valid JSON \u2014 can't tell whose line is there, so its input can't be passed on"}]};let R=Z8(A.value);if(R!==null&&!Y6(A.value))G="user",H=R,N=A.value;else if(R!==null){let D=$W(X.env)?.previous,F=Z8(D);if(F!==null&&!C4(F))G="user",H=F,N=D,Q=!0}}if(X.platform==="win32"&&H!==null)return{...$,conflicts:[{path:Z,node:"statusLine",command:`passing input to a foreign line is not implemented on Windows \u2014 not installing over "${a5(H)}"`}]};let L={type:"command",command:yg(X.mycBin,G==="project"?H??void 0:void 0)},B=Q0(N);for(let O of["padding","refreshInterval"])if(typeof B[O]==="number")L[O]=B[O];let T={...$.value,statusLine:L},q="it is neither awaited nor killed \u2014 its output from the last finished run shows above our line";if(G==="project")U.push(`${Z}: statusLine is ours; the previous project line "${a5(H??"")}" gets the same stdin (--then), ${q}`);else if(G==="user"&&Q)U.push(`${Z}: statusLine is ours; the user line is myc's too (myc wire --scope user --status-line), and the line it replaced, "${a5(H??"")}", gets the same stdin (read from ${eK(X.env)??"~/.myc/wire-user.json"} on every redraw), ${q}`);else if(G==="user")U.push(`${Z}: statusLine is ours; the user line "${a5(H??"")}" from ${c9(X.env)} gets the same stdin (read on every redraw), ${q}`);else U.push(`${Z}: statusLine is ours; there was no previous line in the project or user settings \u2014 no one to pass input to`);if(T3(H0(X.root,".claude/settings.local.json")).value!==void 0)U.push(".claude/settings.local.json: has its own statusLine \u2014 local settings override project ones, "+"so Claude Code will show that line, not myc's (file left alone)");return{...$,value:T,nodes:[...$.nodes,"statusLine"],changedNodes:[...$.changedNodes??[],...KW(Y,L)?[]:["statusLine"]],notes:U,statusLine:{path:Z,previous:W,passthrough:G}}}function oX0($,X){let Y=H0(X.root,".codex/config.toml"),z=m0(Y)!==null,J=m0(Y)??"",U=[YW,"[mcp_servers.myc]",'command = "myc"','args = ["mcp", "--profile", "agent"]',"startup_timeout_sec = 10",zW].join(`
|
|
8751
|
+
`),K=[],W=J;if(!gg(W,YW,zW)&&/^\s*\[mcp_servers\.myc\]/m.test(W))$.conflicts.push({path:".codex/config.toml",node:"[mcp_servers.myc]",command:"the section already exists outside the myc markers"});else W=rg(W,YW,zW,U),K.push("[mcp_servers.myc]");if(gg(W,Eq,vq))W=JW(W,Eq,vq),$.notes.push(`${".codex/config.toml"}: removed our old notify on .codex/myc-notify.mjs \u2014 ${mM}. The .codex/myc-notify.mjs file itself is removed by \`myc unwire\``);let V=Y$.filter((G)=>X.events.includes(G.event)&&BN.has(G.event));if(V.length>0)J6($,X.root,GY,lM({events:X.events,hookOutput:X.hookOutput})),a9($,X.root,Sg,(G)=>lX0(G,V,X.mode,Sg)),$.untouched.push("~/.codex/config.toml (project trust and hook review \u2014 by hand only)"),$.notes.push(`Codex: ${hM}`);if(X.statusLine)$.notes.push("Codex: status line not installed \u2014 in codex 0.153.4 tui.status_line is a list of built-in "+"items (/statusline), a command can't go there");if($.conflicts.some((G)=>G.path===".codex/config.toml"))return;if(W===J){$.actions.push({path:".codex/config.toml",kind:"unchanged",detail:"up to date",content:W,nodes:K,backup:!1});return}$.actions.push({path:".codex/config.toml",kind:J.length===0?"new":"merge",detail:`+${uq(K.length)}: ${K.join(", ")}`,content:W,nodes:K,backup:J.length>0,created:!z})}function aX0($,X){if(X.statusLine)$.notes.push("opencode: status line not installed \u2014 there is no config key for it, the TUI draws its own line");J6($,X.root,".opencode/plugin/myc.ts",cM({events:X.events,hookOutput:X.hookOutput})),a9($,X.root,"opencode.json",(Z)=>{let Y={...Z.value};if(!Z.exists)Y.$schema=A3;let z=Q0(Y.mcp);return z.myc={type:"local",command:["myc","mcp","--profile","agent"],enabled:!0},Y.mcp=z,{nodes:["mcp.myc"],conflicts:[],value:Y}})}function sX0($,X){if(J6($,X.root,".kimi-code/skills/myc/SKILL.md",X9()),J6($,X.root,".kimi-code/myc-hooks.mjs",dM({events:X.events,hookOutput:X.hookOutput})),a9($,X.root,".kimi-code/mcp.json",(Z)=>{let Y={...Z.value},z=Q0(Y.mcpServers);return z.myc=eg($,X,".kimi-code/mcp.json",z.myc),Y.mcpServers=z,{nodes:["mcpServers.myc"],conflicts:[],value:Y}}),$.untouched.push("~/.kimi-code/config.toml (Kimi has a user-level hook config only)"),X.statusLine)$.notes.push("Kimi: this version of wire does not install the status line \u2014 Kimi has a status_line with a command, "+"but only in the user's tui.toml, and myc does not write outside the project");$.notes.push("Kimi reads hooks only from ~/.kimi-code/config.toml \u2014 it has no project config, "+`and myc does not write outside the project. The skill and MCP are already in place; to also get prime at startup and an episode before compaction, paste this once:
|
|
8752
|
+
`+oM(X.events))}function rX0($,X){if(X.statusLine)$.notes.push("mimo: status line not installed \u2014 there is no config key for it, the TUI draws its own line");J6($,X.root,".mimocode/skills/myc/SKILL.md",X9()),J6($,X.root,".mimocode/plugin/myc.ts",iM({events:X.events,hookOutput:X.hookOutput})),a9($,X.root,".mimocode/mimocode.json",(Z)=>{let Y={...Z.value};if(!Z.exists)Y.$schema=dg;let z=Q0(Y.mcp);return z.myc={type:"local",command:["myc","mcp","--profile","agent"],enabled:!0},Y.mcp=z,{nodes:["mcp.myc"],conflicts:[],value:Y}})}function tX0($,X){if(J6($,X.root,".minimax/skills/myc/SKILL.md",X9()),J6($,X.root,HY,aM({events:X.events,hookOutput:X.hookOutput})),$b($,X),X.statusLine)$.notes.push("mcode: status line not installed \u2014 this version of wire knows no mcode config key for it");let Z=sM({events:X.events,hookOutput:X.hookOutput});$.notes.push("mcode reads hooks only from user-level plugins (~/.minimax/plugins \u2014 MINIMAX_DATA_DIR ?? "+`~/.minimax); wire does not write outside the project. The skill, MCP and the helper are in place; to also get prime at startup and an episode before compaction, create these two files once:
|
|
8753
8753
|
~/.minimax/plugins/myc/.claude-plugin/plugin.json
|
|
8754
8754
|
${Z.manifest}
|
|
8755
8755
|
|
|
8756
8756
|
~/.minimax/plugins/myc/hooks/hooks.json
|
|
8757
|
-
${Z.hooks}`)}function
|
|
8757
|
+
${Z.hooks}`)}function eX0($,X){let Y=H0(X.root,"AGENTS.md"),z=m0(Y);if(!X.agentsMd){$.untouched.push("AGENTS.md (needs --agents-md)");return}let J=rg(z??"",m1,u1,rM());if(z===J){$.actions.push({path:"AGENTS.md",kind:"unchanged",detail:"block already in place",content:J,nodes:["myc-block"],backup:!1});return}$.actions.push({path:"AGENTS.md",kind:z===null?"new":"merge",detail:"block between the myc:start/myc:end markers",content:J,nodes:["myc-block"],backup:z!==null,created:z===null})}function VW($){let X=m0($);if(X===null)return null;try{let Z=JSON.parse(X);if(Z===null||typeof Z!=="object"||!Array.isArray(Z.entries))return null;let Y=Z.status_line,z=Y!==void 0&&Y!==null&&typeof Y==="object"&&typeof Y.path==="string"?{status_line:{path:Y.path,previous:Y.previous??null,passthrough:Y.passthrough??"none"}}:{};return{v:1,written_at:typeof Z.written_at==="number"?Z.written_at:Number.NaN,agents:Array.isArray(Z.agents)?Z.agents:[],...Z.hook_output==="json"||Z.hook_output==="text"?{hook_output:Z.hook_output}:{},entries:Z.entries,...z}}catch{return null}}function cq($,X,Z){let Y=og(),z={root:$,events:X,hookOutput:Z,mode:void 0,agentsMd:!1,mycBin:{command:"myc",source:"none"},statusLine:!1,queueBin:{command:"myc",source:"path"},permissions:[],previousJournal:null,env:{},platform:process.platform};for(let U of o0)Xb[U](Y,z);let J=new Map;for(let U of Y.actions)if(U.nodes.length===0)J.set(U.path,U.content);return J}function D4($){return c6($)}function Sq($,X){let Z=X.globals.db,Y=Z!==void 0?m$(_7(Z)):H0($,".myc");return H0(Y,P4)}function $90($,X){let Z=H0($,X.path);if(X.kind==="unchanged")return;if(i9(m$(Z),{recursive:!0}),X.backup&&i6(Z))ZW(Z,`${Z}${d5}`);R7(Z,X.content)}function X90($,X,Z,Y){let z=new Map(($?.entries??[]).map((H)=>[H.path,H])),J=X.actions.map((H)=>{let N=z.get(H.path),Q=N!==void 0?N.preexisting??[]:H.preexisting??[],L=N!==void 0?N.created===!0:H.created===!0;return{path:H.path,kind:H.kind,nodes:H.nodes,hash:c6(H.content),...Q.length>0?{preexisting:Q}:{},...L?{created:L}:{}}}),U=new Set(J.map((H)=>H.path)),K=($?.entries??[]).filter((H)=>!U.has(H.path)),W=o0.filter((H)=>Z.includes(H)||($?.agents??[]).includes(H)),V=K.length===0||$?.hook_output===Y,G=X.statusLine??(Z.includes("claude")?void 0:$?.status_line);return{v:1,written_at:Date.now(),agents:W,...V?{hook_output:Y}:{},entries:[...J,...K],...G!==void 0?{status_line:G}:{}}}function M0($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function Jb($){let X=f($,"scope")??"project";return X==="project"||X==="user"?X:null}function Ub($){let X=[],Z=[];for(let Y of Y$)if($.hasTop(Y.command))X.push(Y.event);else Z.push({event:Y.event,reason:`no \`myc ${Y.command}\` command in this build`});return{available:X,skipped:Z}}function Kb($){if($===void 0)return[...o0];let X=[];for(let Z of $.split(",").map((Y)=>Y.trim()).filter((Y)=>Y.length>0)){if(!o0.includes(Z))return null;X.push(Z)}return X.length>0?X:null}function Y90($,X={}){let Z={probeStatusLine:Yb,probeQueue:zb,probeMcp:Vb,probeUserStatusLine:Gb,env:process.env,platform:process.platform,...X};return{name:"wire",summary:"install myc hooks and MCP for Claude Code, Codex, opencode, Kimi, MiniMax Code and MiMo Code without touching foreign files",flags:Z90,help:"Writes only its own files in full (helper, skill, plugin); JSON configs are merged node by node with a .myc.bak alongside. CLAUDE.md is never touched and AGENTS.md only with --agents-md. A foreign hook on the same event is a conflict: nothing is written until --hook-mode says what to do. Running wire twice changes nothing. statusLine is left alone unless --status-line is given; then the line that was there (project, else user) keeps receiving the same stdin, and unwire puts it back byte for byte. --queue-hook adds a PreToolUse hook on Bash that rewrites a heavy command (a full test run, a build) into `myc run -- <the same command>`, so agents on one machine take turns; without the flag no such hook is written, and unwire removes it. --scope user wires Claude Code's user layer (~/.claude) instead of the project: for agents in git worktrees and nested repos whose project layer has no myc. Its helper exits at once where there is no myc workspace or the project wires myc itself; foreign hooks on the same event stay (append is the default, replace is refused); statusLine only with --status-line: myc's line (the full line in a myc workspace, nothing of its own outside one), the line that was there is kept in the journal and keeps getting the same input, and unwire puts it back; the MCP server is registered with `claude mcp add --scope user`; the journal is ~/.myc/wire-user.json. Without --agents the user layer is Claude Code's only; --agents opencode (or claude,opencode) wires opencode's global config ($XDG_CONFIG_HOME/opencode, else ~/.config/opencode): mcp.myc goes into its opencode.json[c] as one node (other entries and comments stay byte for byte), and plugin/myc.ts does nothing where there is no myc workspace or the project wires opencode itself.",handler:(Y)=>{wU();let z=Jb(Y);if(z===null)return M0("usage.invalid","--scope takes project or user",2);if(z==="user")return O90(Y,$,Z);let J=_7(Y.globals.directory??process.cwd()),U=Kb(f(Y,"agents"));if(U===null)return M0("usage.invalid",`--agents takes ${o0.join(", ")}`,2);let K=f(Y,"hook-mode");if(K!==void 0&&!["append","replace","skip"].includes(K))return M0("usage.invalid","--hook-mode takes append, replace, skip",2);let W=K,V=f(Y,"hook-output")??"json";if(V!=="json"&&V!=="text")return M0("usage.invalid","--hook-output takes json or text",2);let{available:G,skipped:H}=Ub($);if(!G.includes("pre-compact"))return M0("precond.missing_command","no `myc absorb-session` command \u2014 nothing to install pre-compact on",5);let N=tg(J,Z.env),Q=Y.flags["status-line"]===!0,L=[],B=null;if(Y.flags["queue-hook"]===!0)if(!U.includes("claude"))L.push("the queue hook is installed only for Claude Code, which is not in --agents \u2014 hooks.PreToolUse left alone");else if(Z.platform==="win32")L.push("queue hook not installed: its command is a POSIX shell snippet and myc run was not checked on Windows");else{let P=Z.probeQueue(J,Z.env);if(!P.ok)return M0("precond.queue_bin",`nowhere to queue heavy commands through: ${P.why}. A hook on a myc without \`run\` would turn `+"every heavy command into an error \u2014 nothing written",5,"MYC_BIN=<path to a fresh myc> myc wire --queue-hook");B=P.bin}let T={root:J,events:G,hookOutput:V,mode:W,agentsMd:Y.flags["agents-md"]===!0,mycBin:N,statusLine:Q,queueBin:B,permissions:M3($),previousJournal:VW(Sq(J,Y)),env:Z.env,platform:Z.platform};if(Q&&U.includes("claude")){let P=Z.probeStatusLine(J,N);if(!P.ok)return M0("precond.statusline_bin",`nowhere to install the status line: ${P.why??"the binary does not answer"}. A line on that `+"binary would show nothing and cut the previous line off from its input \u2014 nothing written",5,N.source==="repo"?"bun run build":"MYC_BIN=<path to a fresh myc> myc wire --status-line")}let q=og();for(let P of o0)if(U.includes(P))Xb[P](q,T);if(eX0(q,T),Q&&!U.includes("claude"))q.notes.push("the status line is installed only for Claude Code, which is not in --agents \u2014 statusLine left alone");q.notes.push(...L);let j=q.conflicts.filter((P)=>P.node==="statusLine");if(j.length>0)return M0("conflict.status_line",["status line not installed, nothing written:",...j.map((P)=>` ${P.path}: ${P.command}`)].join(`
|
|
8758
8758
|
`),4);if(q.conflicts.length>0){let P=q.conflicts.map((_)=>` ${_.path} \u2192 ${_.node}: ${_.command}`);return M0("conflict.foreign_hook",["foreign nodes where ours go, nothing written:",...P,""," --hook-mode append add the myc hook second in the same array (recommended)"," --hook-mode replace replace it (a .myc.bak is kept)"," --hook-mode skip don't install this hook (myc loses context on compaction)"].join(`
|
|
8759
|
-
`),4,"myc wire --hook-mode append")}for(let P of q.trackedAbsolute)Y.warn("wire.absolute_path_tracked",P.kept?`${P.path} is tracked by git: the relative myc command already there (${P.command}) is kept, the absolute MYC_BIN path (${P.bin}) was not written \u2014 a clone on another machine would not have it`:`${P.path} is tracked by git and now carries the absolute path ${P.bin} \u2014 committing it publishes `+"this machine's path; prefer a repo-relative myc (e.g. ./dist/myc) or keep this change out of the commit");let O=Y.flags["dry-run"]===!0,A=q.actions.filter((P)=>P.kind!=="unchanged").length,R=null,D=0;if(!O){for(let M of q.actions)
|
|
8760
|
-
`),R=cg(J,P),m$(P)===H0(J,".myc"))G9(m$(P),"wire")}catch(M){Y.warn("degraded.journal",`journal ${P} not written (${M instanceof Error?M.message:String(M)}): myc unwire won't be able to remove the hooks`)}}for(let P of H)Y.warn("degraded.hook_missing",`hook ${P.event} not installed: ${P.reason}`);if(N.source==="none"&&U.includes("claude"))Y.warn("degraded.bin_unresolved","no myc executable found: not in MYC_BIN, node_modules/.bin/myc, dist/myc, "+".myc/bin/myc, ~/.myc/bin/myc or PATH. .mcp.json says 'myc' \u2014 "+"the MCP server won't start until myc is on PATH or in MYC_BIN");return{ok:!0,data:{root:J,agents:U,events:T.events,skipped_events:H,actions:q.actions.map((P)=>({path:P.path,action:P.kind,detail:P.detail})),evicted:q.evicted,untouched:q.untouched,notes:q.notes,dry_run:O,changed:A,journal:R,journal_kept:D}}},renderHuman:(Y)=>{if(Y.scope==="user")return
|
|
8759
|
+
`),4,"myc wire --hook-mode append")}for(let P of q.trackedAbsolute)Y.warn("wire.absolute_path_tracked",P.kept?`${P.path} is tracked by git: the relative myc command already there (${P.command}) is kept, the absolute MYC_BIN path (${P.bin}) was not written \u2014 a clone on another machine would not have it`:`${P.path} is tracked by git and now carries the absolute path ${P.bin} \u2014 committing it publishes `+"this machine's path; prefer a repo-relative myc (e.g. ./dist/myc) or keep this change out of the commit");let O=Y.flags["dry-run"]===!0,A=q.actions.filter((P)=>P.kind!=="unchanged").length,R=null,D=0;if(!O){for(let M of q.actions)$90(J,M);let P=Sq(J,Y),_=X90(T.previousJournal,q,U,V);D=_.entries.length-q.actions.length;try{if(i9(m$(P),{recursive:!0}),R7(P,`${JSON.stringify(_,null,2)}
|
|
8760
|
+
`),R=cg(J,P),m$(P)===H0(J,".myc"))G9(m$(P),"wire")}catch(M){Y.warn("degraded.journal",`journal ${P} not written (${M instanceof Error?M.message:String(M)}): myc unwire won't be able to remove the hooks`)}}for(let P of H)Y.warn("degraded.hook_missing",`hook ${P.event} not installed: ${P.reason}`);if(N.source==="none"&&U.includes("claude"))Y.warn("degraded.bin_unresolved","no myc executable found: not in MYC_BIN, node_modules/.bin/myc, dist/myc, "+".myc/bin/myc, ~/.myc/bin/myc or PATH. .mcp.json says 'myc' \u2014 "+"the MCP server won't start until myc is on PATH or in MYC_BIN");return{ok:!0,data:{root:J,agents:U,events:T.events,skipped_events:H,actions:q.actions.map((P)=>({path:P.path,action:P.kind,detail:P.detail})),evicted:q.evicted,untouched:q.untouched,notes:q.notes,dry_run:O,changed:A,journal:R,journal_kept:D}}},renderHuman:(Y)=>{if(Y.scope==="user")return C90(Y);let z=Y,U=[z.dry_run?"would write:":"written:"],K=Math.max(...z.actions.map((V)=>V.path.length),10);for(let V of z.actions)U.push(` ${V.action.padEnd(9)} ${V.path.padEnd(K)} ${V.detail}`);if(z.untouched.length>0)U.push(`untouched: ${z.untouched.join(", ")}`);if(z.evicted.length>0){let V=[...new Set(z.evicted.map((G)=>G.path))];U.push(`evicted by --hook-mode replace: ${z.evicted.length} foreign ${z.evicted.length===1?"handler":"handlers"}`);for(let G of z.evicted){let H=G.matcher!==void 0?`${G.event}[${G.matcher}]`:G.event;U.push(` ${G.path} \u2192 ${H}: ${G.command}`)}U.push(z.dry_run?" to restore: they stay in place \u2014 nothing written (--dry-run)":` to restore: ${V.map((G)=>`cp ${G}${d5} ${G}`).join(" && ")}`)}for(let V of z.notes)U.push(`! ${V}`);if(z.journal!==null){let V=z.journal_kept>0?`; entries kept from earlier runs: ${z.journal_kept}`:"";U.push(`journal: ${z.journal} (for myc unwire${V})`)}if(z.dry_run)U.push("nothing written (--dry-run)");else if(z.changed===0)U.push("everything already in place, no files touched");let W=xU(E0);if(W!==null)U.push(W);return`${U.join(`
|
|
8761
8761
|
`)}
|
|
8762
|
-
`}}}function
|
|
8762
|
+
`}}}function z90($,X,Z=new Set){let Y={...$};if(Y6(Y.statusLine)){let V=X?.previous;if(V!==void 0&&V!==null)Y.statusLine=V;else delete Y.statusLine}let z=Q0(Y.hooks),J=!1;for(let V of Object.keys(z)){let G=G$(z[V]).filter((H)=>!lq(H));if(J=!0,G.length===0&&!Z.has(`hooks.${V}`))delete z[V];else z[V]=G}if(J)if(Object.keys(z).length===0&&!Z.has("hooks"))delete Y.hooks;else Y.hooks=z;let U=Q0(Y.permissions);if(Array.isArray(U.allow)){let V=U.allow.filter((G)=>!ng(G));if(V.length===0&&!Z.has("permissions.allow"))delete U.allow;else U.allow=V;if(Object.keys(U).length===0&&!Z.has("permissions"))delete Y.permissions;else Y.permissions=U}let K=Q0(Y.mcpServers);if(K.myc!==void 0)if(delete K.myc,Object.keys(K).length===0&&!Z.has("mcpServers"))delete Y.mcpServers;else Y.mcpServers=K;let W=Q0(Y.mcp);if(W.myc!==void 0)if(delete W.myc,Object.keys(W).length===0&&!Z.has("mcp"))delete Y.mcp;else Y.mcp=W;return Y}function J90($={}){let X=$.env??process.env;return{name:"unwire",summary:"remove exactly what `myc wire` installed, by the .myc/wire.json journal",flags:[{name:"dry-run",description:"print what would be removed, change nothing"},Zb],help:"Files changed after we wrote them are left alone and reported: a journal hash mismatch means a human edited the file, and removing our node blind would be the same trust breach as writing it blind. --scope user undoes `myc wire --scope user` by ~/.myc/wire-user.json: myc's hook entries and the permission rules wire added come out of ~/.claude/settings.json node by node (everything else stays byte for byte), the helpers and the skill are deleted, the MCP server goes through `claude mcp remove --scope user`; for opencode, mcp.myc comes out of its global config (comments and the rest stay byte for byte) and the plugin is deleted.",handler:(Z)=>{let Y=Jb(Z);if(Y===null)return M0("usage.invalid","--scope takes project or user",2);if(Y==="user")return P90(Z,X);let z=_7(Z.globals.directory??process.cwd()),J=Sq(z,Z),U=m0(J);if(U===null)return M0("notfound.journal",`no journal ${J}: nothing to remove`,3,"myc wire");let K;try{K=JSON.parse(U)}catch(Q){return M0("io.read",`journal can't be parsed: ${Q instanceof Error?Q.message:String(Q)}`,1)}let W=Z.flags["dry-run"]===!0,V=[],G=[],H=[];for(let Q of K.entries){let L=H0(z,Q.path),B=m0(L);if(B===null){H.push(Q.path);continue}if(c6(B)!==Q.hash){G.push({path:Q.path,reason:"changed after we wrote it \u2014 left alone"});continue}if(Q.nodes.length===0){if(!W)z6(L,{force:!0});V.push(Q.path);continue}let T=Q.created===!0,q=(_,M,E)=>{if(T&&M){if(!W)z6(L,{force:!0});V.push(`${Q.path} (${E}; file created by wire \u2014 deleted)`)}else{if(!W)R7(L,_);V.push(`${Q.path} (${E})`)}};if(Q.path.endsWith(".md")){let _=JW(B,m1,u1);q(_,_.trim().length===0,"the myc block");continue}if(Q.path.endsWith(".toml")){let _=JW(B,Eq,vq);_=JW(_,YW,zW),q(_,_.trim().length===0,"the myc blocks");continue}let j=o9(L);if(j.broken){G.push({path:Q.path,reason:"not valid JSON"});continue}let O=K.status_line,A=O!==void 0&&O!==null&&O.path===Q.path?O:void 0,R=new Set(Array.isArray(Q.preexisting)?Q.preexisting:[]),D=z90(j.value,A,R),F=Y6(j.value.statusLine)&&A?.previous!==void 0&&A.previous!==null?"; previous statusLine restored":"",P={...D};if(T){let _=P.$schema;if(_===A3||_===dg)delete P.$schema}q(yq(D,j.indent),Object.keys(P).length===0,`${Q.nodes.join(", ")}${F}`)}if(!W&&G.length===0)z6(J,{force:!0});if(!W){let Q=_7(z),L=new Set;for(let B of K.entries){let T=m$(_7(Q,B.path));while(T.startsWith(`${Q}/`))L.add(T),T=m$(T)}for(let B of[...L].sort((T,q)=>q.length-T.length))try{lg(B),V.push(`${cg(Q,B)}/ (empty directory left by wire \u2014 removed)`)}catch{}}return{ok:!0,data:{removed:V,kept:G,gone:H,dry_run:W}}},renderHuman:(Z)=>{let Y=Z,z=[Y.dry_run?"would remove:":"removed:"];for(let J of Y.removed)z.push(` - ${J}`);for(let J of Y.kept)z.push(` ! ${J.path}: ${J.reason}`);for(let J of Y.gone)z.push(` \xB7 ${J}: file already gone`);if(Y.removed.length===0)z.push(" (nothing to remove)");return`${z.join(`
|
|
8763
8763
|
`)}
|
|
8764
8764
|
`}}}function n9($){return $!==void 0&&$.length>0?$:void 0}function R3($){let X=n9($.HOME)??n9($.USERPROFILE);if(X===void 0)return null;let Z=n9($.CLAUDE_CONFIG_DIR),Y=Z??H0(X,".claude"),z=H0(Y,"helpers"),J=H0(n9($.XDG_CONFIG_HOME)??H0(X,".config"),"opencode");return{opencodeDir:J,opencodePlugin:H0(J,"plugin","myc.ts"),home:X,claudeDir:Y,settings:H0(Y,"settings.json"),helpersDir:z,helper:H0(z,ig),queueHelper:H0(z,j3),skill:H0(Y,"skills","myc","SKILL.md"),claudeJson:H0(Z??X,".claude.json"),journal:eK($)??H0(X,".myc",tK)}}function Wb($,X=i6){let Z=n9($.MYC_BIN);if(Z!==void 0&&X(_7(Z)))return{command:_7(Z),source:"env"};let Y=n9($.HOME);if(Y!==void 0&&X(H0(Y,".myc/bin/myc")))return{command:H0(Y,".myc/bin/myc"),source:"home"};for(let z of($.PATH??"").split(":"))if(z.length>0&&kq(z)&&X(H0(z,"myc")))return{command:H0(z,"myc"),source:"path"};return{command:"myc",source:"none"}}function Hb($){for(let X of($.PATH??"").split(":"))if(X.length>0&&i6(H0(X,"claude")))return H0(X,"claude");return null}function bq($,X,Z){try{let Y=Bun.spawnSync([$,...X],{env:Z,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:60000}),z=`${Y.stdout.toString()}${Y.stderr.toString()}`.trim().split(`
|
|
8765
|
-
`).filter((J)=>J.length>0).pop()??"";return{code:Y.exitCode??-1,out:z}}catch(Y){return{code:-1,out:Y instanceof Error?Y.message:String(Y)}}}function A4($){return["claude",...$].map(i5).join(" ")}function iq($){let X=m0($);if(X===null)return{value:void 0,broken:!1};try{let Z=JSON.parse(X);if(!$$(Z))return{value:void 0,broken:!0};let Y=Q0(Z.mcpServers)[Y8];return{value:$$(Y)?Y:void 0,broken:!1}}catch{return{value:void 0,broken:!0}}}function wq($,X){let Z=$,Y=Z.type;return(Y===void 0||Y==="stdio")&&Z.command===X.command&&JSON.stringify(G$(Z.args))===JSON.stringify(X.args)}function
|
|
8765
|
+
`).filter((J)=>J.length>0).pop()??"";return{code:Y.exitCode??-1,out:z}}catch(Y){return{code:-1,out:Y instanceof Error?Y.message:String(Y)}}}function A4($){return["claude",...$].map(i5).join(" ")}function iq($){let X=m0($);if(X===null)return{value:void 0,broken:!1};try{let Z=JSON.parse(X);if(!$$(Z))return{value:void 0,broken:!0};let Y=Q0(Z.mcpServers)[Y8];return{value:$$(Y)?Y:void 0,broken:!1}}catch{return{value:void 0,broken:!0}}}function wq($,X){let Z=$,Y=Z.type;return(Y===void 0||Y==="stdio")&&Z.command===X.command&&JSON.stringify(G$(Z.args))===JSON.stringify(X.args)}function U90($,X){let Z=i5(X),Y=`if [ -f ${Z} ]; then node ${Z} ${$.event}; else cat >/dev/null; fi`;return{...$.matcher!==void 0?{matcher:$.matcher}:{},hooks:[{type:"command",command:Y,timeout:pq($)}]}}function K90($,X){let Z=_q(X),Y=`f="\${CLAUDE_PROJECT_DIR:-.}/${F3}"`,z=Rq(X);if(!z.startsWith(Y))throw Error(`queue hook command no longer starts with ${Y}: the user-scope path substitution is out of date`);let J=`f=${i5($)}${z.slice(Y.length)}`;return{...Z,hooks:G$(Z.hooks).map((U)=>({...Q0(U),command:J}))}}function P3($,X){return G$(Q0($).hooks).some((Z)=>{let Y=Q0(Z).command;return typeof Y==="string"&&X.some((z)=>Y.includes(z))})}function Qb($,X,Z){let Y=$.endsWith(`
|
|
8766
8766
|
`);return{ok:`${JSON.stringify(X,null,Z)}${Y?`
|
|
8767
|
-
`:""}`===$,newline:Y}}function
|
|
8767
|
+
`:""}`===$,newline:Y}}function W90($,X,Z){let Y=[],z=$.hooks;if($$(z)){let U=!1;for(let[K,W]of Object.entries(z)){let V=G$(W).some((G)=>P3(G,X));if(U=U||V,Array.isArray(W)&&!V)Y.push(`hooks.${K}`)}if(!U)Y.push("hooks")}let J=$.permissions;if($$(J)){let U=J.allow,K=Array.isArray(U)&&U.some((W)=>Z.includes(W));if(Array.isArray(U)&&!K)Y.push("permissions.allow");if(!K)Y.push("permissions")}return Y}function XW($,X){return[...new Set([...$,...X])]}function _3($){let X=m0($);if(X===null)return null;try{let Z=JSON.parse(X);if(!$$(Z)||Z.scope!=="user"||!Array.isArray(Z.files))return null;let{status_line:Y,opencode:z}=Z,J=$$(z)&&typeof z.config==="string"&&typeof z.plugin==="string";return{v:1,scope:"user",written_at:typeof Z.written_at==="number"?Z.written_at:Number.NaN,hook_output:Z.hook_output==="text"?"text":"json",files:Z.files,dirs:Array.isArray(Z.dirs)?Z.dirs:[],settings:$$(Z.settings)?Z.settings:null,mcp:$$(Z.mcp)?Z.mcp:null,...typeof Z.version==="string"?{version:Z.version}:{},...typeof Z.bin==="string"?{bin:Z.bin}:{},...Array.isArray(Z.events)?{events:Z.events.filter((U)=>typeof U==="string")}:{},...$$(Y)?{status_line:{previous:Y.previous??null}}:{},...J?{opencode:V90(z)}:{}}}catch{return null}}function V90($){let X=$.mcp,Z=$$(X)?G$(X.command):[],Y=$.backup;return{config:$.config,created:$.created===!0,container:$.container===!0,mcp:Z.length>0&&Z.every((z)=>typeof z==="string")?{command:Z}:null,plugin:$.plugin,bin:typeof $.bin==="string"?$.bin:"myc",version:typeof $.version==="string"?$.version:"",...$$(Y)&&typeof Y.path==="string"&&typeof Y.hash==="string"?{backup:{path:Y.path,hash:Y.hash}}:{}}}function s9($,X,Z,Y,z=Y){return{opencodePlugin:nM({events:X,hookOutput:Z,selfPath:$.opencodePlugin,mycBin:z}),helper:wM({events:X,hookOutput:Z,selfDir:$.helpersDir,mycBin:Y}),queueHelper:xM(Mq(),$.helpersDir,j3,"// User-layer copy, generated by `myc wire --scope user --queue-hook`: the same helper behind a guard that lets it act only in a myc workspace whose project does not run its own queue hook."),skill:X9()}}function nq($,X){return P3($,X)}function dq($){return iq($)}function Nb($,X){return $===X?"~":$.startsWith(`${X}/`)?`~${$.slice(X.length)}`:$}function UW($,X,Z){let Y=m0(X);if(Y===Z){$.push({path:X,kind:"unchanged",content:Z,detail:"up to date"});return}$.push({path:X,kind:Y===null?"new":"rewrite",content:Z,detail:`${(Buffer.byteLength(Z,"utf8")/1024).toFixed(1)} KB`})}function G90($,X,Z,Y,z){let J={command:X.command,args:gq},U=["mcp","add","--scope","user",Y8,"--",X.command,...gq],K={server:J,add:U},W=iq($.claudeJson);if(W.broken)return{...K,state:"refused",oursBefore:!1,reason:`${$.claudeJson} is not valid JSON \u2014 can't tell whether myc is registered`};let V=Z?.mcp,G=V?.added===!0&&W.value!==void 0&&wq(W.value,{command:V.command,args:V.args});if(W.value!==void 0&&wq(W.value,J))return{...K,state:"unchanged",oursBefore:G};if(W.value!==void 0&&!G){let N=[W.value.command,...G$(W.value.args)].map(String).join(" ");return{...K,state:"foreign",oursBefore:G,reason:`mcpServers.myc in ${$.claudeJson} was not registered by myc wire (${N}) \u2014 left alone`}}let H=Y();if(!H.ok)return{...K,state:"refused",oursBefore:G,reason:H.why};if(z===null)return{...K,state:"refused",oursBefore:G,reason:"claude is not on PATH"};return{...K,state:W.value===void 0?"add":"replace",oursBefore:G}}function H90($,X){let Z=$.statusLine,Y=Y6(Z),z=[],J=(N)=>{let Q=Z8(N);if(Q===null)return"a line without a command";return`"${a5(Q)}"${rK(Q)?" (orca's line)":""}`},U=`${X.rel}: myc's statusLine is there with no record of the previous one in ${X.journal} \u2014 unwire will remove it and has nothing to restore`;if(!X.want){if(Y){if(X.recorded===void 0)z.push(U);return{record:X.recorded??{previous:null},notes:z,node:!1}}if(X.recorded!==void 0)z.push(Z===void 0?`${X.rel}: myc's statusLine was removed after wire \u2014 its record is dropped; \`myc wire --scope user --status-line\` puts it back`:`${X.rel}: myc's statusLine was replaced after wire by ${J(Z)} \u2014 left alone and the record of ours dropped; `+"`myc wire --scope user --status-line` puts ours back, and that line keeps getting the same input as the previous one");return{notes:z,node:!1}}let K;if(Y){if(K=X.recorded?.previous??null,X.recorded===void 0)z.push(U)}else if(Z===void 0){if(K=X.recorded?.previous??null,X.recorded!==void 0)z.push(`${X.rel}: myc's statusLine was removed after wire \u2014 put back`)}else if(K=Z,X.recorded!==void 0)z.push(`${X.rel}: myc's statusLine was replaced after wire by ${J(Z)} \u2014 ours goes back, and that line becomes the previous one`);let W=aK(X.bin);if(W.includes(sK))return{conflict:`the command "${a5(W)}" contains "${sK}", so orca would take it for its own line and remove it`};if(!C4(W))return{conflict:`${X.bin.command} is not named myc, so its line could not be told from a foreign one \u2014 set MYC_BIN to a myc executable`};let V={type:"command",command:W},G=Q0(Y?Z:K);for(let N of["padding","refreshInterval"])if(typeof G[N]==="number")V[N]=G[N];if(!(Y&&JSON.stringify(Z)===JSON.stringify(V)))$.statusLine=V;let H=Z8(K);if(H!==null&&!C4(H))z.push(`${X.rel}: statusLine is myc's (myc statusline --scope user: the full line in a myc workspace, nothing of its own outside one); the previous line ${J(K)} is kept in ${X.journal} and gets the same stdin on every redraw \u2014 `+"neither awaited nor killed; unwire puts it back");else z.push(`${X.rel}: statusLine is myc's; there was no previous line \u2014 no one to pass input to`);return{record:{previous:K},notes:z,node:!0}}function p6($,X){let Z=X;for(;;){let Y=$[Z];if(Y===" "||Y==="\t"||Y===`
|
|
8768
8768
|
`||Y==="\r"||Y==="\uFEFF")Z++;else if($.startsWith("//",Z)){let z=$.indexOf(`
|
|
8769
8769
|
`,Z);Z=z===-1?$.length:z+1}else if($.startsWith("/*",Z)){let z=$.indexOf("*/",Z+2);if(z===-1)throw new d9(`unterminated comment at offset ${Z}`);Z=z+2}else return Z}}function oq($){let X=0,Z=(U)=>{throw new d9(`${U} at offset ${X}`)},Y=()=>{let U=X++;while(X<$.length){let K=$[X];if(K==="\\")X+=2;else if(K==='"')return JSON.parse($.slice(U,++X));else if(K===`
|
|
8770
8770
|
`)Z("newline in a string");else X++}return Z("unterminated string")},z=()=>{X=p6($,X);let U=X,K=$[X];if(K==="{"){X++;let V=[],G={};for(;;){if(X=p6($,X),$[X]==="}")return{kind:"object",start:U,end:++X,members:V,value:G};if($[X]!=='"')Z("expected a key");let H=X,N=Y();if(X=p6($,X),$[X]!==":")Z("expected ':'");X++;let Q=z();if(V.push({key:N,keyStart:H,node:Q}),Object.defineProperty(G,N,{value:Q.value,enumerable:!0,writable:!0,configurable:!0}),X=p6($,X),$[X]===",")X++;else if($[X]!=="}")Z("expected ',' or '}'")}}if(K==="["){X++;let V=[];for(;;){if(X=p6($,X),$[X]==="]")return{kind:"value",start:U,end:++X,value:V};if(V.push(z().value),X=p6($,X),$[X]===",")X++;else if($[X]!=="]")Z("expected ',' or ']'")}}if(K==='"'){let V=Y();return{kind:"value",start:U,end:X,value:V}}wg.lastIndex=X;let W=wg.exec($);if(W===null)return Z("unexpected token");return X+=W[0].length,{kind:"value",start:U,end:X,value:JSON.parse(W[0])}},J=z();if(p6($,X)!==$.length)Z("trailing content");return J}function D3($){return oq($).value}function C3($,X){let Z=$;for(let Y of[...X].sort((z,J)=>J.start-z.start))Z=`${Z.slice(0,Y.start)}${Y.text}${Z.slice(Y.end)}`;return Z}function xq($,X){let Z=$.lastIndexOf(`
|
|
@@ -8781,13 +8781,13 @@ ${G}${H}`}]}let U=xq($,X.start),K=`${U}${z}`,W=`${JSON.stringify(Z)}: ${hq(Y,K,z
|
|
|
8781
8781
|
${K}${W}
|
|
8782
8782
|
${U}`}];let V=Iq($,X.start+1);return[{start:V,end:V,text:`
|
|
8783
8783
|
${K}${W}`}]}function mg($,X,Z){let Y=X.members[Z],z=Y.keyStart;while(z>X.start+1&&($[z-1]===" "||$[z-1]==="\t"))z--;if(z>X.start+1&&$[z-1]===`
|
|
8784
|
-
`)z--;if(z>X.start+1&&$[z-1]==="\r")z--;let J=(K,W)=>/^\s*$/.test($.slice(K,W)),U=p6($,Y.node.end);if($[U]===","){if(X.members.length===1&&J(X.start+1,z)&&J(U+1,X.end-1))return[{start:X.start+1,end:X.end-1,text:""}];return[{start:z,end:U+1,text:""}]}if(Z>0){let K=p6($,X.members[Z-1].node.end);return[{start:K,end:K+1,text:""},{start:z,end:Y.node.end,text:""}]}if(J(X.start+1,z)&&J(Y.node.end,X.end-1))return[{start:X.start+1,end:X.end-1,text:""}];return[{start:z,end:Y.node.end,text:""}]}function
|
|
8785
|
-
`:
|
|
8786
|
-
`:""}`,d=T===u?"unchanged":T===null?"new":"merge",a=Hb(Z.env),e=
|
|
8787
|
-
`),
|
|
8784
|
+
`)z--;if(z>X.start+1&&$[z-1]==="\r")z--;let J=(K,W)=>/^\s*$/.test($.slice(K,W)),U=p6($,Y.node.end);if($[U]===","){if(X.members.length===1&&J(X.start+1,z)&&J(U+1,X.end-1))return[{start:X.start+1,end:X.end-1,text:""}];return[{start:z,end:U+1,text:""}]}if(Z>0){let K=p6($,X.members[Z-1].node.end);return[{start:K,end:K+1,text:""},{start:z,end:Y.node.end,text:""}]}if(J(X.start+1,z)&&J(Y.node.end,X.end-1))return[{start:X.start+1,end:X.end-1,text:""}];return[{start:z,end:Y.node.end,text:""}]}function L90($){return/\n([ \t]+)\x22/.exec($)?.[1]??" "}function B90($,X){let Z=oq($);if(Z.kind!=="object")throw new d9("the top level is not an object");let Y=L90($),z=xg(Z,"mcp");if(z===void 0)return C3($,hg($,Z,"mcp",{[Y8]:X},Y));if(z.node.kind!=="object")throw new d9('"mcp" is not an object');let J=xg(z.node,Y8);if(J===void 0)return C3($,hg($,z.node,Y8,X,Y));let U=Tb($,J.keyStart)??xq($,J.keyStart);return C3($,[{start:J.node.start,end:J.node.end,text:hq(X,U,Y)}])}function T90($,X){let Z=oq($);if(Z.kind!=="object")throw new d9("the top level is not an object");let Y=Z.members.map((U)=>U.key).lastIndexOf("mcp"),z=Z.members[Y];if(z===void 0||z.node.kind!=="object")return $;let J=z.node.members.map((U)=>U.key).lastIndexOf(Y8);if(J===-1)return $;if(X&&z.node.members.length===1)return C3($,mg($,Z,Y));return C3($,mg($,z.node,J))}function WW($,X){return $$($)&&$.type==="local"&&JSON.stringify($.command)===JSON.stringify(X)}function q90($){for(let X of["opencode.jsonc","opencode.json","config.json"])if(i6(H0($,X)))return H0($,X);return H0($,"opencode.json")}function aq($){let X=m0($);if(X===null)return{value:void 0,broken:!1,exists:!1};try{let Z=D3(X);return{value:$$(Z)?Q0(Z.mcp)[Y8]:void 0,broken:!$$(Z),exists:!0}}catch{return{value:void 0,broken:!0,exists:!0}}}function sq($,X){return WW($,X)}function F90($){let{paths:X,prev:Z,bin:Y,show:z}=$,J=[],U=[];UW(U,X.opencodePlugin,s9(X,$.events,$.hookOutput,Y.command).opencodePlugin);let K=Z?.opencode,W=K!==void 0&&i6(K.config)?K.config:q90(X.opencodeDir),V=m0(W),G={};if(V!==null){let F;try{F=D3(V)}catch(P){return{failure:M0("conflict.opencode_config",`${W} is not valid JSONC (${P instanceof Error?P.message:String(P)}) \u2014 nothing written`,4)}}if(!$$(F))return{failure:M0("conflict.opencode_config",`${W}: the top level is not an object \u2014 nothing written`,4)};if(G=F,G.mcp!==void 0&&!$$(G.mcp))return{failure:M0("conflict.opencode_config",`${W}: "mcp" is not an object \u2014 nothing written`,4)}}let H={type:"local",command:[Y.command,...gq],enabled:!0},N=Q0(G.mcp)[Y8],Q=K!==void 0&&K.config===W,L=Q&&K.mcp!==null&&WW(N,K.mcp.command),B=Q&&K.mcp!==null?K.container:G.mcp===void 0,T={path:W,before:V},q=(F,P)=>({files:U,config:{...T,after:V??"",kind:"unchanged",detail:F==="unchanged"?"up to date":F==="foreign"?"mcp.myc is someone else's \u2014 left alone":"mcp.myc not written (see the warning)"},mcp:{state:F,command:H.command,...P!==void 0?{reason:P}:{}},container:B,oursBefore:L,notes:J});if(WW(N,H.command)){if(Q0(N).enabled===!1)J.push(`${z(W)}: mcp.myc is myc's but disabled by hand ("enabled": false) \u2014 left as is`);return q("unchanged")}if(N!==void 0&&!L){let F=`mcp.myc in ${z(W)} was not written by myc wire (${JSON.stringify(N)}) \u2014 left alone`;return J.push(F),q("foreign",F)}let j=$.probe();if(!j.ok)return q("refused",j.why);let O=N===void 0?"add":"replace",A;try{A=V===null?`${JSON.stringify({$schema:A3,mcp:{[Y8]:H}},null,2)}
|
|
8785
|
+
`:B90(V,H)}catch(F){return{failure:M0("conflict.opencode_config",`${W}: ${F instanceof Error?F.message:String(F)} \u2014 nothing written`,4)}}let R=structuredClone(G);if(R.mcp={...Q0(R.mcp),[Y8]:H},V===null)R.$schema=A3;let D;try{D=D3(A)}catch{D=void 0}if(V!==null&&JSON.stringify(D)!==JSON.stringify(R))return{failure:M0("conflict.opencode_config",`${W}: mcp.myc can't be placed without touching other entries \u2014 nothing written`,4,`add it by hand under "mcp": "myc": ${JSON.stringify(H)}`)};return{files:U,config:{...T,after:A,kind:V===null?"new":"merge",detail:`+1 node: mcp.myc${O==="replace"?" (re-pointed)":""}`},mcp:{state:O,command:H.command},container:B,oursBefore:L,notes:J}}function j90($,X,Z,Y){let{paths:z,prev:J,bin:U,events:K,mode:W,wantStatusLine:V,show:G}=Y,H=[],N=[],Q=[],L=null;if($.flags["queue-hook"]===!0){let r=Z.probeQueue(z.claudeDir,Z.env,"user");if(!r.ok)return{failure:M0("precond.queue_bin",`nowhere to queue heavy commands through: ${r.why}. A hook on a myc without \`run\` would turn every heavy `+"command into an error \u2014 nothing written",5,"MYC_BIN=<path to a fresh myc> myc wire --scope user --queue-hook")};L=r.bin}if(V){let r=Z.probeUserStatusLine(U,Z.env);if(!r.ok)return{failure:M0("precond.statusline_bin",`nowhere to install the status line: ${r.why}. A line on that binary would show nothing and cut the `+"previous line off from its input \u2014 nothing written",5,"MYC_BIN=<path to a fresh myc> myc wire --scope user --status-line")}}let B=s9(z,K,Y.hookOutput,U.command);UW(Q,z.helper,B.helper),UW(Q,z.skill,B.skill);let T=m0(z.settings),q=o9(z.settings);if(q.broken)return{failure:M0("conflict.user_settings",`${z.settings} is not valid JSON \u2014 nothing written`,4)};let j=T===null?{ok:!0,newline:!0}:Qb(T,q.value,q.indent);if(!j.ok)return{failure:M0("conflict.user_settings",`${z.settings} is not laid out the way JSON.stringify writes it (indent ${JSON.stringify(q.indent)}), so a `+"node-by-node merge would reformat other tools' entries \u2014 nothing written",4,"let Claude Code or orca rewrite the file (e.g. change any setting in /config), then run wire again")};let O=[z.helper,z.queueHelper],A=(r)=>P3(r,O),R=Y$.filter((r)=>K.includes(r.event)).map((r)=>({event:r.claudeEvent,entry:U90(r,z.helper)})),D=null;for(let r of G$(Q0(q.value.hooks).PreToolUse))if(P3(r,[z.queueHelper]))D=Q0(r);if(L!==null)D=K90(z.queueHelper,L.command),H.push(`${G(z.settings)}: hooks.PreToolUse[Bash] \u2014 in a myc workspace a heavy command goes through \`myc run -- \u2026\` `+`with ${L.command} (${L.source}); approved without asking only when your own rules allow the original command`);let F=R.length;if(D!==null)R.push({event:"PreToolUse",entry:D}),UW(Q,z.queueHelper,B.queueHelper);else N.push(`${G(z.settings)}:hooks.PreToolUse (needs --queue-hook)`);let P={...q.value},_=Q0(P.hooks),M=[],E=[];for(let[r,{event:c,entry:l}]of R.entries()){let m=G$(_[c]),n=m.filter((q0)=>!A(q0)),X0=m.length>n.length;if(!X0&&n.length>0&&W==="skip"){H.push(`${G(z.settings)}: hooks.${c} \u2014 a foreign hook is there, myc's not installed (--hook-mode skip)`);continue}if(r<F)E.push(c);let _0;if(X0){_0=[];let q0=!1;for(let P0 of m)if(!A(P0))_0.push(P0);else if(!q0)_0.push(l),q0=!0}else if(_0=[...m,l],n.length>0)H.push(`${G(z.settings)}: hooks.${c} \u2014 ${n.length} foreign ${n.length===1?"entry stays":"entries stay"} byte for byte; Claude Code runs them and myc's side by side`);if(_[c]=_0,!KW(m,_0))M.push(`hooks.${c}`)}if(M.length>0)P.hooks=_;let b=M3(X),k=Q0(P.permissions),y=G$(k.allow),g=b.filter((r)=>!y.includes(r));if(g.length>0)k.allow=[...y,...g],P.permissions=k,M.push(`permissions.allow[${g.length===1?g[0]:`Bash(myc <command>:*) \xD7${g.length}`}]`);let S=y.find((r)=>r===o5||r==="Bash(myc run:*)");if(S!==void 0)H.push(`${G(z.settings)}: permissions.allow has ${String(S)}, so \`myc run -- <any command>\` runs without asking `+"in every project; wire did not write it and leaves it alone \u2014 remove it by hand");let w=P.statusLine,h=H90(P,{want:V,recorded:J?.status_line,bin:U,rel:G(z.settings),journal:G(z.journal)});if("conflict"in h)return{failure:M0("conflict.status_line",`status line not installed, nothing written: ${h.conflict}`,4)};if(H.push(...h.notes),h.node&&!KW(w,P.statusLine))M.push("statusLine");if(!V&&h.record===void 0)N.push(`${G(z.settings)}:statusLine (needs --status-line)`);let u=`${JSON.stringify(P,null,q.indent)}${j.newline?`
|
|
8786
|
+
`:""}`,d=T===u?"unchanged":T===null?"new":"merge",a=Hb(Z.env),e=G90(z,U,J,Y.probe,a);if(e.state!=="unchanged"&&e.state!=="foreign")H.push(`${G(z.claudeJson)} is written by \`claude mcp\` itself (it keeps its own backup under ${G(z.claudeDir)}/backups); running sessions rewrite that file, so myc only reads it`);if(e.state==="foreign"&&e.reason!==void 0)H.push(e.reason);return{files:Q,settingsText:T,settingsContent:u,settingsKind:d,settingsDetail:M.length>0&&d!=="unchanged"?`+${uq(M.length)}: ${M.join(", ")}`:"up to date",source:q,helpers:O,addedRules:g,placedEvents:E,statusLine:h.record,mcp:e,claude:a,notes:H,untouched:N}}function O90($,X,Z){let Y=(g)=>M0("usage.scope",g,2),z=Bb,J=f($,"agents");if(J!==void 0){let g=Kb(J);if(g===null)return M0("usage.invalid",`--agents takes ${o0.join(", ")}`,2);let S=g.filter((w)=>!bg.includes(w));if(S.length>0)return Y(`--scope user wires Claude Code and opencode only; ${S.join(", ")} ${S.length===1?"is":"are"} not implemented `+`in the user layer \u2014 wire them per project: myc wire --agents ${S.join(",")}`);z=g}let U=Q90(z),K=N90(z),W=$.flags["status-line"]===!0;if($.flags["agents-md"]===!0)return Y("--agents-md is not available with --scope user: AGENTS.md is a project file");let V=f($,"hook-mode");if(V==="replace")return Y("--hook-mode replace is not available with --scope user: it would evict other tools' hooks (orca, herdr, \u2026) "+"from every project on the machine. The default, append, keeps them and adds myc's alongside; skip leaves an event alone when a foreign hook is there");if(V!==void 0&&V!=="append"&&V!=="skip")return M0("usage.invalid","--hook-mode takes append or skip with --scope user",2);let G=V==="skip"?"skip":"append",H=f($,"hook-output")??"json";if(H!=="json"&&H!=="text")return M0("usage.invalid","--hook-output takes json or text",2);if(Z.platform==="win32")return M0("precond.platform","--scope user is not implemented on Windows: its hook commands are POSIX shell, checked on macOS and Linux only",5);let N=R3(Z.env);if(N===null)return M0("precond.no_home","HOME is not set: no user layer of Claude Code to wire",5);let{available:Q,skipped:L}=Ub(X);if(!Q.includes("pre-compact"))return M0("precond.missing_command","no `myc absorb-session` command \u2014 nothing to install pre-compact on",5);let B=N.home,T=(g)=>Nb(g,B),q=_3(N.journal),j=Wb(Z.env),O=[],A=[],R,D=()=>R??=Z.probeMcp(j,Z.env);if(!U){if(W)O.push("the status line is installed only for Claude Code, which is not in --agents \u2014 statusLine left alone");if($.flags["queue-hook"]===!0)O.push("the queue hook is installed only for Claude Code, which is not in --agents \u2014 hooks.PreToolUse left alone")}let F=U?j90($,X,Z,{paths:N,prev:q,bin:j,events:Q,hookOutput:H,mode:G,wantStatusLine:W,probe:D,show:T}):null;if(F!==null&&"failure"in F)return F.failure;let P=K?F90({paths:N,prev:q,bin:j,events:Q,hookOutput:H,probe:D,show:T}):null;if(P!==null&&"failure"in P)return P.failure;if(F!==null)O.push(...F.notes),A.push(...F.untouched);if(P!==null){if(W)O.push("opencode: status line not installed \u2014 there is no config key for it, the TUI draws its own line");O.push(...P.notes)}let _=[...F?.files??[],...P?.files??[]],M=$.flags["dry-run"]===!0,E=F===null?void 0:{state:F.mcp.state,command:A4(F.mcp.add),...F.mcp.reason!==void 0?{reason:F.mcp.reason}:{}},b=null;if(!M){if(F!==null&&m0(N.settings)!==F.settingsText)return M0("conflict.user_settings_changed",`${N.settings} changed while wire was planning \u2014 nothing written`,4,"myc wire --scope user");if(P!==null&&m0(P.config.path)!==P.config.before)return M0("conflict.opencode_config_changed",`${P.config.path} changed while wire was planning \u2014 nothing written`,4,"myc wire --scope user --agents opencode");let S=[...F!==null?[N.claudeDir,N.helpersDir,m$(m$(N.skill)),m$(N.skill)]:[],...P!==null?[N.opencodeDir,m$(N.opencodePlugin)]:[],m$(N.journal)].filter((l)=>!i6(l)),w=[];for(let l of _){if(l.kind==="unchanged")continue;i9(m$(l.path),{recursive:!0});let m=m0(l.path);if(m!==null)ZW(l.path,`${l.path}${d5}`),w.push({path:`${l.path}${d5}`,hash:c6(m)});R7(l.path,l.content)}let h=q?.settings?.backup;if(F!==null&&F.settingsKind!=="unchanged"){if(i9(m$(N.settings),{recursive:!0}),F.settingsText!==null){let l=`${N.settings}${d5}`;ZW(N.settings,l),h={path:l,hash:c6(F.settingsText)}}R7(N.settings,F.settingsContent)}let u=P!==null&&q?.opencode?.config===P.config.path?q.opencode:void 0,d=u?.backup;if(P!==null&&P.config.kind!=="unchanged"){if(i9(m$(P.config.path),{recursive:!0}),P.config.before!==null){let l=`${P.config.path}${d5}`;ZW(P.config.path,l),d={path:l,hash:c6(P.config.before)}}R7(P.config.path,P.config.after)}let a=F!==null&&F.mcp.state==="unchanged"?F.mcp.oursBefore:!1;if(F!==null&&(F.mcp.state==="add"||F.mcp.state==="replace")&&F.claude!==null){let l=!0;if(F.mcp.state==="replace"){let m=bq(F.claude,["mcp","remove","--scope","user",Y8],Z.env);if(m.code!==0)l=!1,E={state:"failed",command:A4(F.mcp.add),reason:`claude mcp remove: exit ${m.code}${m.out.length>0?` (${m.out})`:""}`}}if(l){let m=bq(F.claude,F.mcp.add,Z.env);if(m.code===0)a=!0,E={state:"added",command:A4(F.mcp.add)};else E={state:"failed",command:A4(F.mcp.add),reason:`exit ${m.code}${m.out.length>0?` (${m.out})`:""}`}}}let e=F===null?{settings:q?.settings??null,mcp:q?.mcp??null,...q?.version!==void 0?{version:q.version}:{},...q?.bin!==void 0?{bin:q.bin}:{},...q?.events!==void 0?{events:q.events}:{},...q?.status_line!==void 0?{status_line:q.status_line}:{}}:(()=>{let l=XW(q?.settings?.permissions??[],F.addedRules);return{settings:{path:N.settings,created:q?.settings?.created??F.settingsText===null,preexisting:XW(q?.settings?.preexisting??[],W90(F.source.value,F.helpers,l)),permissions:l,helpers:XW(q?.settings?.helpers??[],F.helpers),...h!==void 0?{backup:h}:{}},mcp:a||F.mcp.state==="unchanged"?{config:N.claudeJson,command:F.mcp.server.command,args:F.mcp.server.args,added:a}:q?.mcp??null,version:E0,bin:j.command,events:F.placedEvents,...F.statusLine!==void 0?{status_line:F.statusLine}:{}}})(),r=q?.opencode;if(P!==null){let l=P.mcp.state==="add"||P.mcp.state==="replace"||P.mcp.state==="unchanged"&&P.oursBefore;r={config:P.config.path,created:u!==void 0&&u.mcp!==null?u.created:P.config.kind==="new",container:P.container,mcp:l?{command:P.mcp.command}:P.oursBefore&&u!==void 0?u.mcp:null,plugin:N.opencodePlugin,bin:j.command,version:E0,...d!==void 0?{backup:d}:{}}}let c={v:1,scope:"user",written_at:Date.now(),hook_output:F!==null?H:q?.hook_output??H,files:[...(q?.files??[]).filter((l)=>!_.some((m)=>m.path===l.path)&&!w.some((m)=>m.path===l.path)),..._.map((l)=>({path:l.path,hash:c6(l.content)})),...w],dirs:XW(q?.dirs??[],S),settings:null,mcp:null,...e,...r!==void 0?{opencode:r}:{}};try{i9(m$(N.journal),{recursive:!0});let l=`${N.journal}.${process.pid}.tmp`;R7(l,`${JSON.stringify(c,null,2)}
|
|
8787
|
+
`),gX0(l,N.journal),b=N.journal}catch(l){$.warn("degraded.journal",`journal ${N.journal} not written (${l instanceof Error?l.message:String(l)}): myc unwire --scope user won't be able to remove the hooks`)}}for(let g of L)$.warn("degraded.hook_missing",`hook ${g.event} not installed: ${g.reason}`);if(j.source==="none"){let g=[F!==null?"the helper":"",P!==null?"the opencode plugin and its MCP server":""].filter((S)=>S.length>0).join(" and ");$.warn("degraded.bin_unresolved",`no myc executable found: not in MYC_BIN, ~/.myc/bin/myc or PATH \u2014 ${g} fall back to \`myc\` on the session's PATH`)}if(E!==void 0&&(E.state==="refused"||E.state==="failed"))$.warn("degraded.mcp_unregistered",`MCP server myc ${M?"would not be":"not"} registered in the user layer: ${E.reason??"unknown reason"}. Hooks, skill and permissions ${M?"would be":"are"} in place; to register it yourself: ${E.command}`);if(P!==null&&P.mcp.state==="refused")$.warn("degraded.opencode_mcp_unwritten",`mcp.myc ${M?"would not be":"not"} written to ${P.config.path}: ${P.mcp.reason??"unknown reason"}. The plugin ${M?"would be":"is"} in place; to add the server yourself, put under "mcp" in that file: "myc": ${JSON.stringify({type:"local",command:P.mcp.command,enabled:!0})}`);let k=[..._.map((g)=>({path:g.path,action:g.kind,detail:g.detail})),...F!==null?[{path:N.settings,action:F.settingsKind,detail:F.settingsDetail}]:[],...P!==null?[{path:P.config.path,action:P.config.kind,detail:P.config.detail}]:[]];return{ok:!0,data:{scope:"user",home:B,agents:bg.filter((g)=>z.includes(g)),events:Q,skipped_events:L,actions:k,...E!==void 0?{mcp:E}:{},...P!==null?{opencode:{config:P.config.path,mcp:{state:P.mcp.state,command:P.mcp.command.join(" "),...P.mcp.reason!==void 0?{reason:P.mcp.reason}:{}}}}:{},untouched:A,notes:O,dry_run:M,changed:k.filter((g)=>g.action!=="unchanged").length+(F!==null&&(F.mcp.state==="add"||F.mcp.state==="replace")?1:0),journal:b}}}function C90($){let X=(J)=>Nb(J,$.home),Z=($.agents??Bb).map((J)=>Lb[J]??J).join(" and "),Y=[$.dry_run?`would write (user layer of ${Z}):`:`written (user layer of ${Z}):`],z=Math.max(...$.actions.map((J)=>X(J.path).length),10);for(let J of $.actions)Y.push(` ${J.action.padEnd(9)} ${X(J.path).padEnd(z)} ${J.detail}`);if($.mcp!==void 0){let J={add:$.dry_run?`would run: ${$.mcp.command}`:$.mcp.command,replace:$.dry_run?`would re-register: ${$.mcp.command}`:$.mcp.command,added:$.mcp.command,unchanged:"already registered",foreign:"someone else's server named myc \u2014 left alone",refused:`not registered: ${$.mcp.reason??""}`,failed:`failed: ${$.mcp.reason??""}`};Y.push(` ${($.mcp.state==="added"?"register":$.mcp.state).padEnd(9)} ${"MCP server myc (user)".padEnd(z)} ${J[$.mcp.state]}`)}if($.opencode!==void 0){let J=$.opencode.mcp,U={add:`${$.dry_run?"would write":"written"} to ${X($.opencode.config)}: ${J.command}`,replace:`${$.dry_run?"would re-point":"re-pointed"} in ${X($.opencode.config)}: ${J.command}`,unchanged:`already in ${X($.opencode.config)}`,foreign:"someone else's server named myc \u2014 left alone",refused:`not written: ${J.reason??""}`};Y.push(` ${J.state.padEnd(9)} ${"MCP server myc (opencode)".padEnd(z)} ${U[J.state]}`)}if($.untouched.length>0)Y.push(`untouched: ${$.untouched.join(", ")}`);for(let J of $.notes)Y.push(`! ${J}`);if($.journal!==null)Y.push(`journal: ${X($.journal)} (for myc unwire --scope user)`);if($.dry_run)Y.push("nothing written (--dry-run)");else if($.changed===0)Y.push("everything already in place, no files touched");return`${Y.join(`
|
|
8788
8788
|
`)}
|
|
8789
|
-
`}function
|
|
8790
|
-
`:""}`);J.push(`${V.path} (${q.nodes.join(", ")})`)}}}let L=V.backup;if(W&&L!==void 0){let B=m0(L.path);if(B!==null&&c6(B)===L.hash){if(!z)z6(L.path,{force:!0});J.push(L.path)}}}let G=Y.opencode;if(G!==void 0){let Q=!0,L=`${G.config}: mcp.myc`,B=G.mcp!==null?m0(G.config):null;if(G.mcp!==null&&B===null)K.push(G.config);if(G.mcp!==null&&B!==null){let q;try{q=D3(B)}catch{q=void 0}let j=$$(q)?Q0(q.mcp)[Y8]:void 0;if(!$$(q))Q=!1,U.push({path:G.config,reason:"not valid JSONC \u2014 mcp.myc left in place"});else if(j===void 0)K.push(L);else if(!WW(j,G.mcp.command))U.push({path:L,reason:"changed after wire wrote it \u2014 left alone"});else{let O=G.container&&Object.keys(Q0(q.mcp)).length===1,A=structuredClone(q);if(delete A.mcp[Y8],O)delete A.mcp;let R,D;try{R=
|
|
8789
|
+
`}function A90($,X,Z){let Y={...$},z=new Set(X.preexisting),J=[];if(Y6(Y.statusLine)){let V=Z?.previous;if(V!==void 0&&V!==null)Y.statusLine=V,J.push("statusLine (previous restored)");else delete Y.statusLine,J.push("statusLine")}let U=Q0(Y.hooks),K=!1;for(let V of Object.keys(U)){let G=G$(U[V]),H=G.filter((N)=>!P3(N,X.helpers));if(H.length===G.length)continue;if(K=!0,J.push(`hooks.${V}`),H.length===0&&!z.has(`hooks.${V}`))delete U[V];else U[V]=H}if(K)if(Object.keys(U).length===0&&!z.has("hooks"))delete Y.hooks;else Y.hooks=U;let W=Q0(Y.permissions);if(Array.isArray(W.allow)){let V=W.allow,G=V.filter((H)=>!X.permissions.includes(H));if(G.length!==V.length){if(J.push(`permissions.allow[${V.length-G.length}]`),G.length===0&&!z.has("permissions.allow"))delete W.allow;else W.allow=G;if(Object.keys(W).length===0&&!z.has("permissions"))delete Y.permissions;else Y.permissions=W}}return{value:Y,nodes:J}}function P90($,X){let Z=R3(X);if(Z===null)return M0("precond.no_home","HOME is not set: no user layer of Claude Code to unwire",5);let Y=_3(Z.journal);if(Y===null)return M0("notfound.journal",`no journal ${Z.journal}: nothing to remove`,3,"myc wire --scope user");let z=$.flags["dry-run"]===!0,J=[],U=[],K=[],W=!0,V=Y.settings;if(V!==null){let Q=m0(V.path);if(Q===null)K.push(V.path);else{let B=o9(V.path),T=B.broken?{ok:!1,newline:!0}:Qb(Q,B.value,B.indent);if(!T.ok)W=!1,U.push({path:V.path,reason:`${B.broken?"not valid JSON":"not laid out the way JSON.stringify writes it"} \u2014 stripping would reformat `+`other tools' entries; myc's entries left in place (hooks running ${V.helpers.join(", ")}; ${V.permissions.length} permissions.allow rules Bash(myc <command>:*))`});else{let q=A90(B.value,V,Y.status_line);if(q.nodes.length===0)J.push(`${V.path} (no myc entries left)`);else if(V.created&&Object.keys(q.value).length===0){if(!z)z6(V.path,{force:!0});J.push(`${V.path} (${q.nodes.join(", ")}; file created by wire \u2014 deleted)`)}else{if(!z)R7(V.path,`${JSON.stringify(q.value,null,B.indent)}${T.newline?`
|
|
8790
|
+
`:""}`);J.push(`${V.path} (${q.nodes.join(", ")})`)}}}let L=V.backup;if(W&&L!==void 0){let B=m0(L.path);if(B!==null&&c6(B)===L.hash){if(!z)z6(L.path,{force:!0});J.push(L.path)}}}let G=Y.opencode;if(G!==void 0){let Q=!0,L=`${G.config}: mcp.myc`,B=G.mcp!==null?m0(G.config):null;if(G.mcp!==null&&B===null)K.push(G.config);if(G.mcp!==null&&B!==null){let q;try{q=D3(B)}catch{q=void 0}let j=$$(q)?Q0(q.mcp)[Y8]:void 0;if(!$$(q))Q=!1,U.push({path:G.config,reason:"not valid JSONC \u2014 mcp.myc left in place"});else if(j===void 0)K.push(L);else if(!WW(j,G.mcp.command))U.push({path:L,reason:"changed after wire wrote it \u2014 left alone"});else{let O=G.container&&Object.keys(Q0(q.mcp)).length===1,A=structuredClone(q);if(delete A.mcp[Y8],O)delete A.mcp;let R,D;try{R=T90(B,O),D=D3(R)}catch{R=null}if(R===null||JSON.stringify(D)!==JSON.stringify(A))Q=!1,U.push({path:L,reason:"can't be taken out without touching other entries \u2014 left in place"});else if(G.created&&Object.keys(A).every((F)=>F==="$schema"&&A[F]===A3)){if(!z)z6(G.config,{force:!0});J.push(`${L} (file created by wire \u2014 deleted)`)}else{if(!z)R7(G.config,R);J.push(L)}}}let T=G.backup;if(Q&&T!==void 0){let q=m0(T.path);if(q!==null&&c6(q)===T.hash){if(!z)z6(T.path,{force:!0});J.push(T.path)}}}for(let Q of Y.files){if(!W&&V!==null&&V.helpers.includes(Q.path)){U.push({path:Q.path,reason:`${V.path} still runs it`});continue}let L=m0(Q.path);if(L===null){K.push(Q.path);continue}if(c6(L)!==Q.hash){U.push({path:Q.path,reason:"changed after we wrote it \u2014 left alone"});continue}if(!z)z6(Q.path,{force:!0});J.push(Q.path)}let H=Y.mcp;if(H!==null&&H.added){let L=["mcp","remove","--scope","user",Y8],B=iq(H.config);if(B.value===void 0&&!B.broken)K.push("MCP server myc (user scope)");else if(B.broken||!wq(B.value??{},{command:H.command,args:H.args}))U.push({path:"MCP server myc (user scope)",reason:`${B.broken?`${H.config} is not valid JSON`:"changed after wire registered it"} \u2014 left alone`});else{let T=Hb(X);if(T===null)U.push({path:"MCP server myc (user scope)",reason:`claude is not on PATH \u2014 remove it yourself: ${A4(L)}`});else if(z)J.push(`MCP server myc (user scope): ${A4(L)}`);else{let q=bq(T,L,X);if(q.code===0)J.push(`MCP server myc (user scope): ${A4(L)}`);else U.push({path:"MCP server myc (user scope)",reason:`${A4(L)}: exit ${q.code}${q.out.length>0?` (${q.out})`:""}`})}}}if(!z&&U.length===0){z6(Z.journal,{force:!0});for(let Q of[...Y.dirs].sort((L,B)=>B.length-L.length))try{if(fX0(Q).length===0)lg(Q)}catch{}}return{ok:!0,data:{removed:J,kept:U,gone:K,dry_run:z}}}var P4="wire.json",d5=".myc.bak",ig="myc-hooks.mjs",o5="Bash(myc:*)",mq,Eq="# myc:notify:start",vq="# myc:notify:end",Sg=".codex/hooks.json",YW="# myc:mcp:start",zW="# myc:mcp:end",A3="https://opencode.ai/config.json",dg="https://mimo.xiaomi.com/mimocode/config.json",Xb,Zb,Z90,Yb=($,X)=>{if(X.source==="none")return{ok:!1,why:"no myc executable found"};let Z=X.source==="repo"?H0($,X.command):X.command;try{let Y=Bun.spawnSync([Z,n5,"--help"],{cwd:$,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:1e4});if(Y.exitCode===0&&Y.stdout.toString().includes(n5))return{ok:!0};let z=Y.stderr.toString().trim().split(`
|
|
8791
8791
|
`)[0]??"";return{ok:!1,why:`${X.command} ${n5} --help: exit ${Y.exitCode}${z.length>0?` (${z})`:""}`}}catch(Y){return{ok:!1,why:`${X.command} does not start: ${Y instanceof Error?Y.message:String(Y)}`}}},zb=($,X,Z="project")=>{let Y=[],z=X.MYC_BIN;if(z!==void 0&&z.length>0)Y.push({command:_7($,z),exe:_7($,z),source:"env"});for(let U of(X.PATH??"").split(":"))if(U.length>0&&i6(H0(U,"myc"))){Y.push({command:"myc",exe:H0(U,"myc"),source:"path"});break}for(let U of["node_modules/.bin/myc","dist/myc",".myc/bin/myc"])Y.push({command:U,exe:H0($,U),source:"repo"});if(X.HOME!==void 0&&X.HOME.length>0){let U=H0(X.HOME,".myc/bin/myc");Y.push({command:U,exe:U,source:"home"})}let J=[];for(let U of Y){if(!i6(U.exe)){if(U.source==="env")J.push(`MYC_BIN=${U.command} (no such file)`);continue}try{let K=Bun.spawnSync([U.exe,"run","--help"],{cwd:$,env:X,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:1e4});if(K.exitCode===0&&K.stdout.toString().includes("myc run"))return{ok:!0,bin:{command:Z==="user"?U.exe:U.command,source:U.source}};let W=K.stderr.toString().trim().split(`
|
|
8792
8792
|
`)[0]??"";J.push(`${U.command} run --help: exit ${K.exitCode}${W.length>0?` (${W})`:""}`)}catch(K){J.push(`${U.command} does not start: ${K instanceof Error?K.message:String(K)}`)}}return{ok:!1,why:J.length>0?`no myc here knows \`run\` \u2014 ${J.join("; ")}`:"no myc executable found in MYC_BIN, PATH, node_modules/.bin, dist, .myc/bin or ~/.myc/bin"}},Y8="myc",gq,Vb=($,X)=>{if($.source==="none")return{ok:!1,why:"no myc executable found (MYC_BIN, ~/.myc/bin/myc, PATH)"};let Z=ug(H0(pg(),"myc-wire-probe-"));try{let Y=[{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"myc-wire",version:"0"}}},{jsonrpc:"2.0",id:2,method:"tools/list"}],z=Bun.spawnSync([$.command,"mcp","--profile","agent"],{cwd:Z,env:{...X,CLAUDE_PROJECT_DIR:Z},stdin:Buffer.from(`${Y.map((V)=>JSON.stringify(V)).join(`
|
|
8793
8793
|
`)}
|
|
@@ -8795,15 +8795,15 @@ ${K}${W}`}]}function mg($,X,Z){let Y=X.members[Z],z=Y.keyStart;while(z>X.start+1
|
|
|
8795
8795
|
`))try{let G=JSON.parse(V);if(typeof G.id==="number")J.set(G.id,Q0(G.result))}catch{}let U=J.get(2);if(U===void 0||!Array.isArray(U.tools)){let V=z.stderr.toString().trim().split(`
|
|
8796
8796
|
`)[0]??"";return{ok:!1,why:`${$.command} mcp did not answer tools/list (exit ${z.exitCode}${V.length>0?`: ${V}`:""})`}}let K=U.tools.length,W=J.get(1)?.instructions!==void 0;if(K>0||W)return{ok:!1,why:`${$.command} mcp outside a myc workspace still serves ${K} tools${W?" and its instructions":""} \u2014 `+"an older build; registered for every project, it would put them into every session"};return{ok:!0}}catch(Y){return{ok:!1,why:`${$.command} mcp does not start: ${Y instanceof Error?Y.message:String(Y)}`}}finally{z6(Z,{recursive:!0,force:!0})}},Gb=($,X)=>{if($.source==="none")return{ok:!1,why:"no myc executable found (MYC_BIN, ~/.myc/bin/myc, PATH)"};let Z=ug(H0(pg(),"myc-wire-probe-sl-")),Y=[n5,"--scope","user","--no-pass"];try{let z=Bun.spawnSync([$.command,...Y],{cwd:Z,env:{...X,CLAUDE_PROJECT_DIR:Z},stdin:Buffer.from(`${JSON.stringify({session_id:"myc-wire-probe",cwd:Z,workspace:{current_dir:Z}})}
|
|
8797
8797
|
`),stdout:"pipe",stderr:"pipe",timeout:15000}),J=`${$.command} ${Y.join(" ")}`;if(z.exitCode!==0){let K=z.stderr.toString().trim().split(`
|
|
8798
|
-
`)[0]??"";return{ok:!1,why:`${J}: exit ${z.exitCode}${K.length>0?` (${K})`:""} \u2014 an older build`}}let U=z.stdout.toString().trim();if(U.length>0)return{ok:!1,why:`${J} prints "${a5(U)}" outside a myc workspace \u2014 an older build`};return{ok:!0}}catch(z){return{ok:!1,why:`${$.command} does not start: ${z instanceof Error?z.message:String(z)}`}}finally{z6(Z,{recursive:!0,force:!0})}},Lb,bg,Bb,K90=($)=>$.includes("claude"),W90=($)=>$.includes("opencode"),d9,wg;var GW=v(()=>{V0();j0();hU();v8();B4();q3();l1();fg();ML();mq=new Map([["run","executes the command given to it"],["statusline","--then executes a shell command"],["wire","rewrites the agent's own hooks and permissions"],["unwire","rewrites the agent's own hooks and permissions"],["serve","opens a port, registers tenants and mints access tokens"]]);Xb={claude:mX0,codex:pX0,opencode:cX0,kimi:iX0,mcode:dX0,mimo:nX0};Zb={name:"scope",value:"string",description:"project (default) \u2014 this tree; user \u2014 the user layer of Claude Code (~/.claude) and, with --agents opencode, "+"of opencode (~/.config/opencode), for agents in git worktrees and nested repos where the project layer has no myc"},rX0=[Zb,{name:"agents",value:"string",description:`${o0.join(",")} (default: all ${o0.length})`},{name:"dry-run",description:"print every file and change, write nothing"},{name:"agents-md",description:"also insert the myc block into AGENTS.md (opt-in)"},{name:"hook-mode",value:"string",description:"append|replace|skip \u2014 what to do when a foreign hook is already there"},{name:"hook-output",value:"string",description:"json|text \u2014 how the rescue packet reaches the agent (default json)"},{name:"status-line",description:"also put myc's line into Claude Code's statusLine; the line that was there keeps getting the same input (opt-in)"},{name:"queue-hook",description:"also install a Claude Code PreToolUse hook that runs heavy Bash commands (full test runs, builds) through `myc run` (opt-in)"}];gq=["mcp","--profile","agent"];Lb={claude:"Claude Code",opencode:"opencode"},bg=o0.filter(($)=>Lb[$]!==void 0),Bb=["claude"];d9=class d9 extends Error{};wg=/-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/y});var Rb={};s(Rb,{renderReport:()=>QW,createDoctorCommand:()=>o90,checkUserLayer:()=>Db,checkSqlite:()=>Mb,HOOK_GRACE_MS:()=>Ab});import{existsSync as E3,readFileSync as j90}from"fs";import{dirname as eq,join as r9,resolve as Cb}from"path";import{Database as O90}from"bun:sqlite";function HW($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,...Y!==void 0?{hint:Y}:{}}}function C90($,X){try{return $.query(`SELECT max(version) AS v FROM ${X}`).get()?.v??null}catch{return null}}function A90($){let X=(Z)=>Z.reduce((Y,z)=>Math.max(Y,z.version),0);return[{name:"vectors",table:B6,known:X(n7),objects:[B6,...n7.flatMap((Z)=>Z.objects)],applicable:$.vec0,...$.vec0?{}:{why:`vec0 not loaded (${$.vec0Reason??"no reason given"})`}},{name:"swarm",table:h6,known:X(Q9),objects:[h6,...Q9.flatMap((Z)=>Z.objects)],applicable:!0}]}function P90($,X){let Z=new Set;for(let[Y,z]of $)for(let J of X)if(z.name===J||z.name.startsWith(`${J}_`)){Z.add(Y);break}return Z}async function D90($){let X=$.database,Z=X$.reduce((Q,L)=>Math.max(Q,L.version),0),Y=az(X)??[],z=Y.length===0?null:Math.max(...Y.map((Q)=>Q.version)),J=[],U=A90($),K=new Set(Y.map((Q)=>Q.version)),W=X$.filter((Q)=>!K.has(Q.version)).map((Q)=>Q.version),V=Y.filter((Q)=>Q.version>Z),G=V.filter((Q)=>Q.readableFrom===null||Q.readableFrom>Z),H=Math.max(0,...Y.map((Q)=>Q.readableFrom??Q.version));if(z===null)J.push({name:"version",verdict:"drift",detail:"no schema_migrations table in the database \u2014 the schema was never applied"});else if(G.length>0)J.push({name:"version",verdict:"drift",detail:`database is newer than the binary: schema ${z}, the binary knows ${Z}`});else if(W.length>0)J.push({name:"version",verdict:"drift",detail:`migrations not applied: ${W.join(", ")} (the binary knows up to ${Z})`,items:W.map(String)});else if(V.length>0)J.push({name:"version",verdict:"ok",detail:`schema ${z} of ${Z}: ${V.map((Q)=>Q.version).join(", ")} written by a newer myc and compatible with this binary`});else J.push({name:"version",verdict:"ok",detail:`schema ${z} of ${Z}`+(H<z?`; myc that knows schema ${H} opens it too`:"")});if(z===null)J.push({name:"objects",verdict:"unknown",detail:"nothing to compare against: no schema"});else{let Q=new O90(":memory:");try{await i8(Q,{migrations:X$,writable:!0});let L=T2(X),B=new Map;for(let q of U)for(let j of P90(L,q.objects))B.set(j,`set "${q.name}": has its own bookkeeping table`);let T=PJ(T2(Q),L,{ignore:B});if(DJ(T))J.push({name:"objects",verdict:"ok",detail:`${L.size-B.size} objects match the binary's migrations`});else{let q=[...T.missing.map((j)=>`missing from the database: ${j}`),...T.extra.map((j)=>`extra in the database: ${j}`),...T.differing.map((j)=>`DDL text differs: ${j}`)];J.push({name:"objects",verdict:"drift",detail:`${q.length} differences`,items:q})}}finally{Q.close()}}let N=[{name:"base",table:"schema_migrations",applied:z,known:Z,applicable:!0}];for(let Q of U){let L=C90(X,Q.table);if(N.push({name:Q.name,table:Q.table,applied:L,known:Q.known,applicable:Q.applicable,...Q.why!==void 0?{why:Q.why}:{}}),!Q.applicable)J.push({name:Q.name,verdict:"unknown",detail:`${Q.why??"set not applicable"} \u2014 this set's schema was not checked`});else if(L===null)J.push({name:Q.name,verdict:"n/a",detail:`set never applied \u2014 its objects are created on demand (the binary knows up to ${Q.known})`});else if(L>Q.known)J.push({name:Q.name,verdict:"drift",detail:`database has ${L}, the binary knows ${Q.known} \u2014 the database is newer than the binary`});else if(L<Q.known)J.push({name:Q.name,verdict:"drift",detail:`database has ${L}, the binary knows ${Q.known} \u2014 the set is behind`});else J.push({name:Q.name,verdict:"ok",detail:`${L} of ${Q.known}`})}return{ledgers:N,checks:J}}function qb($){return`${$.ancestor}\u2192${$.descendant}@${$.depth}`}function M90($){try{return $.tx("immediate",(X)=>{let Z=new Map(W2(X).map((J)=>[qb(J),J]));$J(X);let Y=new Map(W2(X).map((J)=>[qb(J),J])),z=[];for(let J of Y.keys())if(!Z.has(J))z.push(`missing row ${J}`);for(let J of Z.keys())if(!Y.has(J))z.push(`extra row ${J}`);throw new I3(z)}),[]}catch(X){if(X instanceof I3)return[...X.rows];throw X}}function R90($){let X=$.all(x.edges_cycle_marked,[]),Z=$.all(x.nodes_multi_parent,[]);if(X.length===0&&Z.length===0)return{name:"tree",verdict:"ok",detail:"no merge cycles, no node with two parents"};let Y=[...X.map((z)=>`cycle marked on parent(${z.src} \u2192 ${z.dst}) \u2014 a human breaks it`),...Z.map((z)=>`${z.id}: ${Number(z.n)} live parent edges, inheritance follows one`)];return{name:"tree",verdict:"drift",detail:`${X.length} cycle${X.length===1?"":"s"} from merge, ${Z.length} node${Z.length===1?"":"s"} with two parents`,items:Y.slice(0,20)}}function _90($){let X={actor:"doctor",siteId:"",ops:new o$("doctor",{clock:new u0}),now:()=>Date.now()};try{return $.tx("immediate",(Z)=>{let Y=()=>new Map(Z.all(x.edges_state,[]).map((W)=>[`${W.src} ${W.type} ${W.dst}`,JSON.stringify(W)])),z=Y(),J=Z.all(x.edges_state,[]);for(let W of J){let V=z0(g7(k$(W.src,W.type,W.dst)),Z);z0(m4(X,W.src,W.type,W.dst,V),Z)}let U=Y(),K=[];for(let[W,V]of z)if(U.get(W)!==V)K.push(W);throw new I3(K)}),[]}catch(Z){if(Z instanceof I3)return[...Z.rows];throw Z}}function I90($){let X=$.all(x.content_duplicates,[]),Z=$.all(x.external_duplicates,[]);if(X.length===0&&Z.length===0)return{name:"duplicates",verdict:"ok",detail:"no node has a twin"};return{name:"duplicates",verdict:"drift",detail:`${X.length} by content, ${Z.length} by external ref \u2014 `+"resolved by the merge, not damage; merge or retire the twin yourself",items:[...X.map((Y)=>`${Y.id}: content twin of ${Y.of}`),...Z.map((Y)=>`${Y.id}: same external ref ${Y.ref} as ${Y.of}`)].slice(0,20)}}function Fb($,X){if(X.length===0)return{name:$,verdict:"ok",detail:"matches the recount"};return{name:$,verdict:"drift",detail:`nodes that differ: ${X.length}`,items:X.slice(0,20).map((Z)=>`${Z.id}: stored ${Z.stored}, recount ${Z.actual}`)}}function k90($){let X=[];try{X.push(Fb("open_blockers",$.all(x.open_blockers_drift,[]))),X.push(Fb("anc_blockers",$.all(x.anc_blockers_drift,[])))}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);X.push({name:"open_blockers",verdict:"unknown",detail:`not checked: ${Y}`}),X.push({name:"anc_blockers",verdict:"unknown",detail:`not checked: ${Y}`})}try{let Z=M90($);X.push(Z.length===0?{name:"parent_closure",verdict:"ok",detail:"matches the recount from edges"}:{name:"parent_closure",verdict:"drift",detail:`rows that differ: ${Z.length}`,items:Z.slice(0,20)})}catch(Z){X.push({name:"parent_closure",verdict:"unknown",detail:`not checked: ${Z instanceof Error?Z.message:String(Z)}`})}try{let Z=_90($);X.push(Z.length===0?{name:"edges",verdict:"ok",detail:"every edge row matches its OR-Set"}:{name:"edges",verdict:"drift",detail:`rows that differ: ${Z.length} \u2014 repaired by \`myc import\``,items:Z.slice(0,20)})}catch(Z){X.push({name:"edges",verdict:"unknown",detail:`not checked: ${Z instanceof Error?Z.message:String(Z)}`})}try{X.push(I90($))}catch(Z){X.push({name:"duplicates",verdict:"unknown",detail:`not checked: ${Z instanceof Error?Z.message:String(Z)}`})}try{X.push(R90($))}catch(Z){X.push({name:"tree",verdict:"unknown",detail:`not checked: ${Z instanceof Error?Z.message:String(Z)}`})}return{checks:X}}function v90($){if($===null)return null;{let X=new Set,Z=!1;for(let Y of $.entries??[]){for(let z of Y.nodes??[])if(z.startsWith("hooks."))X.add(z.slice(6));if((Y.nodes??[]).length===0&&/myc(-hooks)?\.(ts|mjs)$/.test(Y.path??""))Z=!0}if(Z)for(let Y of E90)X.add(Y);return{events:X,writtenAt:$.written_at}}}function k3($){try{return E3($)?j90($,"utf8"):null}catch{return null}}function y90($,X,Z,Y){if(Z===null)return[{path:P4,verdict:"unknown",detail:`unknown: the journal ${r9(X,P4)} is missing or unreadable \u2014 `+"nothing to check the installed files against this build"}];let J=(Z.hook_output!==void 0?[Z.hook_output]:["json","text"]).map((K)=>cq($,Y,K)),U=[];for(let K of Z.entries){let W=J.map((N)=>N.get(K.path)).filter((N)=>N!==void 0);if(W.length===0)continue;let V=W.map(D4),G=k3(r9($,K.path));if(G===null){U.push({path:K.path,verdict:"drift",detail:"gone: the `myc wire` journal remembers it, but the file is not on disk \u2014 the hook has nothing to run; `myc wire`",recorded:K.hash,expected:V[0]});continue}let H=D4(G);if(V.includes(H)){U.push({path:K.path,verdict:"ok",detail:`up to date: matches what this build generates (${H})`,recorded:K.hash,expected:H,actual:H});continue}if(H===K.hash){U.push({path:K.path,verdict:"drift",detail:`stale: the file is exactly what \`myc wire\` wrote (${K.hash}), but this build's template produces a different one (${V[0]}) \u2014 rerun \`myc wire\``,recorded:K.hash,expected:V[0],actual:H});continue}U.push({path:K.path,verdict:"drift",detail:`changed after we wrote it: on disk (${H}) is neither what \`myc wire\` wrote (${K.hash}) nor what this build produces (${V[0]}) \u2014 \`myc wire\` restores our file, `+"the current one goes to .myc.bak",recorded:K.hash,expected:V[0],actual:H})}return U}function jb($){return`${$} time${$===1?"":"s"}`}function tq($){return new Date($).toISOString().replace("T"," ").slice(0,19)}function f90($,X){let Z=0,Y,z=[];for(let[J,U]of Object.entries($)){if(!J.endsWith(`:${X}`))continue;if(Z+=U.count,z.push(J.slice(0,J.length-X.length-1)),Y===void 0||U.last_at>Y.last_at)Y=U}return{count:Z,last:Y,agents:z}}function S90($,X,Z,Y,z=Date.now()){let J=VW(r9(X,P4)),U=Db(Y,Z),K=J===null&&U.journal!==null&&U.events!==void 0&&U.checks.every((B)=>B.verdict==="ok"||B.verdict==="n/a"),W=v90(J)??(K?{events:new Set(U.events??[]),writtenAt:U.writtenAt??Number.NaN}:null),V=FN($).hooks,G=[],H=Y$.filter((B)=>Z.hasTop(B.command)).map((B)=>B.event);for(let B of Y$){let T=Z.hasTop(B.command),q=W===null?null:W.events.has(B.claudeEvent),j=tM.includes(B.event),{count:O,last:A,agents:R}=f90(V,B.event);if(!T){G.push({event:B.event,command:B.command,installed:!1,verdict:"n/a",detail:`not wired: this build has no \`myc ${B.command}\` command`});continue}if(O>0&&A!==void 0){let P=eM[A.last_status];G.push({event:B.event,command:B.command,installed:q,verdict:P!==void 0?"drift":"ok",detail:P!==void 0?`fired ${jb(O)}, but did no work last time (${tq(A.last_at)}, status ${A.last_status}${R.length>0?`, agents: ${R.join(", ")}`:""}): ${P}`:`fired ${jb(O)}, last ${tq(A.last_at)} (${A.last_status}, ${A.last_ms} ms)${R.length>0?`, agents: ${R.join(", ")}`:""}`,count:O,last_at:A.last_at});continue}if(q===null){G.push({event:B.event,command:B.command,installed:null,verdict:"unknown",detail:`unknown: no journal ${r9(X,P4)} \u2014 `+"whether the hook is installed cannot be seen from here"});continue}if(!q){G.push({event:B.event,command:B.command,installed:!1,verdict:"drift",detail:K?"not installed: no project wiring here, and the user layer (`myc wire --scope user`) did not put this event in":"not installed: the event is not in the `myc wire` journal"});continue}let F=(W===null||Number.isNaN(W.writtenAt)?Number.POSITIVE_INFINITY:z-W.writtenAt)<Ab;G.push({event:B.event,command:B.command,installed:!0,verdict:j&&!F?"drift":"unknown",detail:!j?`unknown: installed, but does not report itself \u2014 \`myc ${B.command}\` is called both by hand and by the hook, and nothing tells them apart`:F?`unknown: installed ${tq(W.writtenAt)} and has not fired yet \u2014 the event simply had no occasion to happen`:"installed, but never fired"})}let N=K?[{path:"project layer",verdict:"n/a",detail:`not wired here (user layer: ok) \u2014 no ${r9(X,P4)}, and none is needed: Claude Code runs myc's hooks from the user layer (${U.journal}) in this tree`}]:y90(eq(X),X,J,H),Q=[...G.map((B)=>({name:B.event,verdict:B.verdict,detail:B.detail})),...N.map((B)=>({name:B.path,verdict:B.verdict,detail:B.detail})),...U.checks,...U.opencode??[]],L=$===X?void 0:K?`counter from ${$} (it belongs to the database), installation from the user layer ${U.journal} (this working tree ${eq(X)} has no project wiring)`:`counter from ${$} (it belongs to the database), install journal from ${X} (it belongs to the working tree)`;if(L!==void 0)Q.unshift({name:"sources",verdict:"ok",detail:L});return{journal:J!==null,...K?{layer:"user"}:{},hooks:G,generated:N,checks:Q,countersDir:$,journalDir:X,...L!==void 0?{split:L}:{},user:U}}function g90($){let X=k3($);if(X===null)return{value:null,broken:!1};try{let Z=JSON.parse(X);return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)?{value:Z,broken:!1}:{value:null,broken:!0}}catch{return{value:null,broken:!0}}}function $F($){return $!==null&&typeof $==="object"&&!Array.isArray($)?$:{}}function XF($){return Array.isArray($)?$:[]}function Pb($){let X=$.replace(/\s+/g," ").trim();return X.length<=60?X:`${X.slice(0,59)}\u2026`}function Ob($){let X=Z8($);if(X===null)return"a line without a command";return`"${Pb(X)}"${rK(X)?" (orca's line)":""}`}function b90($,X){return $.startsWith(`${X}/`)?`~${$.slice(X.length)}`:$}function w90($){let X=/^const WIRED_BIN = (".*");$/m.exec($);if(X===null)return;try{let Z=JSON.parse(X[1]);return typeof Z==="string"?Z:void 0}catch{return}}function Db($,X){let Z=R3($);if(Z===null)return{journal:null,checks:[{name:"user layer",verdict:"n/a",detail:"HOME is not set \u2014 no user layer of Claude Code to check"}]};let Y=(H)=>b90(H,Z.home),z=_3(Z.journal);if(z===null)return{journal:null,checks:[{name:"user layer",verdict:"n/a",detail:`not wired: no ${Y(Z.journal)} (\`myc wire --scope user\` wires Claude Code's user layer for agents in git worktrees; if myc's entries are in ~/.claude/settings.json anyway, it writes the journal again)`}]};let J=z.opencode!==void 0?x90(Z,z,z.opencode,X,Y):void 0;if(z.settings===null)return{journal:Z.journal,checks:[{name:"user layer",verdict:"n/a",detail:"Claude Code's user layer is not wired (`myc wire --scope user`); only opencode's is"}],...J!==void 0?{opencode:J}:{},writtenAt:z.written_at};let U=g90(Z.settings),K=[],W=z.settings?.helpers??[Z.helper,Z.queueHelper],V="`myc wire --scope user`";if(U.broken)K.push({name:"user:settings",verdict:"unknown",detail:`${Y(Z.settings)} is not valid JSON \u2014 can't see myc's entries in it`});else{let H=U.value??{},N=$F(H.hooks),Q=Y$.filter((P)=>X.hasTop(P.command)).map((P)=>P.claudeEvent),L=z.events??Q,B=(P,_)=>XF(N[P]).some((M)=>nq(M,_)),T=L.filter((P)=>!B(P,W)).map((P)=>`hooks.${P}`),q=z.files.some((P)=>P.path===Z.queueHelper);if(q&&!B("PreToolUse",[Z.queueHelper]))T.push("hooks.PreToolUse (the queue hook)");let j=`${L.join(", ")}${q?" + the queue hook on PreToolUse":""}`;K.push(T.length===0?{name:"user:hooks",verdict:"ok",detail:`myc's entries in place: ${j}`}:{name:"user:hooks",verdict:"drift",detail:`gone from ${Y(Z.settings)}: ${T.join(", ")} \u2014 removed after wire (by hand or by another tool), `+`so nothing runs myc there; ${V} puts them back`,items:T});let O=XF($F(H.permissions).allow),A=new Set(z.settings?.permissions??[]),R=M3(X).filter((P)=>!O.includes(P)),D=R.filter((P)=>A.has(P)),F=R.filter((P)=>!A.has(P));K.push(R.length===0?{name:"user:permissions",verdict:"ok",detail:"every Bash(myc <command>:*) rule of this build is in permissions.allow"}:{name:"user:permissions",verdict:"drift",detail:[D.length>0?`${D.length} rules wire added are gone`:"",F.length>0?`${F.length} rules of this build were never added (commands newer than the wire run)`:""].filter((P)=>P.length>0).join("; ")+` \u2014 Claude Code asks before those myc commands; ${V} adds them`,items:R})}K.push(...m90(Z,z,X,$,Y)),K.push(u90(Z,z,U,Y)),K.push(l90(Z,z,Y));let G=z.events??Y$.filter((H)=>X.hasTop(H.command)).map((H)=>H.claudeEvent);return{journal:Z.journal,checks:K,...J!==void 0?{opencode:J}:{},events:G,writtenAt:z.written_at}}function x90($,X,Z,Y,z){let U=Y$.filter((Q)=>Y.hasTop(Q.command)).map((Q)=>Q.event),K={...$,opencodePlugin:Z.plugin},W=s9(K,U,X.hook_output,Z.bin,Z.bin).opencodePlugin,V=X.files.find((Q)=>Q.path===Z.plugin),G=[];if(V!==void 0)G.push(h90(`user:${z(Z.plugin)}`,Z.plugin,V.hash,W,Z.version.length>0?`myc ${Z.version}`:"an earlier myc","`myc wire --scope user --agents opencode`"));let H="user:opencode:mcp",N=aq(Z.config);if(N.broken)G.push({name:H,verdict:"unknown",detail:`${z(Z.config)} is not valid JSONC \u2014 can't see mcp.myc in it`});else if(Z.mcp===null)G.push(N.value!==void 0?{name:H,verdict:"n/a",detail:`a server named myc is in ${z(Z.config)}, not written by wire \u2014 not checked`}:{name:H,verdict:"drift",detail:`mcp.myc is not in ${z(Z.config)} (wire could not write it): opencode in git worktrees gets no myc tools; \`myc wire --scope user --agents opencode\``});else if(N.value===void 0)G.push({name:H,verdict:"drift",detail:`gone: the mcp.myc wire wrote is not in ${z(Z.config)}${N.exists?"":" (the file is gone)"} any more \u2014 opencode in git worktrees gets no myc tools; ${"`myc wire --scope user --agents opencode`"}`});else if(!sq(N.value,Z.mcp.command))G.push({name:H,verdict:"drift",detail:`changed after wire wrote it: now ${JSON.stringify(N.value)}, wire wrote ${Z.mcp.command.join(" ")}; \`myc wire --scope user --agents opencode\``});else if($F(N.value).enabled===!1)G.push({name:H,verdict:"n/a",detail:`myc's server in ${z(Z.config)} is disabled by hand ("enabled": false) \u2014 opencode does not start it`});else if(Z.mcp.command[0].startsWith("/")&&!E3(Z.mcp.command[0]))G.push({name:H,verdict:"drift",detail:`mcp.myc runs ${Z.mcp.command[0]}, which is not there \u2014 the server does not start; ${"`myc wire --scope user --agents opencode`"} with a myc that exists`});else G.push({name:H,verdict:"ok",detail:`in ${z(Z.config)}: ${Z.mcp.command.join(" ")}`});return G}function h90($,X,Z,Y,z,J){let U=k3(X);if(U===null)return{name:$,verdict:"drift",detail:`gone: the journal remembers it, but the file is not on disk \u2014 myc does nothing there; ${J}`};let K=D4(U),W=D4(Y);if(K===W)return{name:$,verdict:"ok",detail:`up to date: matches what this build (myc ${E0}) writes (${K})`};if(K===Z)return{name:$,verdict:"drift",detail:`stale: exactly what ${J} wrote (${z}, ${Z}), but this build (myc ${E0}) writes a different one (${W}) \u2014 rerun ${J}`};return{name:$,verdict:"drift",detail:`changed after we wrote it: on disk (${K}) is neither what wire wrote (${Z}) nor what this build writes (${W}) \u2014 ${J} restores ours, the current one goes to .myc.bak`}}function m90($,X,Z,Y,z){let J=Y$.filter((N)=>Z.hasTop(N.command)).map((N)=>N.event),U=k3($.helper),K=X.bin??(U!==null?w90(U):void 0)??"myc",W=s9($,J,X.hook_output,K),V=new Map([[$.helper,W.helper],[$.queueHelper,W.queueHelper],[$.skill,W.skill]]),G=X.version!==void 0?`myc ${X.version}`:"an earlier myc",H=[];for(let N of X.files){let Q=V.get(N.path);if(Q===void 0)continue;let L=`user:${z(N.path)}`,B=k3(N.path);if(B===null){H.push({name:L,verdict:"drift",detail:"gone: the journal remembers it, but the file is not on disk \u2014 the hooks that call it exit quietly, so myc "+"does nothing there; `myc wire --scope user`"});continue}let T=D4(B),q=D4(Q);if(T===q)H.push({name:L,verdict:"ok",detail:`up to date: matches what this build (myc ${E0}) writes (${T})`});else if(T===N.hash)H.push({name:L,verdict:"drift",detail:`stale: exactly what \`myc wire --scope user\` wrote (${G}, ${N.hash}), but this build (myc ${E0}) writes a different one (${q}) \u2014 rerun \`myc wire --scope user\``});else H.push({name:L,verdict:"drift",detail:`changed after we wrote it: on disk (${T}) is neither what wire wrote (${N.hash}) nor what this build writes (${q}) \u2014 \`myc wire --scope user\` restores ours, the current one goes to .myc.bak`})}return H}function u90($,X,Z,Y){if(Z.broken)return{name:"user:statusLine",verdict:"unknown",detail:`${Y($.settings)} is not valid JSON \u2014 can't see the status line`};let J=Z.value?.statusLine,U=X.status_line;if(U===void 0){if(Y6(J))return{name:"user:statusLine",verdict:"drift",detail:`myc's line is in ${Y($.settings)} with no record in ${Y($.journal)} of the line it replaced \u2014 `+"that line gets no input; `myc wire --scope user --status-line` records what is known"};return{name:"user:statusLine",verdict:"n/a",detail:"not installed (`myc wire --scope user --status-line` puts myc's line there)"}}let K=Z8(U.previous)!==null?`the previous line ${Ob(U.previous)} gets the same input`:"there was no previous line";if(J===void 0)return{name:"user:statusLine",verdict:"drift",detail:`gone: myc's line was removed from ${Y($.settings)} after wire, and the line it replaced gets no input either; \`myc wire --scope user --status-line\` puts it back, \`myc wire --scope user\` forgets it`};if(!Y6(J))return{name:"user:statusLine",verdict:"drift",detail:`no longer myc's: now ${Ob(J)} \u2014 replaced after wire. \`myc wire --scope user --status-line\` puts ours `+"back and keeps this one as the previous line (it keeps getting the same input); `myc wire --scope user` accepts it and forgets ours"};let W=Z8(J)??"";if(X.bin!==void 0&&W===aK({command:X.bin})&&X.bin.startsWith("/")&&!E3(X.bin))return{name:"user:statusLine",verdict:"drift",detail:`myc's line runs ${X.bin}, which is not there \u2014 the line is empty and the previous line gets no input; `+"`myc wire --scope user --status-line` with a myc that exists"};return{name:"user:statusLine",verdict:"ok",detail:`myc's line (${Pb(W)}); ${K}`}}function l90($,X,Z){let z=X.mcp,J=z?.config??$.claudeJson,U=dq(J);if(U.broken)return{name:"user:mcp",verdict:"unknown",detail:`${Z(J)} is not valid JSON \u2014 can't see whether myc is registered`};let K="`myc wire --scope user` (it runs `claude mcp add --scope user myc -- <myc> mcp --profile agent`)";if(z===null){if(U.value!==void 0)return{name:"user:mcp",verdict:"n/a",detail:`a server named myc is registered in ${Z(J)}, not by wire \u2014 not checked`};return{name:"user:mcp",verdict:"drift",detail:`not registered in the user layer (wire could not do it): agents in git worktrees get no myc tools; ${K}`}}if(U.value===void 0)return{name:"user:mcp",verdict:"drift",detail:`gone: the MCP server myc wire registered is not in ${Z(J)} any more \u2014 agents in git worktrees get no myc tools; ${K}`};let W=U.value.command,V=XF(U.value.args);if(W!==z.command||JSON.stringify(V)!==JSON.stringify(z.args))return{name:"user:mcp",verdict:"drift",detail:`changed after wire registered it: now ${[W,...V].map(String).join(" ")}, wire registered ${[z.command,...z.args].join(" ")}; ${K}`};if(z.command.startsWith("/")&&!E3(z.command))return{name:"user:mcp",verdict:"drift",detail:`registered, but ${z.command} is not there \u2014 the server does not start; ${K}`};return{name:"user:mcp",verdict:"ok",detail:`registered: ${[z.command,...z.args].join(" ")}`}}function Mb(){let $;try{$=K6()}catch(z){let J=z instanceof L$?` \u2014 fix: ${z.hint}`:"";return{checks:[{name:"library",verdict:"drift",detail:`${z instanceof Error?z.message:String(z)}${J}`}]}}let X=$.support==="ok"?"ok":$.support==="old"?"unknown":"drift",Z=`SQLite ${$.version} \u2014 ${y4($)}`,Y=[{name:"library",verdict:X,detail:$.support==="ok"?Z:`${$.problem} \u2014 fix: ${$.hint}`,items:[...$.locked!==null?[$.locked]:[],...$.skipped.map((z)=>`passed over: ${z}`)]},{name:"open paths",verdict:X,detail:`cli (show/ready/close/create), cli+vec0 (recall, drain), engine, mcp, web \u2014 each chooses the library before its first connection, the same way: ${Z}`}];if($.support!=="unsupported")try{let z=l$().vec;Y.push(z.loaded?{name:"vec0",verdict:"ok",detail:`${z.version} \u2014 ${z.path}`}:{name:"vec0",verdict:"unknown",detail:`not loaded \u2014 recall falls back to BM25: ${z.reason}`})}catch(z){Y.push({name:"vec0",verdict:"drift",detail:z instanceof Error?z.message:String(z)})}return{checks:Y}}function c90($,X){if(X==="schema")return $.schema?.checks??[];if(X==="recount")return $.recount?.checks??[];if(X==="background")return $.background?.checks??[];return $.hooks?.checks??[]}function QW($,X){let Z=[`database ${$.db}`];for(let Y of $.sqlite!==void 0?["sqlite",...$.sections]:$.sections){let z=Y==="sqlite"?$.sqlite.checks:c90($,Y);Z.push(`${i90[Y]??Y}`);for(let J of z){if(Z.push(` ${p90[J.verdict]} ${J.name}: ${J.detail}`),!X)continue;for(let U of J.items??[])Z.push(` ${U}`)}}return Z}function n90($){let X=0,Z=0;for(let Y of $)if(Y.verdict==="drift")X++;else if(Y.verdict==="unknown")Z++;return{drift:X,unknown:Z}}function d90($){let X=$.globals.db;if(X!==void 0)return{path:Cb(X)};let Z=K$($.globals.directory??process.cwd());if("dbPath"in Z)return{path:Z.dbPath};return HW("ws.not_initialized",`workspace not initialized: looked in ${Z.searched.join(", ")}`,7,"myc init")}function o90($,X={}){let Z=X.env??process.env;return{name:"doctor",summary:"check what the database claims against what can be recounted",flags:[{name:"schema",description:"schema version and object-level diff against this binary"},{name:"recount",description:"materialised counters against a recount from the graph"},{name:"hooks",description:"when each hook last fired, which events are not installed, and the user layer myc wire --scope user put in ~/.claude (and ~/.config/opencode)"},{name:"background",description:"whether the background after commands keeps up: anchor sweeps and code-index refreshes against local writes"},{name:"verbose",description:"list every diverging object, node and row, not just counts"}],help:"Exit 0 only when every checked item converges. A section that could not be checked is "+"reported as 'unknown' and never as 'ok' \u2014 a diagnostic that prints ok where it looked at "+"nothing is worse than silence.\n\nThe database is opened WITHOUT running migrations, on purpose: a database written by a newer myc refuses to open on the normal path with `precond.schema`, and that failure is exactly what sends people here.\n\n--recount only compares. `parent_closure` and the edge rows are compared by running the real rebuild and the real reprojection inside a transaction that is always rolled back, so the file is left byte-for-byte unchanged and the check cannot drift from the repair it mirrors. Edge rows diverging from their OR-Set are repaired by `myc import`; twins (same content or same external ref), merge "+"cycles and a node with two live parents are reported and never repaired \u2014 the merge "+"resolved what it could and a human decides the rest.\n\n--hooks answers two questions. Did it fire: the counter is written only by a caller that declared itself through MYC_HOOK, so 'session-start fired N times' means sessions, not hand-typed `myc prime` calls. Is it the current hook: every file myc generates in full is hashed against what this build would generate, so a helper installed by an older version is reported as stale by name instead of silently doing nothing. The user layer (`myc wire --scope user`) is checked by ~/.myc/wire-user.json against ~/.claude: myc's hook entries and rules still there, its helpers what this build writes, its status line not replaced by another tool, its MCP server still registered (~/.claude.json is only read); with opencode wired (--agents opencode), its plugin is what this build writes and mcp.myc is still in opencode's global config (read as JSONC, never written).\n\n--background compares the marks the background leaves after commands (anchor_swept_at, "+"code_indexed_at) with local writes in the oplog. Age alone is not evidence \u2014 an idle "+"workspace has old marks by right; drift is a mark more than two periods overdue while local writes kept coming for a whole period after that: commands ran, the background after them did not.",handler:async(Y)=>{let z={schema:Y.flags.schema===!0,recount:Y.flags.recount===!0,hooks:Y.flags.hooks===!0,background:Y.flags.background===!0},J=!z.schema&&!z.recount&&!z.hooks&&!z.background,U=["schema","recount","hooks","background"].filter((B)=>J||z[B]),K=Y.flags.verbose===!0||!J,W=d90(Y);if("ok"in W)return W;let V=W.path;if(!E3(V))return HW("ws.not_initialized",`no database: ${V}`,7,"myc init");let G=eq(V),H=r9(Cb(Y.globals.directory??process.cwd()),".myc"),N=Mb(),Q;if(U.includes("schema")||U.includes("recount")||U.includes("background"))try{Q=X4(V,void 0,{extensions:!0})}catch(B){let T=N5(B);if(T!==void 0){let q=QW({db:V,sections:[],sqlite:N,ok:!1,unknown:0},!0);return{...T,msg:[T.msg,...q].join(`
|
|
8799
|
-
`)}}return HW("db.open",`cannot open the database: ${B instanceof Error?B.message:String(B)}`,1)}try{let B=U.includes("schema")?await
|
|
8798
|
+
`)[0]??"";return{ok:!1,why:`${J}: exit ${z.exitCode}${K.length>0?` (${K})`:""} \u2014 an older build`}}let U=z.stdout.toString().trim();if(U.length>0)return{ok:!1,why:`${J} prints "${a5(U)}" outside a myc workspace \u2014 an older build`};return{ok:!0}}catch(z){return{ok:!1,why:`${$.command} does not start: ${z instanceof Error?z.message:String(z)}`}}finally{z6(Z,{recursive:!0,force:!0})}},Lb,bg,Bb,Q90=($)=>$.includes("claude"),N90=($)=>$.includes("opencode"),d9,wg;var GW=v(()=>{V0();j0();hU();v8();B4();q3();l1();fg();ML();mq=new Map([["run","executes the command given to it"],["statusline","--then executes a shell command"],["wire","rewrites the agent's own hooks and permissions"],["unwire","rewrites the agent's own hooks and permissions"],["serve","opens a port, registers tenants and mints access tokens"]]);Xb={claude:iX0,codex:oX0,opencode:aX0,kimi:sX0,mcode:tX0,mimo:rX0};Zb={name:"scope",value:"string",description:"project (default) \u2014 this tree; user \u2014 the user layer of Claude Code (~/.claude) and, with --agents opencode, "+"of opencode (~/.config/opencode), for agents in git worktrees and nested repos where the project layer has no myc"},Z90=[Zb,{name:"agents",value:"string",description:`${o0.join(",")} (default: all ${o0.length})`},{name:"dry-run",description:"print every file and change, write nothing"},{name:"agents-md",description:"also insert the myc block into AGENTS.md (opt-in)"},{name:"hook-mode",value:"string",description:"append|replace|skip \u2014 what to do when a foreign hook is already there"},{name:"hook-output",value:"string",description:"json|text \u2014 how the rescue packet reaches the agent (default json)"},{name:"status-line",description:"also put myc's line into Claude Code's statusLine; the line that was there keeps getting the same input (opt-in)"},{name:"queue-hook",description:"also install a Claude Code PreToolUse hook that runs heavy Bash commands (full test runs, builds) through `myc run` (opt-in)"}];gq=["mcp","--profile","agent"];Lb={claude:"Claude Code",opencode:"opencode"},bg=o0.filter(($)=>Lb[$]!==void 0),Bb=["claude"];d9=class d9 extends Error{};wg=/-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/y});var Rb={};s(Rb,{renderReport:()=>QW,createDoctorCommand:()=>e90,checkUserLayer:()=>Db,checkSqlite:()=>Mb,HOOK_GRACE_MS:()=>Ab});import{existsSync as E3,readFileSync as D90}from"fs";import{dirname as eq,join as r9,resolve as Cb}from"path";import{Database as M90}from"bun:sqlite";function HW($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,...Y!==void 0?{hint:Y}:{}}}function R90($,X){try{return $.query(`SELECT max(version) AS v FROM ${X}`).get()?.v??null}catch{return null}}function _90($){let X=(Z)=>Z.reduce((Y,z)=>Math.max(Y,z.version),0);return[{name:"vectors",table:B6,known:X(n7),objects:[B6,...n7.flatMap((Z)=>Z.objects)],applicable:$.vec0,...$.vec0?{}:{why:`vec0 not loaded (${$.vec0Reason??"no reason given"})`}},{name:"swarm",table:h6,known:X(Q9),objects:[h6,...Q9.flatMap((Z)=>Z.objects)],applicable:!0}]}function I90($,X){let Z=new Set;for(let[Y,z]of $)for(let J of X)if(z.name===J||z.name.startsWith(`${J}_`)){Z.add(Y);break}return Z}async function k90($){let X=$.database,Z=X$.reduce((Q,L)=>Math.max(Q,L.version),0),Y=az(X)??[],z=Y.length===0?null:Math.max(...Y.map((Q)=>Q.version)),J=[],U=_90($),K=new Set(Y.map((Q)=>Q.version)),W=X$.filter((Q)=>!K.has(Q.version)).map((Q)=>Q.version),V=Y.filter((Q)=>Q.version>Z),G=V.filter((Q)=>Q.readableFrom===null||Q.readableFrom>Z),H=Math.max(0,...Y.map((Q)=>Q.readableFrom??Q.version));if(z===null)J.push({name:"version",verdict:"drift",detail:"no schema_migrations table in the database \u2014 the schema was never applied"});else if(G.length>0)J.push({name:"version",verdict:"drift",detail:`database is newer than the binary: schema ${z}, the binary knows ${Z}`});else if(W.length>0)J.push({name:"version",verdict:"drift",detail:`migrations not applied: ${W.join(", ")} (the binary knows up to ${Z})`,items:W.map(String)});else if(V.length>0)J.push({name:"version",verdict:"ok",detail:`schema ${z} of ${Z}: ${V.map((Q)=>Q.version).join(", ")} written by a newer myc and compatible with this binary`});else J.push({name:"version",verdict:"ok",detail:`schema ${z} of ${Z}`+(H<z?`; myc that knows schema ${H} opens it too`:"")});if(z===null)J.push({name:"objects",verdict:"unknown",detail:"nothing to compare against: no schema"});else{let Q=new M90(":memory:");try{await i8(Q,{migrations:X$,writable:!0});let L=T2(X),B=new Map;for(let q of U)for(let j of I90(L,q.objects))B.set(j,`set "${q.name}": has its own bookkeeping table`);let T=PJ(T2(Q),L,{ignore:B});if(DJ(T))J.push({name:"objects",verdict:"ok",detail:`${L.size-B.size} objects match the binary's migrations`});else{let q=[...T.missing.map((j)=>`missing from the database: ${j}`),...T.extra.map((j)=>`extra in the database: ${j}`),...T.differing.map((j)=>`DDL text differs: ${j}`)];J.push({name:"objects",verdict:"drift",detail:`${q.length} differences`,items:q})}}finally{Q.close()}}let N=[{name:"base",table:"schema_migrations",applied:z,known:Z,applicable:!0}];for(let Q of U){let L=R90(X,Q.table);if(N.push({name:Q.name,table:Q.table,applied:L,known:Q.known,applicable:Q.applicable,...Q.why!==void 0?{why:Q.why}:{}}),!Q.applicable)J.push({name:Q.name,verdict:"unknown",detail:`${Q.why??"set not applicable"} \u2014 this set's schema was not checked`});else if(L===null)J.push({name:Q.name,verdict:"n/a",detail:`set never applied \u2014 its objects are created on demand (the binary knows up to ${Q.known})`});else if(L>Q.known)J.push({name:Q.name,verdict:"drift",detail:`database has ${L}, the binary knows ${Q.known} \u2014 the database is newer than the binary`});else if(L<Q.known)J.push({name:Q.name,verdict:"drift",detail:`database has ${L}, the binary knows ${Q.known} \u2014 the set is behind`});else J.push({name:Q.name,verdict:"ok",detail:`${L} of ${Q.known}`})}return{ledgers:N,checks:J}}function qb($){return`${$.ancestor}\u2192${$.descendant}@${$.depth}`}function E90($){try{return $.tx("immediate",(X)=>{let Z=new Map(W2(X).map((J)=>[qb(J),J]));$J(X);let Y=new Map(W2(X).map((J)=>[qb(J),J])),z=[];for(let J of Y.keys())if(!Z.has(J))z.push(`missing row ${J}`);for(let J of Z.keys())if(!Y.has(J))z.push(`extra row ${J}`);throw new I3(z)}),[]}catch(X){if(X instanceof I3)return[...X.rows];throw X}}function v90($){let X=$.all(x.edges_cycle_marked,[]),Z=$.all(x.nodes_multi_parent,[]);if(X.length===0&&Z.length===0)return{name:"tree",verdict:"ok",detail:"no merge cycles, no node with two parents"};let Y=[...X.map((z)=>`cycle marked on parent(${z.src} \u2192 ${z.dst}) \u2014 a human breaks it`),...Z.map((z)=>`${z.id}: ${Number(z.n)} live parent edges, inheritance follows one`)];return{name:"tree",verdict:"drift",detail:`${X.length} cycle${X.length===1?"":"s"} from merge, ${Z.length} node${Z.length===1?"":"s"} with two parents`,items:Y.slice(0,20)}}function y90($){let X={actor:"doctor",siteId:"",ops:new o$("doctor",{clock:new u0}),now:()=>Date.now()};try{return $.tx("immediate",(Z)=>{let Y=()=>new Map(Z.all(x.edges_state,[]).map((W)=>[`${W.src} ${W.type} ${W.dst}`,JSON.stringify(W)])),z=Y(),J=Z.all(x.edges_state,[]);for(let W of J){let V=z0(g7(k$(W.src,W.type,W.dst)),Z);z0(m4(X,W.src,W.type,W.dst,V),Z)}let U=Y(),K=[];for(let[W,V]of z)if(U.get(W)!==V)K.push(W);throw new I3(K)}),[]}catch(Z){if(Z instanceof I3)return[...Z.rows];throw Z}}function f90($){let X=$.all(x.content_duplicates,[]),Z=$.all(x.external_duplicates,[]);if(X.length===0&&Z.length===0)return{name:"duplicates",verdict:"ok",detail:"no node has a twin"};return{name:"duplicates",verdict:"drift",detail:`${X.length} by content, ${Z.length} by external ref \u2014 `+"resolved by the merge, not damage; merge or retire the twin yourself",items:[...X.map((Y)=>`${Y.id}: content twin of ${Y.of}`),...Z.map((Y)=>`${Y.id}: same external ref ${Y.ref} as ${Y.of}`)].slice(0,20)}}function Fb($,X){if(X.length===0)return{name:$,verdict:"ok",detail:"matches the recount"};return{name:$,verdict:"drift",detail:`nodes that differ: ${X.length}`,items:X.slice(0,20).map((Z)=>`${Z.id}: stored ${Z.stored}, recount ${Z.actual}`)}}function S90($){let X=[];try{X.push(Fb("open_blockers",$.all(x.open_blockers_drift,[]))),X.push(Fb("anc_blockers",$.all(x.anc_blockers_drift,[])))}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);X.push({name:"open_blockers",verdict:"unknown",detail:`not checked: ${Y}`}),X.push({name:"anc_blockers",verdict:"unknown",detail:`not checked: ${Y}`})}try{let Z=E90($);X.push(Z.length===0?{name:"parent_closure",verdict:"ok",detail:"matches the recount from edges"}:{name:"parent_closure",verdict:"drift",detail:`rows that differ: ${Z.length}`,items:Z.slice(0,20)})}catch(Z){X.push({name:"parent_closure",verdict:"unknown",detail:`not checked: ${Z instanceof Error?Z.message:String(Z)}`})}try{let Z=y90($);X.push(Z.length===0?{name:"edges",verdict:"ok",detail:"every edge row matches its OR-Set"}:{name:"edges",verdict:"drift",detail:`rows that differ: ${Z.length} \u2014 repaired by \`myc import\``,items:Z.slice(0,20)})}catch(Z){X.push({name:"edges",verdict:"unknown",detail:`not checked: ${Z instanceof Error?Z.message:String(Z)}`})}try{X.push(f90($))}catch(Z){X.push({name:"duplicates",verdict:"unknown",detail:`not checked: ${Z instanceof Error?Z.message:String(Z)}`})}try{X.push(v90($))}catch(Z){X.push({name:"tree",verdict:"unknown",detail:`not checked: ${Z instanceof Error?Z.message:String(Z)}`})}return{checks:X}}function b90($){if($===null)return null;{let X=new Set,Z=!1;for(let Y of $.entries??[]){for(let z of Y.nodes??[])if(z.startsWith("hooks."))X.add(z.slice(6));if((Y.nodes??[]).length===0&&/myc(-hooks)?\.(ts|mjs)$/.test(Y.path??""))Z=!0}if(Z)for(let Y of g90)X.add(Y);return{events:X,writtenAt:$.written_at}}}function k3($){try{return E3($)?D90($,"utf8"):null}catch{return null}}function w90($,X,Z,Y){if(Z===null)return[{path:P4,verdict:"unknown",detail:`unknown: the journal ${r9(X,P4)} is missing or unreadable \u2014 `+"nothing to check the installed files against this build"}];let J=(Z.hook_output!==void 0?[Z.hook_output]:["json","text"]).map((K)=>cq($,Y,K)),U=[];for(let K of Z.entries){let W=J.map((N)=>N.get(K.path)).filter((N)=>N!==void 0);if(W.length===0)continue;let V=W.map(D4),G=k3(r9($,K.path));if(G===null){U.push({path:K.path,verdict:"drift",detail:"gone: the `myc wire` journal remembers it, but the file is not on disk \u2014 the hook has nothing to run; `myc wire`",recorded:K.hash,expected:V[0]});continue}let H=D4(G);if(V.includes(H)){U.push({path:K.path,verdict:"ok",detail:`up to date: matches what this build generates (${H})`,recorded:K.hash,expected:H,actual:H});continue}if(H===K.hash){U.push({path:K.path,verdict:"drift",detail:`stale: the file is exactly what \`myc wire\` wrote (${K.hash}), but this build's template produces a different one (${V[0]}) \u2014 rerun \`myc wire\``,recorded:K.hash,expected:V[0],actual:H});continue}U.push({path:K.path,verdict:"drift",detail:`changed after we wrote it: on disk (${H}) is neither what \`myc wire\` wrote (${K.hash}) nor what this build produces (${V[0]}) \u2014 \`myc wire\` restores our file, `+"the current one goes to .myc.bak",recorded:K.hash,expected:V[0],actual:H})}return U}function jb($){return`${$} time${$===1?"":"s"}`}function tq($){return new Date($).toISOString().replace("T"," ").slice(0,19)}function x90($,X){let Z=0,Y,z=[];for(let[J,U]of Object.entries($)){if(!J.endsWith(`:${X}`))continue;if(Z+=U.count,z.push(J.slice(0,J.length-X.length-1)),Y===void 0||U.last_at>Y.last_at)Y=U}return{count:Z,last:Y,agents:z}}function h90($,X,Z,Y,z=Date.now()){let J=VW(r9(X,P4)),U=Db(Y,Z),K=J===null&&U.journal!==null&&U.events!==void 0&&U.checks.every((B)=>B.verdict==="ok"||B.verdict==="n/a"),W=b90(J)??(K?{events:new Set(U.events??[]),writtenAt:U.writtenAt??Number.NaN}:null),V=FN($).hooks,G=[],H=Y$.filter((B)=>Z.hasTop(B.command)).map((B)=>B.event);for(let B of Y$){let T=Z.hasTop(B.command),q=W===null?null:W.events.has(B.claudeEvent),j=tM.includes(B.event),{count:O,last:A,agents:R}=x90(V,B.event);if(!T){G.push({event:B.event,command:B.command,installed:!1,verdict:"n/a",detail:`not wired: this build has no \`myc ${B.command}\` command`});continue}if(O>0&&A!==void 0){let P=eM[A.last_status];G.push({event:B.event,command:B.command,installed:q,verdict:P!==void 0?"drift":"ok",detail:P!==void 0?`fired ${jb(O)}, but did no work last time (${tq(A.last_at)}, status ${A.last_status}${R.length>0?`, agents: ${R.join(", ")}`:""}): ${P}`:`fired ${jb(O)}, last ${tq(A.last_at)} (${A.last_status}, ${A.last_ms} ms)${R.length>0?`, agents: ${R.join(", ")}`:""}`,count:O,last_at:A.last_at});continue}if(q===null){G.push({event:B.event,command:B.command,installed:null,verdict:"unknown",detail:`unknown: no journal ${r9(X,P4)} \u2014 `+"whether the hook is installed cannot be seen from here"});continue}if(!q){G.push({event:B.event,command:B.command,installed:!1,verdict:"drift",detail:K?"not installed: no project wiring here, and the user layer (`myc wire --scope user`) did not put this event in":"not installed: the event is not in the `myc wire` journal"});continue}let F=(W===null||Number.isNaN(W.writtenAt)?Number.POSITIVE_INFINITY:z-W.writtenAt)<Ab;G.push({event:B.event,command:B.command,installed:!0,verdict:j&&!F?"drift":"unknown",detail:!j?`unknown: installed, but does not report itself \u2014 \`myc ${B.command}\` is called both by hand and by the hook, and nothing tells them apart`:F?`unknown: installed ${tq(W.writtenAt)} and has not fired yet \u2014 the event simply had no occasion to happen`:"installed, but never fired"})}let N=K?[{path:"project layer",verdict:"n/a",detail:`not wired here (user layer: ok) \u2014 no ${r9(X,P4)}, and none is needed: Claude Code runs myc's hooks from the user layer (${U.journal}) in this tree`}]:w90(eq(X),X,J,H),Q=[...G.map((B)=>({name:B.event,verdict:B.verdict,detail:B.detail})),...N.map((B)=>({name:B.path,verdict:B.verdict,detail:B.detail})),...U.checks,...U.opencode??[]],L=$===X?void 0:K?`counter from ${$} (it belongs to the database), installation from the user layer ${U.journal} (this working tree ${eq(X)} has no project wiring)`:`counter from ${$} (it belongs to the database), install journal from ${X} (it belongs to the working tree)`;if(L!==void 0)Q.unshift({name:"sources",verdict:"ok",detail:L});return{journal:J!==null,...K?{layer:"user"}:{},hooks:G,generated:N,checks:Q,countersDir:$,journalDir:X,...L!==void 0?{split:L}:{},user:U}}function m90($){let X=k3($);if(X===null)return{value:null,broken:!1};try{let Z=JSON.parse(X);return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)?{value:Z,broken:!1}:{value:null,broken:!0}}catch{return{value:null,broken:!0}}}function $F($){return $!==null&&typeof $==="object"&&!Array.isArray($)?$:{}}function XF($){return Array.isArray($)?$:[]}function Pb($){let X=$.replace(/\s+/g," ").trim();return X.length<=60?X:`${X.slice(0,59)}\u2026`}function Ob($){let X=Z8($);if(X===null)return"a line without a command";return`"${Pb(X)}"${rK(X)?" (orca's line)":""}`}function u90($,X){return $.startsWith(`${X}/`)?`~${$.slice(X.length)}`:$}function l90($){let X=/^const WIRED_BIN = (".*");$/m.exec($);if(X===null)return;try{let Z=JSON.parse(X[1]);return typeof Z==="string"?Z:void 0}catch{return}}function Db($,X){let Z=R3($);if(Z===null)return{journal:null,checks:[{name:"user layer",verdict:"n/a",detail:"HOME is not set \u2014 no user layer of Claude Code to check"}]};let Y=(H)=>u90(H,Z.home),z=_3(Z.journal);if(z===null)return{journal:null,checks:[{name:"user layer",verdict:"n/a",detail:`not wired: no ${Y(Z.journal)} (\`myc wire --scope user\` wires Claude Code's user layer for agents in git worktrees; if myc's entries are in ~/.claude/settings.json anyway, it writes the journal again)`}]};let J=z.opencode!==void 0?p90(Z,z,z.opencode,X,Y):void 0;if(z.settings===null)return{journal:Z.journal,checks:[{name:"user layer",verdict:"n/a",detail:"Claude Code's user layer is not wired (`myc wire --scope user`); only opencode's is"}],...J!==void 0?{opencode:J}:{},writtenAt:z.written_at};let U=m90(Z.settings),K=[],W=z.settings?.helpers??[Z.helper,Z.queueHelper],V="`myc wire --scope user`";if(U.broken)K.push({name:"user:settings",verdict:"unknown",detail:`${Y(Z.settings)} is not valid JSON \u2014 can't see myc's entries in it`});else{let H=U.value??{},N=$F(H.hooks),Q=Y$.filter((P)=>X.hasTop(P.command)).map((P)=>P.claudeEvent),L=z.events??Q,B=(P,_)=>XF(N[P]).some((M)=>nq(M,_)),T=L.filter((P)=>!B(P,W)).map((P)=>`hooks.${P}`),q=z.files.some((P)=>P.path===Z.queueHelper);if(q&&!B("PreToolUse",[Z.queueHelper]))T.push("hooks.PreToolUse (the queue hook)");let j=`${L.join(", ")}${q?" + the queue hook on PreToolUse":""}`;K.push(T.length===0?{name:"user:hooks",verdict:"ok",detail:`myc's entries in place: ${j}`}:{name:"user:hooks",verdict:"drift",detail:`gone from ${Y(Z.settings)}: ${T.join(", ")} \u2014 removed after wire (by hand or by another tool), `+`so nothing runs myc there; ${V} puts them back`,items:T});let O=XF($F(H.permissions).allow),A=new Set(z.settings?.permissions??[]),R=M3(X).filter((P)=>!O.includes(P)),D=R.filter((P)=>A.has(P)),F=R.filter((P)=>!A.has(P));K.push(R.length===0?{name:"user:permissions",verdict:"ok",detail:"every Bash(myc <command>:*) rule of this build is in permissions.allow"}:{name:"user:permissions",verdict:"drift",detail:[D.length>0?`${D.length} rules wire added are gone`:"",F.length>0?`${F.length} rules of this build were never added (commands newer than the wire run)`:""].filter((P)=>P.length>0).join("; ")+` \u2014 Claude Code asks before those myc commands; ${V} adds them`,items:R})}K.push(...i90(Z,z,X,$,Y)),K.push(n90(Z,z,U,Y)),K.push(d90(Z,z,Y));let G=z.events??Y$.filter((H)=>X.hasTop(H.command)).map((H)=>H.claudeEvent);return{journal:Z.journal,checks:K,...J!==void 0?{opencode:J}:{},events:G,writtenAt:z.written_at}}function p90($,X,Z,Y,z){let U=Y$.filter((Q)=>Y.hasTop(Q.command)).map((Q)=>Q.event),K={...$,opencodePlugin:Z.plugin},W=s9(K,U,X.hook_output,Z.bin,Z.bin).opencodePlugin,V=X.files.find((Q)=>Q.path===Z.plugin),G=[];if(V!==void 0)G.push(c90(`user:${z(Z.plugin)}`,Z.plugin,V.hash,W,Z.version.length>0?`myc ${Z.version}`:"an earlier myc","`myc wire --scope user --agents opencode`"));let H="user:opencode:mcp",N=aq(Z.config);if(N.broken)G.push({name:H,verdict:"unknown",detail:`${z(Z.config)} is not valid JSONC \u2014 can't see mcp.myc in it`});else if(Z.mcp===null)G.push(N.value!==void 0?{name:H,verdict:"n/a",detail:`a server named myc is in ${z(Z.config)}, not written by wire \u2014 not checked`}:{name:H,verdict:"drift",detail:`mcp.myc is not in ${z(Z.config)} (wire could not write it): opencode in git worktrees gets no myc tools; \`myc wire --scope user --agents opencode\``});else if(N.value===void 0)G.push({name:H,verdict:"drift",detail:`gone: the mcp.myc wire wrote is not in ${z(Z.config)}${N.exists?"":" (the file is gone)"} any more \u2014 opencode in git worktrees gets no myc tools; ${"`myc wire --scope user --agents opencode`"}`});else if(!sq(N.value,Z.mcp.command))G.push({name:H,verdict:"drift",detail:`changed after wire wrote it: now ${JSON.stringify(N.value)}, wire wrote ${Z.mcp.command.join(" ")}; \`myc wire --scope user --agents opencode\``});else if($F(N.value).enabled===!1)G.push({name:H,verdict:"n/a",detail:`myc's server in ${z(Z.config)} is disabled by hand ("enabled": false) \u2014 opencode does not start it`});else if(Z.mcp.command[0].startsWith("/")&&!E3(Z.mcp.command[0]))G.push({name:H,verdict:"drift",detail:`mcp.myc runs ${Z.mcp.command[0]}, which is not there \u2014 the server does not start; ${"`myc wire --scope user --agents opencode`"} with a myc that exists`});else G.push({name:H,verdict:"ok",detail:`in ${z(Z.config)}: ${Z.mcp.command.join(" ")}`});return G}function c90($,X,Z,Y,z,J){let U=k3(X);if(U===null)return{name:$,verdict:"drift",detail:`gone: the journal remembers it, but the file is not on disk \u2014 myc does nothing there; ${J}`};let K=D4(U),W=D4(Y);if(K===W)return{name:$,verdict:"ok",detail:`up to date: matches what this build (myc ${E0}) writes (${K})`};if(K===Z)return{name:$,verdict:"drift",detail:`stale: exactly what ${J} wrote (${z}, ${Z}), but this build (myc ${E0}) writes a different one (${W}) \u2014 rerun ${J}`};return{name:$,verdict:"drift",detail:`changed after we wrote it: on disk (${K}) is neither what wire wrote (${Z}) nor what this build writes (${W}) \u2014 ${J} restores ours, the current one goes to .myc.bak`}}function i90($,X,Z,Y,z){let J=Y$.filter((N)=>Z.hasTop(N.command)).map((N)=>N.event),U=k3($.helper),K=X.bin??(U!==null?l90(U):void 0)??"myc",W=s9($,J,X.hook_output,K),V=new Map([[$.helper,W.helper],[$.queueHelper,W.queueHelper],[$.skill,W.skill]]),G=X.version!==void 0?`myc ${X.version}`:"an earlier myc",H=[];for(let N of X.files){let Q=V.get(N.path);if(Q===void 0)continue;let L=`user:${z(N.path)}`,B=k3(N.path);if(B===null){H.push({name:L,verdict:"drift",detail:"gone: the journal remembers it, but the file is not on disk \u2014 the hooks that call it exit quietly, so myc "+"does nothing there; `myc wire --scope user`"});continue}let T=D4(B),q=D4(Q);if(T===q)H.push({name:L,verdict:"ok",detail:`up to date: matches what this build (myc ${E0}) writes (${T})`});else if(T===N.hash)H.push({name:L,verdict:"drift",detail:`stale: exactly what \`myc wire --scope user\` wrote (${G}, ${N.hash}), but this build (myc ${E0}) writes a different one (${q}) \u2014 rerun \`myc wire --scope user\``});else H.push({name:L,verdict:"drift",detail:`changed after we wrote it: on disk (${T}) is neither what wire wrote (${N.hash}) nor what this build writes (${q}) \u2014 \`myc wire --scope user\` restores ours, the current one goes to .myc.bak`})}return H}function n90($,X,Z,Y){if(Z.broken)return{name:"user:statusLine",verdict:"unknown",detail:`${Y($.settings)} is not valid JSON \u2014 can't see the status line`};let J=Z.value?.statusLine,U=X.status_line;if(U===void 0){if(Y6(J))return{name:"user:statusLine",verdict:"drift",detail:`myc's line is in ${Y($.settings)} with no record in ${Y($.journal)} of the line it replaced \u2014 `+"that line gets no input; `myc wire --scope user --status-line` records what is known"};return{name:"user:statusLine",verdict:"n/a",detail:"not installed (`myc wire --scope user --status-line` puts myc's line there)"}}let K=Z8(U.previous)!==null?`the previous line ${Ob(U.previous)} gets the same input`:"there was no previous line";if(J===void 0)return{name:"user:statusLine",verdict:"drift",detail:`gone: myc's line was removed from ${Y($.settings)} after wire, and the line it replaced gets no input either; \`myc wire --scope user --status-line\` puts it back, \`myc wire --scope user\` forgets it`};if(!Y6(J))return{name:"user:statusLine",verdict:"drift",detail:`no longer myc's: now ${Ob(J)} \u2014 replaced after wire. \`myc wire --scope user --status-line\` puts ours `+"back and keeps this one as the previous line (it keeps getting the same input); `myc wire --scope user` accepts it and forgets ours"};let W=Z8(J)??"";if(X.bin!==void 0&&W===aK({command:X.bin})&&X.bin.startsWith("/")&&!E3(X.bin))return{name:"user:statusLine",verdict:"drift",detail:`myc's line runs ${X.bin}, which is not there \u2014 the line is empty and the previous line gets no input; `+"`myc wire --scope user --status-line` with a myc that exists"};return{name:"user:statusLine",verdict:"ok",detail:`myc's line (${Pb(W)}); ${K}`}}function d90($,X,Z){let z=X.mcp,J=z?.config??$.claudeJson,U=dq(J);if(U.broken)return{name:"user:mcp",verdict:"unknown",detail:`${Z(J)} is not valid JSON \u2014 can't see whether myc is registered`};let K="`myc wire --scope user` (it runs `claude mcp add --scope user myc -- <myc> mcp --profile agent`)";if(z===null){if(U.value!==void 0)return{name:"user:mcp",verdict:"n/a",detail:`a server named myc is registered in ${Z(J)}, not by wire \u2014 not checked`};return{name:"user:mcp",verdict:"drift",detail:`not registered in the user layer (wire could not do it): agents in git worktrees get no myc tools; ${K}`}}if(U.value===void 0)return{name:"user:mcp",verdict:"drift",detail:`gone: the MCP server myc wire registered is not in ${Z(J)} any more \u2014 agents in git worktrees get no myc tools; ${K}`};let W=U.value.command,V=XF(U.value.args);if(W!==z.command||JSON.stringify(V)!==JSON.stringify(z.args))return{name:"user:mcp",verdict:"drift",detail:`changed after wire registered it: now ${[W,...V].map(String).join(" ")}, wire registered ${[z.command,...z.args].join(" ")}; ${K}`};if(z.command.startsWith("/")&&!E3(z.command))return{name:"user:mcp",verdict:"drift",detail:`registered, but ${z.command} is not there \u2014 the server does not start; ${K}`};return{name:"user:mcp",verdict:"ok",detail:`registered: ${[z.command,...z.args].join(" ")}`}}function Mb(){let $;try{$=K6()}catch(z){let J=z instanceof L$?` \u2014 fix: ${z.hint}`:"";return{checks:[{name:"library",verdict:"drift",detail:`${z instanceof Error?z.message:String(z)}${J}`}]}}let X=$.support==="ok"?"ok":$.support==="old"?"unknown":"drift",Z=`SQLite ${$.version} \u2014 ${y4($)}`,Y=[{name:"library",verdict:X,detail:$.support==="ok"?Z:`${$.problem} \u2014 fix: ${$.hint}`,items:[...$.locked!==null?[$.locked]:[],...$.skipped.map((z)=>`passed over: ${z}`)]},{name:"open paths",verdict:X,detail:`cli (show/ready/close/create), cli+vec0 (recall, drain), engine, mcp, web \u2014 each chooses the library before its first connection, the same way: ${Z}`}];if($.support!=="unsupported")try{let z=l$().vec;Y.push(z.loaded?{name:"vec0",verdict:"ok",detail:`${z.version} \u2014 ${z.path}`}:{name:"vec0",verdict:"unknown",detail:`not loaded \u2014 recall falls back to BM25: ${z.reason}`})}catch(z){Y.push({name:"vec0",verdict:"drift",detail:z instanceof Error?z.message:String(z)})}return{checks:Y}}function a90($,X){if(X==="schema")return $.schema?.checks??[];if(X==="recount")return $.recount?.checks??[];if(X==="background")return $.background?.checks??[];return $.hooks?.checks??[]}function QW($,X){let Z=[`database ${$.db}`];for(let Y of $.sqlite!==void 0?["sqlite",...$.sections]:$.sections){let z=Y==="sqlite"?$.sqlite.checks:a90($,Y);Z.push(`${s90[Y]??Y}`);for(let J of z){if(Z.push(` ${o90[J.verdict]} ${J.name}: ${J.detail}`),!X)continue;for(let U of J.items??[])Z.push(` ${U}`)}}return Z}function r90($){let X=0,Z=0;for(let Y of $)if(Y.verdict==="drift")X++;else if(Y.verdict==="unknown")Z++;return{drift:X,unknown:Z}}function t90($){let X=$.globals.db;if(X!==void 0)return{path:Cb(X)};let Z=K$($.globals.directory??process.cwd());if("dbPath"in Z)return{path:Z.dbPath};return HW("ws.not_initialized",`workspace not initialized: looked in ${Z.searched.join(", ")}`,7,"myc init")}function e90($,X={}){let Z=X.env??process.env;return{name:"doctor",summary:"check what the database claims against what can be recounted",flags:[{name:"schema",description:"schema version and object-level diff against this binary"},{name:"recount",description:"materialised counters against a recount from the graph"},{name:"hooks",description:"when each hook last fired, which events are not installed, and the user layer myc wire --scope user put in ~/.claude (and ~/.config/opencode)"},{name:"background",description:"whether the background after commands keeps up: anchor sweeps and code-index refreshes against local writes"},{name:"verbose",description:"list every diverging object, node and row, not just counts"}],help:"Exit 0 only when every checked item converges. A section that could not be checked is "+"reported as 'unknown' and never as 'ok' \u2014 a diagnostic that prints ok where it looked at "+"nothing is worse than silence.\n\nThe database is opened WITHOUT running migrations, on purpose: a database written by a newer myc refuses to open on the normal path with `precond.schema`, and that failure is exactly what sends people here.\n\n--recount only compares. `parent_closure` and the edge rows are compared by running the real rebuild and the real reprojection inside a transaction that is always rolled back, so the file is left byte-for-byte unchanged and the check cannot drift from the repair it mirrors. Edge rows diverging from their OR-Set are repaired by `myc import`; twins (same content or same external ref), merge "+"cycles and a node with two live parents are reported and never repaired \u2014 the merge "+"resolved what it could and a human decides the rest.\n\n--hooks answers two questions. Did it fire: the counter is written only by a caller that declared itself through MYC_HOOK, so 'session-start fired N times' means sessions, not hand-typed `myc prime` calls. Is it the current hook: every file myc generates in full is hashed against what this build would generate, so a helper installed by an older version is reported as stale by name instead of silently doing nothing. The user layer (`myc wire --scope user`) is checked by ~/.myc/wire-user.json against ~/.claude: myc's hook entries and rules still there, its helpers what this build writes, its status line not replaced by another tool, its MCP server still registered (~/.claude.json is only read); with opencode wired (--agents opencode), its plugin is what this build writes and mcp.myc is still in opencode's global config (read as JSONC, never written).\n\n--background compares the marks the background leaves after commands (anchor_swept_at, "+"code_indexed_at) with local writes in the oplog. Age alone is not evidence \u2014 an idle "+"workspace has old marks by right; drift is a mark more than two periods overdue while local writes kept coming for a whole period after that: commands ran, the background after them did not.",handler:async(Y)=>{let z={schema:Y.flags.schema===!0,recount:Y.flags.recount===!0,hooks:Y.flags.hooks===!0,background:Y.flags.background===!0},J=!z.schema&&!z.recount&&!z.hooks&&!z.background,U=["schema","recount","hooks","background"].filter((B)=>J||z[B]),K=Y.flags.verbose===!0||!J,W=t90(Y);if("ok"in W)return W;let V=W.path;if(!E3(V))return HW("ws.not_initialized",`no database: ${V}`,7,"myc init");let G=eq(V),H=r9(Cb(Y.globals.directory??process.cwd()),".myc"),N=Mb(),Q;if(U.includes("schema")||U.includes("recount")||U.includes("background"))try{Q=X4(V,void 0,{extensions:!0})}catch(B){let T=N5(B);if(T!==void 0){let q=QW({db:V,sections:[],sqlite:N,ok:!1,unknown:0},!0);return{...T,msg:[T.msg,...q].join(`
|
|
8799
|
+
`)}}return HW("db.open",`cannot open the database: ${B instanceof Error?B.message:String(B)}`,1)}try{let B=U.includes("schema")?await k90(Q):void 0,T=U.includes("recount")?S90(Q):void 0,q=U.includes("hooks")?h90(G,H,$,Z):void 0,j=U.includes("background")?kg(Q.database,{env:Z,now:Date.now()}):void 0,O=[...N.checks,...B?.checks??[],...T?.checks??[],...q?.checks??[],...j?.checks??[]],{drift:A,unknown:R}=r90(O);for(let F of O)if(F.verdict==="drift")Y.warn("doctor.drift",`${F.name}: ${F.detail}`);else if(F.verdict==="unknown")Y.warn("doctor.unknown",`${F.name}: ${F.detail}`);let D={db:V,sections:[...U],sqlite:N,...B!==void 0?{schema:B}:{},...T!==void 0?{recount:T}:{},...q!==void 0?{hooks:q}:{},...j!==void 0?{background:j}:{},ok:A===0,unknown:R};if(A>0)return HW("precond.drift",[`drift: ${A}`,...QW(D,K)].join(`
|
|
8800
8800
|
`),5);return{ok:!0,data:D,meta:{drift:A,unknown:R}}}finally{Q?.close()}},renderHuman:(Y,z)=>{let J=Y,U=z.flags.verbose===!0||J.sections.length<4;return`${QW(J,U).join(`
|
|
8801
8801
|
`)}
|
|
8802
|
-
`}}}var I3,Ab=86400000,
|
|
8802
|
+
`}}}var I3,Ab=86400000,g90,o90,s90;var _b=v(()=>{n0();o();V0();B4();j0();Eg();R8();LY();l1();v8();q3();GW();I3=class I3 extends Error{rows;constructor($){super("rollback");this.rows=$}};g90=Y$.filter(($)=>$.event!=="stop").map(($)=>$.claudeEvent);o90={ok:"ok ",drift:"DRIFT ",unknown:"unknown ","n/a":"n/a "};s90={schema:"schema",recount:"counters",hooks:"hooks",background:"background"}});var kb={};s(kb,{createVersionCommand:()=>$Z0});function Ib($,X){return $.flags[X]===!0}function $Z0(){return{name:"version",summary:"print the build version; --check asks the registry for a newer one",flags:[{name:"check",description:"ask the npm registry for the latest version (the only network call myc makes)"},{name:"offline",description:"forbid the network for this call; --check then reports 'disabled', not 'up to date'"}],help:`Without --check there is no network at all: the verdict comes from the cache written by the last check, and its age is printed. With --check the npm registry is asked directly (explicit, human-typed, bounded by MYC_UPDATE_CHECK_TIMEOUT_MS, default 3000).
|
|
8803
8803
|
|
|
8804
8804
|
An unreachable registry is reported as 'could not check' with the reason and a WARN `+"line \u2014 never as 'no updates'. Versions are compared numerically, so 0.10.0 is newer than "+"0.9.0.\n\nOff switches, both directions: MYC_UPDATE_CHECK=0 forbids the network even for --check; --offline does the same for one call; MYC_UPDATE_CHECK=1 additionally enables a detached background check (at most once a day) from `myc init` and `myc wire`. The default is manual: myc never reaches the network on its own.\n\nUpdating itself is deliberately NOT automated: swapping the binary under a running agent "+"changes behaviour mid-session \u2014 the task lease is taken by one version and released by "+"another. The upgrade command is printed instead.",handler:async($)=>{let X=process.env,Z=Ib($,"offline"),Y=Ib($,"check"),z=Y?await $k({current:E0,env:X,offline:Z}):PL({current:E0,env:X,offline:Z});if(z.status==="unreachable")$.warn("update.unreachable",`the registry did not answer \u2014 updates NOT checked: ${z.reason}`);if(Y&&z.status==="disabled")$.warn("update.disabled",`update check forbidden: ${z.reason}`);return{ok:!0,data:{version:E0,schema:e4,package:N4,update:z,mode:v5(X),registry:AL(X)},meta:{checked:Y}}},renderHuman:($)=>{let X=$,Z=X.update,Y=[`myc ${X.version} (schema ${X.schema})`];switch(Z.status){case"update_available":Y.push(`update: ${Z.current} \u2192 ${Z.latest}`,` ${bU}`);break;case"up_to_date":Y.push(`latest in the registry: ${Z.latest} \u2014 nothing to update to`);break;case"ahead":Y.push(`the registry has ${Z.latest} \u2014 this build is newer than the published one`);break;case"unreachable":Y.push(`updates NOT checked: ${Z.reason}`);break;case"disabled":Y.push(`update check is off: ${Z.reason}`);break;case"never_checked":Y.push("updates never checked \u2014 `myc version --check`");break}if(Z.source==="cache"&&Z.age_ms!==void 0){if(DL(Z)!==null||Z.status==="up_to_date"||Z.status==="ahead")Y.push(` from cache, checked ${Math.max(1,Math.round(Z.age_ms/60000))} min ago`)}return Y.push(`registry: ${X.registry} \xB7 mode: ${X.mode} (MYC_UPDATE_CHECK)`),`${Y.join(`
|
|
8805
8805
|
`)}
|
|
8806
|
-
`}}}var Eb=v(()=>{v8();o();hU()});var{SQL:
|
|
8806
|
+
`}}}var Eb=v(()=>{v8();o();hU()});var{SQL:XZ0}=globalThis.Bun;function ZF($){let X;for(let[Z,Y]of Object.entries($))if(Y!==null&&typeof Y==="object"&&!(Y instanceof Uint8Array))X??={...$},X[Z]=JSON.stringify(Y);return X??$}function YF($){let X=(Z)=>{return r3(Z),NZ(Z,"pg")};return{dialect:"pg",async one(Z,Y){let z=await $.unsafe(X(Z),[...Y]);return z[0]===void 0?void 0:ZF(z[0])},async all(Z,Y){return(await $.unsafe(X(Z),[...Y])).map(ZF)},async run(Z,Y){let z=await $.unsafe(X(Z),[...Y]);return{changes:z.count??z.length}},async raw(Z,Y=[]){return(await $.unsafe(Z,[...Y])).map(ZF)}}}function YZ0($){try{let X=new URL($);if(X.searchParams.get("application_name")===null)X.searchParams.set("application_name",ZZ0);return X.toString()}catch{return $}}function NW($){let X=YZ0(typeof $==="string"?$:$.url),Z=typeof $==="string"?vb:$.max??vb;if(!Number.isInteger(Z)||Z<1)throw Error(`postgres: pool size must be a positive integer, got ${String(Z)}`);let Y=new XZ0({url:X,max:Z});return{...YF(Y),async withTenant(J,U){if(J.length===0)throw Error("postgres: tenant must not be empty \u2014 an empty tenant sees nothing (RLS fails closed)");return await Y.begin(async(K)=>{return await K.unsafe("SELECT set_config('myc.tenant', $1, true)",[J]),await U(YF(K))})},async withTransaction(J){return await Y.begin(async(U)=>J(YF(U)))},async close(){await Y.close()}}}var vb=10,ZZ0="myc";var zF=v(()=>{o()});var fb=`-- =============================================================================
|
|
8807
8807
|
-- myc \u2014 \u0441\u0445\u0435\u043C\u0430 PostgreSQL (M4, docs/design/01-core-data-model.md \xA78.2)
|
|
8808
8808
|
--
|
|
8809
8809
|
-- \u0417\u0410\u0427\u0415\u041C \u041E\u0422\u0414\u0415\u041B\u042C\u041D\u042B\u0419 \u0414\u0418\u0410\u041B\u0415\u041A\u0422. SQLite \u2014 \u044D\u0442\u043E \u043C\u0430\u0448\u0438\u043D\u0430 \u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u0430: \u043E\u0434\u0438\u043D \u043F\u0440\u043E\u0446\u0435\u0441\u0441,
|
|
@@ -9535,12 +9535,12 @@ ON CONFLICT (version) DO NOTHING;
|
|
|
9535
9535
|
SELECT max(version) AS v FROM schema_migrations
|
|
9536
9536
|
UNION ALL
|
|
9537
9537
|
SELECT max(version) AS v FROM ${y$}
|
|
9538
|
-
) t`);return X?.v==null?0:Number(X.v)}function UF($=X$){return $.reduce((X,Z)=>Math.max(X,Z.version),0)}function
|
|
9538
|
+
) t`);return X?.v==null?0:Number(X.v)}function UF($=X$){return $.reduce((X,Z)=>Math.max(X,Z.version),0)}function JZ0($){return $.pg??r0($.sql)}async function Sb($,X=X$){let Z=[...X].sort((U,K)=>U.version-K.version);if(!await JF($))throw Error("migrations must run as a role that sees every tenant's rows (superuser or BYPASSRLS): under the application role a data migration silently changes nothing and still records the version");let Y=await y3($),z=Z.filter((U)=>U.version>Y),J=[];for(let U of z){let K=JZ0(U).trim(),W=await UZ0(U.sql),G=U.readableFrom!==void 0?`INSERT INTO ${y$} (version, name, checksum, applied_at, readable_from)
|
|
9539
9539
|
VALUES (${U.version}, ${v3(U.name)}, ${v3(W)}, ${Date.now()}, ${U.readableFrom})`:`INSERT INTO schema_migrations (version, name, checksum, applied_at, by_version)
|
|
9540
|
-
VALUES (${U.version}, ${v3(U.name)}, ${v3(W)}, ${Date.now()}, ${v3("myc")})`;await $.withTransaction(async(H)=>{if(K.length>0)await H.raw(K);await H.raw(G)}),J.push(U.version)}return{appliedVersions:J,from:Y,to:await y3($)}}function v3($){return`'${$.replace(/'/g,"''")}'`}async function
|
|
9541
|
-
FROM api_tokens WHERE token_hash = $1`,[Y]))[0];if(J===void 0)return LW;let U=Buffer.from(J.token_hash,"hex"),K=Buffer.from(Y,"hex");if(U.length!==K.length||!
|
|
9540
|
+
VALUES (${U.version}, ${v3(U.name)}, ${v3(W)}, ${Date.now()}, ${v3("myc")})`;await $.withTransaction(async(H)=>{if(K.length>0)await H.raw(K);await H.raw(G)}),J.push(U.version)}return{appliedVersions:J,from:Y,to:await y3($)}}function v3($){return`'${$.replace(/'/g,"''")}'`}async function UZ0($){let X=await crypto.subtle.digest("SHA-256",new TextEncoder().encode($));return[...new Uint8Array(X)].map((Z)=>Z.toString(16).padStart(2,"0")).join("")}var gb=v(()=>{o();n0()});import{randomBytes as bb,timingSafeEqual as KZ0}from"crypto";function KF($){return BW.includes($)}function WF($){return $.split(",").map((X)=>X.trim()).filter((X)=>TW.includes(X))}function VF($,X){return $===void 0||$.scopes.includes(X)}function xb($,X){return $===void 0||$.ws===""||$.ws===X}function hb($){return new Bun.CryptoHasher("sha256").update($).digest("hex")}function VZ0(){return WZ0+bb(32).toString("base64url")}function mb($){let X=$.headers.get("authorization");if(X!==null){let Y=/^Bearer\s+(\S+)$/i.exec(X.trim());if(Y!==null)return Y[1]}let Z=$.headers.get("cookie");if(Z!==null)for(let Y of Z.split(";")){let[z,...J]=Y.trim().split("=");if(z===GF&&J.length>0)return decodeURIComponent(J.join("="))}return null}async function HF($,X,Z=Date.now()){if(X===null||X.length===0)return{ok:!1,code:"denied.no_token",msg:"no token: send Authorization: Bearer <token>"};let Y=hb(X),J=(await $.raw(`SELECT id, tenant_id, subject, token_hash, expires_at, revoked_at, role, scopes, ws
|
|
9541
|
+
FROM api_tokens WHERE token_hash = $1`,[Y]))[0];if(J===void 0)return LW;let U=Buffer.from(J.token_hash,"hex"),K=Buffer.from(Y,"hex");if(U.length!==K.length||!KZ0(U,K))return LW;if(J.revoked_at!==null)return LW;if(J.expires_at!==null&&Number(J.expires_at)<=Z)return LW;$.raw("UPDATE api_tokens SET last_used_at = $1 WHERE id = $2",[Z,J.id]).catch(()=>{return});let W=KF(J.role)?J.role:"viewer",V=J.scopes.trim()===""?wb[W]:WF(J.scopes);return{ok:!0,principal:{token_id:J.id,tenant:J.tenant_id,subject:J.subject,role:W,scopes:V,ws:J.ws??""}}}async function QF($,X,Z,Y={}){if(X.length===0||Z.length===0)throw Error("token: tenant and subject must not be empty");let z=Y.now??Date.now(),J=VZ0(),U=`tok_${bb(6).toString("hex")}`,K=Y.role??"member",W=Y.scopes??wb[K],V=Y.ws??"";return await $.raw(`INSERT INTO api_tokens (id, tenant_id, subject, token_hash, created_at, expires_at, role, scopes, ws)
|
|
9542
9542
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,[U,X,Z,hb(J),z,Y.expiresAt??null,K,W.join(","),V]),{id:U,token:J,tenant:X,subject:Z,role:K,scopes:W,ws:V}}async function ub($,X,Z=Date.now()){return(await $.raw("UPDATE api_tokens SET revoked_at = $1 WHERE id = $2 AND revoked_at IS NULL RETURNING id",[Z,X])).length>0}async function lb($){return(await $.raw(`SELECT id, tenant_id, subject, created_at, expires_at, revoked_at, last_used_at, role, scopes, ws
|
|
9543
|
-
FROM api_tokens ORDER BY tenant_id, subject, created_at`)).map((Z)=>({id:Z.id,tenant:Z.tenant_id,subject:Z.subject,role:Z.role,scopes:Z.scopes,ws:Z.ws??"",created_at:Number(Z.created_at),expires_at:Z.expires_at===null?null:Number(Z.expires_at),revoked_at:Z.revoked_at===null?null:Number(Z.revoked_at),last_used_at:Z.last_used_at===null?null:Number(Z.last_used_at)}))}function pb($,X,Z=2592000){let Y=[`${GF}=${encodeURIComponent($)}`,"Path=/","HttpOnly","SameSite=Strict",`Max-Age=${Z}`];if(X)Y.push("Secure");return Y.join("; ")}function cb(){return`${GF}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`}function ib($){let X=$.headers.get("x-forwarded-proto");if(X!==null)return X.split(",")[0].trim()==="https";return new URL($.url).protocol==="https:"}var
|
|
9543
|
+
FROM api_tokens ORDER BY tenant_id, subject, created_at`)).map((Z)=>({id:Z.id,tenant:Z.tenant_id,subject:Z.subject,role:Z.role,scopes:Z.scopes,ws:Z.ws??"",created_at:Number(Z.created_at),expires_at:Z.expires_at===null?null:Number(Z.expires_at),revoked_at:Z.revoked_at===null?null:Number(Z.revoked_at),last_used_at:Z.last_used_at===null?null:Number(Z.last_used_at)}))}function pb($,X,Z=2592000){let Y=[`${GF}=${encodeURIComponent($)}`,"Path=/","HttpOnly","SameSite=Strict",`Max-Age=${Z}`];if(X)Y.push("Secure");return Y.join("; ")}function cb(){return`${GF}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`}function ib($){let X=$.headers.get("x-forwarded-proto");if(X!==null)return X.split(",")[0].trim()==="https";return new URL($.url).protocol==="https:"}var WZ0="myc_",BW,TW,wb,GF="myc_token",LW;var NF=v(()=>{BW=["owner","maintainer","member","agent","viewer"],TW=["read","write","claim","sync","admin"],wb=Object.freeze({owner:["read","write","claim","sync","admin"],maintainer:["read","write","claim","sync","admin"],member:["read","write","claim"],agent:["read","write","claim"],viewer:["read"]});LW={ok:!1,code:"denied.bad_token",msg:"unknown, revoked or expired token"}});async function LF($){let[X]=await $.raw(`SELECT current_user AS role,
|
|
9544
9544
|
rolsuper AS superuser,
|
|
9545
9545
|
rolbypassrls AS bypass,
|
|
9546
9546
|
version() AS ver
|
|
@@ -9566,10 +9566,10 @@ ON CONFLICT (version) DO NOTHING;
|
|
|
9566
9566
|
${Z===void 0?"":`<div class="facts">signed in as ${U6(Z.subject)} \xB7 tenant ${U6(Z.tenant)} \xB7 <a href="/v1/auth/session">sign out</a></div>`}
|
|
9567
9567
|
<div class="facts">${U6($.postgres)} \xB7 pgvector ${U6($.pgvector??"none")} \xB7 schema ${U6($.schema??"none")} \xB7
|
|
9568
9568
|
role ${U6($.role)} \xB7 RLS: policy on ${$.rls.with_policy} of ${$.rls.tables} tables, FORCE on ${$.rls.forced} \xB7
|
|
9569
|
-
database ${
|
|
9569
|
+
database ${GZ0($.database_bytes)}</div>
|
|
9570
9570
|
${Y}
|
|
9571
9571
|
${X.length===0?'<p class="dim">no tenants: the tenants registry is empty</p>':z}
|
|
9572
|
-
</body></html>`}var w8=($)=>$===null||$===void 0?0:Number($),U6=($)=>$.replace(/[&<>"]/g,(X)=>({"&":"&","<":"<",">":">",'"':"""})[X]),
|
|
9572
|
+
</body></html>`}var w8=($)=>$===null||$===void 0?0:Number($),U6=($)=>$.replace(/[&<>"]/g,(X)=>({"&":"&","<":"<",">":">",'"':"""})[X]),GZ0=($)=>`${($/1024/1024).toFixed(1)} MB`,nb=($)=>$===null||$===0?"\u2014":new Date($).toISOString().replace("T"," ").slice(0,16);function TF($){let X=/^\/v1\/ws\/([^/]+)(\/.*)?$/.exec($);if(X===null)return null;return{ws:decodeURIComponent(X[1]),rest:X[2]??""}}function t9($,X,Z){if($===null||$.trim()==="")return X;let Y=Number($);if(!Number.isFinite(Y)||Y<0)return X;return Math.min(Math.floor(Y),Z)}function FW($){let X=$.attrs;if(typeof X!=="string")return $;try{return{...$,attrs:JSON.parse(X)}}catch{return $}}async function sb($,X,Z){return(await $.withTenant(X,async(z)=>z.all(M4.ws_list,$7(Z)))).map((z)=>({ws:String(z.ws??""),nodes:Number(z.nodes??0),updated_at:Number(z.updated_at??0)}))}var ob=50,ab=500,qW=($,X)=>H6($,X),M4;var rb=v(()=>{o();M4=Z0({ws_nodes_list:{name:"ws_nodes_list",sql:`SELECT id, kind, layer, scope, title, excerpt, status, priority,
|
|
9573
9573
|
assignee, created_at, updated_at, attrs
|
|
9574
9574
|
FROM nodes
|
|
9575
9575
|
WHERE scope = ?1
|
|
@@ -9601,7 +9601,7 @@ ${X.length===0?'<p class="dim">no tenants: the tenants registry is empty</p>':z}
|
|
|
9601
9601
|
FROM nodes
|
|
9602
9602
|
WHERE deleted_at IS NULL AND scope <> ''${qW("nodes",1)}
|
|
9603
9603
|
GROUP BY scope
|
|
9604
|
-
ORDER BY scope`,params:["owner","team","agent"]}})});function I7($){return typeof $==="number"?$:Number($??0)}async function jF($,X,Z,Y,z,J="",U=O8,K=Date.now()){return $.withTenant(X,async(W)=>{let V=await W.one(n4.ready_touches_exist,[])!==void 0,G=J.length>0,H=G?V?jX.ready_top_anchors_repo_acl:jX.ready_top_noanchors_repo_acl:V?jX.ready_top_anchors_acl:jX.ready_top_noanchors_acl,N=[Z,U.priority,U.unblocks,U.freshness,U.anchors,U.type,Y,K],Q=$7(z),L=await W.all(H,G?[...N,J,...Q]:[...N,...Q]),B=[];for(let q of L){let j=String(q.id),O=await W.one(n4.ready_unblocks_one,[j]),A={};try{let F=q.attrs;A=typeof F==="string"&&F.length>0?JSON.parse(F):{}}catch{A={}}let R=typeof A.type==="string"?A.type:"task",D=typeof A.estimate_min==="number"?A.estimate_min:void 0;B.push({id:j,priority:I7(q.priority),status:String(q.status??""),assignee:String(q.assignee??""),title:String(q.title??""),updated_at:I7(q.updated_at),created_at:I7(q.created_at),score:I7(q.score),unblocks:I7(O?.n),type:R,...D!==void 0?{estimate_min:D}:{}})}let T=L.length>0?I7(L[0].total_ready):0;return{items:B,total:T}})}async function tb($,X,Z,Y,z,J,U){let K=await jF($,X,Z,J,U,z);return $.withTenant(X,async(W)=>{let V=await p$(rZ(Z,"project",void 0,Y,z,U),W),G=await W.one(J8.prime_node_count,[Z]),H=await W.all(J8.prime_inprogress,[Z,10]);return{digest:V,in_progress:H.map((N)=>({id:String(N.id),title:String(N.title??""),priority:I7(N.priority),assignee:String(N.assignee??""),lease_holder:String(N.lease_holder??""),lease_expires:I7(N.lease_expires)})),ready:K.items,total_ready:K.total,nodes:I7(G?.n)}})}var qF=10,FF=100;var eb=v(()=>{o()});function Yw($){if(typeof $!=="object"||$===null)return{ok:!1,error:{code:"usage.body",msg:"the body must be a JSON object"}};let X=$,Z=typeof X.title==="string"?X.title.trim():"";if(Z.length===0)return{ok:!1,error:{code:"usage.title",msg:"title must not be empty"}};if(Z.length>jW)return{ok:!1,error:{code:"usage.title",msg:`title must be at most ${jW} characters`}};let Y=typeof X.kind==="string"?X.kind:"";try{l8(Y)}catch{return{ok:!1,error:{code:"usage.kind",msg:`unknown node kind '${Y}'`}}}let z=X.priority===void 0?2:Number(X.priority);if(!Zw.has(z))return{ok:!1,error:{code:"usage.priority",msg:"priority must be 0, 1, 2 or 3"}};let J=typeof X.acl==="string"?X.acl:void 0;if(J!==void 0&&!Jz.includes(J))return{ok:!1,error:{code:"usage.acl",msg:`unknown acl '${J}': ${Jz.join("|")}`}};let U=typeof X.body==="string"?X.body:void 0,K=typeof X.assignee==="string"?X.assignee:void 0,W=typeof X.status==="string"?X.status:void 0,V=typeof X.attrs==="object"&&X.attrs!==null?X.attrs:void 0;return{ok:!0,data:{kind:Y,title:Z,body:U,priority:z,assignee:K,status:W,attrs:V,acl:J}}}function zw($){if(typeof $!=="object"||$===null)return{ok:!1,error:{code:"usage.body",msg:"the body must be a JSON object"}};let X=$,Z={};for(let z of $w)if(X[z]!==void 0)Z[z]=X[z];if(typeof Z.title==="string"){let z=Z.title.trim();if(z.length===0)return{ok:!1,error:{code:"usage.title",msg:"title must not be empty"}};if(z.length>jW)return{ok:!1,error:{code:"usage.title",msg:`title must be at most ${jW} characters`}};Z.title=z}if(Z.priority!==void 0&&!Zw.has(Number(Z.priority)))return{ok:!1,error:{code:"usage.priority",msg:"priority must be 0, 1, 2 or 3"}};if(typeof X.attrs==="object"&&X.attrs!==null)Z.attrs=X.attrs;let Y=Object.keys(X).filter((z)=>z!=="attrs"&&!$w.includes(z));if(Y.length>0)return{ok:!1,error:{code:"usage.field",msg:`these fields cannot be changed here: ${Y.join(", ")}`}};if(Object.keys(Z).length===0)return{ok:!1,error:{code:"usage.empty",msg:"nothing to change"}};return{ok:!0,data:Z}}async function s5($,X){let Z=await $.one(x.meta_get,["site_id"]);if(Z?.value!==void 0&&Z.value!=="")return Z.value;let Y=`srv-${n$(X).split("-").pop()??"0"}`;return await $.run(x.meta_set,["site_id",Y]),Y}function UZ0($,X,Z,Y,z){let J=[$.set(X,"kind",Y.kind),$.set(X,"scope",Z),$.set(X,"title",Y.title),$.set(X,"priority",Y.priority??2),$.set(X,"owner_id",z),$.set(X,"actor",z)];if(Y.acl!==void 0)J.push($.set(X,"acl",Y.acl));if(Y.body!==void 0)J.push($.set(X,"body",Y.body));if(J.push($.set(X,"status",BZ(Y.kind,Y.status??$z[Y.kind]))),Y.assignee!==void 0)J.push($.set(X,"assignee",Y.assignee));for(let[U,K]of Object.entries(Y.attrs??{}))J.push($.set(X,`attrs.${U}`,K));return J.push($.inc(X,"seen_count",1)),J}async function Jw($,X,Z,Y,z){return $.withTenant(X,async(J)=>{let U=await s5(J,Z),K=new o$(U,{clock:new u0}),W=n$(Z),V={actor:z,siteId:U,ops:K,now:()=>Date.now()};await p$(Q6(V),J);let G=UZ0(K,W,Z,Y,z),H=await p$(l4(V,G,1),J);return{id:W,applied:H.applied,collided:H.collided}})}async function Uw($,X,Z,Y,z,J){return $.withTenant(X,async(U)=>{let K=await U.one(x.node_head,[Y]);if(K===void 0||K.scope!==Z)return{ok:!1,error:{code:"notfound.node",msg:`no node ${Y} in workspace ${Z}`}};let W;try{W=jZ(K.kind,z)}catch(N){return{ok:!1,error:{code:"usage.value",msg:N instanceof U0?N.message:String(N)}}}if(W.length===0)return{ok:!1,error:{code:"usage.empty",msg:"nothing to change"}};let V=await s5(U,Z),G=new o$(V,{clock:new u0});return await p$(wZ({actor:J,siteId:V,ops:G,now:()=>Date.now()},()=>W.map(([N,Q])=>G.set(Y,N,Q)),Y,Z,(N)=>new U0("graph.clock_collision",`concurrent write to ${Y}.${N.field??N.op}`)),U),{ok:!0,data:{id:Y,changed:W.map(([N])=>N)}}})}function Kw($){if(typeof $!=="object"||$===null)return{ok:!1,error:{code:"usage.body",msg:"the body must be a JSON object"}};let X=$,Z=typeof X.from==="string"?X.from:"",Y=typeof X.to==="string"?X.to:"",z=typeof X.type==="string"?X.type:"";if(Z===""||Y==="")return{ok:!1,error:{code:"usage.endpoints",msg:"both 'from' and 'to' are required"}};if(Z===Y)return{ok:!1,error:{code:"usage.endpoints",msg:"an edge from a node to itself is not allowed"}};try{t6(z)}catch{return{ok:!1,error:{code:"usage.type",msg:`unknown edge type '${z}'`}}}let J=X.weight===void 0?void 0:Number(X.weight);if(J!==void 0&&!Number.isFinite(J))return{ok:!1,error:{code:"usage.weight",msg:"weight must be a number"}};let U=typeof X.attrs==="object"&&X.attrs!==null?X.attrs:void 0;return{ok:!0,data:{from:Z,to:Y,type:z,weight:J,attrs:U}}}async function Ww($,X,Z,Y){for(let z of[Z,Y]){let J=await $.one(x.node_head,[z]);if(J===void 0||J.scope!==X)return{code:"notfound.node",msg:`no node ${z} in workspace ${X}`}}return}async function Vw($,X,Z,Y,z){return $.withTenant(X,async(J)=>{let U=await Ww(J,Z,Y.from,Y.to);if(U!==void 0)return{ok:!1,error:U};let K=await s5(J,Z),W=new o$(K,{clock:new u0}),V={actor:z,siteId:K,ops:W,now:()=>Date.now()};try{await p$(BV(V,Y.from,Y.type,Y.to,Z,{weight:Y.weight,attrs:JSON.stringify(Y.attrs??{})},(G)=>new U0("graph.clock_collision",`concurrent write to edge ${G.entity_id}`)),J)}catch(G){if(G instanceof p0)return{ok:!1,error:{code:`precond.${G.code.replace("closure.","")}`,msg:G.message}};throw G}return{ok:!0,data:{from:Y.from,type:Y.type,to:Y.to}}})}async function Gw($,X,Z,Y,z){return $.withTenant(X,async(J)=>{let U=await Ww(J,Z,Y.from,Y.to);if(U!==void 0)return{ok:!1,error:U};let K=await s5(J,Z),W=new o$(K,{clock:new u0});return{ok:!0,data:{removed:await p$(xZ({actor:z,siteId:K,ops:W,now:()=>Date.now()},Y.from,Y.type,Y.to,Z),J)}}})}async function Qw($,X,Z,Y,z,J){if(!Number.isFinite(J)||J<=0||J>Xw)return{ok:!1,error:{code:"usage.lease",msg:`lease must be between 1 ms and ${Xw} ms`}};return $.withTenant(X,async(U)=>{let K=await U.one(x.node_head,[Y]);if(K===void 0||K.scope!==Z)return{ok:!1,error:{code:"notfound.node",msg:`no node ${Y} in workspace ${Z}`}};let W=await s5(U,Z),V=new o$(W,{clock:new u0}),H=await p$(hZ({actor:z,siteId:W,ops:V,now:()=>Date.now()},Y,z,J),U);if(H===void 0)return{ok:!1,error:{code:"conflict.claimed",msg:`task ${Y} is already taken or not open`}};let N={};try{N=typeof K.attrs==="string"&&K.attrs.length>0?JSON.parse(K.attrs):{}}catch{N={}}let Q=typeof N.type==="string"?N.type:K.kind;return{ok:!0,data:{...H,prev_status:K.status,type:Q,priority:Number(K.priority)}}})}var jW=500,Zw,$w,Hw,Xw=28800000;var OF=v(()=>{o();Zw=new Set([0,1,2,3]);$w=["title","body","status","priority","assignee","salience"];Hw=c8});function Nw($){if(typeof $!=="object"||$===null||Array.isArray($))return{ok:!1,error:{code:"usage.body",msg:"body must be a JSON object"}};let X=$,Z=X.site_id;if(typeof Z!=="string"||Z===""||Z.length>64)return{ok:!1,error:{code:"usage.site_id",msg:"'site_id' is required"}};let Y=EV(X.have);if(Y===void 0)return{ok:!1,error:{code:"usage.have",msg:"'have' must map site ids to non-negative clocks"}};let z=X.ops??[];if(!Array.isArray(z))return{ok:!1,error:{code:"usage.ops",msg:"'ops' must be an array"}};if(z.length>P8)return{ok:!1,error:{code:"usage.ops",msg:`a batch carries at most ${P8} operations, got ${z.length}`}};let J=[];for(let W=0;W<z.length;W++){let V=fV(z[W]);if(V===void 0)return{ok:!1,error:{code:"usage.ops",msg:`ops[${W}] is malformed`}};J.push(V)}let{want:U,dry:K}=X;if(U!==void 0&&typeof U!=="boolean")return{ok:!1,error:{code:"usage.want",msg:"'want' must be a boolean"}};if(K!==void 0&&typeof K!=="boolean")return{ok:!1,error:{code:"usage.dry",msg:"'dry' must be a boolean"}};if(K===!0&&Array.isArray(z)&&z.length>0)return{ok:!1,error:{code:"usage.dry",msg:"a dry run carries no operations: it changes nothing by definition"}};return{ok:!0,data:{site_id:Z,have:Y,ops:J,want:U!==!1,dry:K===!0}}}async function Lw($,X,Z,Y,z,J=Date.now()){return $.withTenant(X,async(U)=>{let K=await s5(U,Z),W={actor:z,siteId:K,ops:new o$(K,{clock:new u0}),now:()=>J},V=Y.dry===!0;if(Y.ops.length>0)await p$(l4(W,Y.ops,0),U);let G=Y.want===!1?{ops:[],more:!1}:await p$(tZ(Z,Y.have),U),H=await p$(eZ(Z),U);if(!V)await p$($2(Y.site_id,Y.have,0,J),U);return{site_id:K,accepted:V?[]:Y.ops.map((N)=>N.op_id),ops:G.ops,watermarks:H,more:G.more}})}var Bw=v(()=>{o();OF()});import{existsSync as KZ0}from"fs";import{join as WZ0}from"path";import{Database as VZ0}from"bun:sqlite";function QZ0($){if(!KZ0($))throw new r5("db.missing",`no database file: ${$}`);let X;try{X=new VZ0($,{readonly:!0})}catch(J){let U=J instanceof Error?J.message:String(J);throw new r5("db.open",`could not open the database read-only: ${U}`)}try{X.exec(`PRAGMA busy_timeout = ${HZ0}`),X.exec("PRAGMA query_only = 1")}catch{}let Z=new Set,Y=!1,z=()=>{if(Y)return;try{for(let J of X.query("SELECT name FROM sqlite_master WHERE type IN ('table','view')").all())Z.add(J.name)}catch{}Y=!0};return{one(J,U=[]){let K=X.query(J).get(...U);return K===null?void 0:K},all(J,U=[]){return X.query(J).all(...U)},has(J){return z(),Z.has(J)},meta(J){if(z(),!Z.has("myc_meta"))return;return this.one("SELECT value FROM myc_meta WHERE key = ?1",[J])?.value},close(){X.close()}}}function f3($,X){return $.one(X)?.n??0}function NZ0($){let X=[],Z=$.has("myc_health")?$.all("SELECT component, state, reason, since FROM myc_health ORDER BY component").map((V)=>({component:String(V.component),state:String(V.state),reason:String(V.reason??""),since:Number(V.since??0)})):[];for(let V of Z){if(V.state==="ok")continue;X.push({code:`health.${V.component}`,msg:`${V.component}: ${V.state}${V.reason.length>0?` \u2014 ${V.reason}`:""}`})}let Y=$.has("nodes")?f3($,"SELECT count(*) AS n FROM nodes WHERE deleted_at IS NULL"):0,z=$.meta("embed_fingerprint")??null;if(z===null)X.push({code:"embeddings.off",msg:"the embedding model has never written a vector (myc_meta.embed_fingerprint is empty) \u2014 "+"the vector branch of search and the absorb cosine are unavailable, semantics cut down to FTS"});let J=$.has("schema_migrations_vec")&&f3($,"SELECT count(*) AS n FROM schema_migrations_vec")>0;if(!J)X.push({code:"vector.unavailable",msg:"the sqlite-vec extension (vec0) was never loaded: vector migrations are not applied \u2014 "+"vector search is off, the other surfaces work"});let U=0;if($.has("nodes_vec"))try{U=f3($,"SELECT count(*) AS n FROM nodes_vec")}catch{}let K=$.has("jobs")?f3($,"SELECT count(*) AS n FROM jobs WHERE attempts < max_attempts"):0,W=$.has("jobs")?f3($,"SELECT count(*) AS n FROM jobs WHERE attempts >= max_attempts"):0;if(W>0)X.push({code:"jobs.failed",msg:`${W} background jobs ran out of attempts \u2014 some nodes will stay unprocessed`});return{ok:X.length===0,degraded:X.map((V)=>V.code),warn:X,nodes:Y,vectors:U,queue:K,failed:W,fts:$.has("nodes_fts")?"ok":"missing",vec:J?"ok":"unavailable",embed_fingerprint:z,components:Z}}function n6($,X,Z,Y={}){return A0({ok:!0,cmd:$,ws:X,ts:new Date().toISOString(),data:Z,meta:{degraded:[],...Y},warn:[]})}function A0($,X=200){return new Response(JSON.stringify($),{status:X,headers:{"content-type":"application/json; charset=utf-8"}})}function LZ0($){if($.db!==void 0)return $.db;return WZ0($.dir??process.cwd(),".myc","myc.db")}function Tw($){return`<!doctype html>
|
|
9604
|
+
ORDER BY scope`,params:["owner","team","agent"]}})});function I7($){return typeof $==="number"?$:Number($??0)}async function jF($,X,Z,Y,z,J="",U=O8,K=Date.now()){return $.withTenant(X,async(W)=>{let V=await W.one(n4.ready_touches_exist,[])!==void 0,G=J.length>0,H=G?V?jX.ready_top_anchors_repo_acl:jX.ready_top_noanchors_repo_acl:V?jX.ready_top_anchors_acl:jX.ready_top_noanchors_acl,N=[Z,U.priority,U.unblocks,U.freshness,U.anchors,U.type,Y,K],Q=$7(z),L=await W.all(H,G?[...N,J,...Q]:[...N,...Q]),B=[];for(let q of L){let j=String(q.id),O=await W.one(n4.ready_unblocks_one,[j]),A={};try{let F=q.attrs;A=typeof F==="string"&&F.length>0?JSON.parse(F):{}}catch{A={}}let R=typeof A.type==="string"?A.type:"task",D=typeof A.estimate_min==="number"?A.estimate_min:void 0;B.push({id:j,priority:I7(q.priority),status:String(q.status??""),assignee:String(q.assignee??""),title:String(q.title??""),updated_at:I7(q.updated_at),created_at:I7(q.created_at),score:I7(q.score),unblocks:I7(O?.n),type:R,...D!==void 0?{estimate_min:D}:{}})}let T=L.length>0?I7(L[0].total_ready):0;return{items:B,total:T}})}async function tb($,X,Z,Y,z,J,U){let K=await jF($,X,Z,J,U,z);return $.withTenant(X,async(W)=>{let V=await p$(rZ(Z,"project",void 0,Y,z,U),W),G=await W.one(J8.prime_node_count,[Z]),H=await W.all(J8.prime_inprogress,[Z,10]);return{digest:V,in_progress:H.map((N)=>({id:String(N.id),title:String(N.title??""),priority:I7(N.priority),assignee:String(N.assignee??""),lease_holder:String(N.lease_holder??""),lease_expires:I7(N.lease_expires)})),ready:K.items,total_ready:K.total,nodes:I7(G?.n)}})}var qF=10,FF=100;var eb=v(()=>{o()});function Yw($){if(typeof $!=="object"||$===null)return{ok:!1,error:{code:"usage.body",msg:"the body must be a JSON object"}};let X=$,Z=typeof X.title==="string"?X.title.trim():"";if(Z.length===0)return{ok:!1,error:{code:"usage.title",msg:"title must not be empty"}};if(Z.length>jW)return{ok:!1,error:{code:"usage.title",msg:`title must be at most ${jW} characters`}};let Y=typeof X.kind==="string"?X.kind:"";try{l8(Y)}catch{return{ok:!1,error:{code:"usage.kind",msg:`unknown node kind '${Y}'`}}}let z=X.priority===void 0?2:Number(X.priority);if(!Zw.has(z))return{ok:!1,error:{code:"usage.priority",msg:"priority must be 0, 1, 2 or 3"}};let J=typeof X.acl==="string"?X.acl:void 0;if(J!==void 0&&!Jz.includes(J))return{ok:!1,error:{code:"usage.acl",msg:`unknown acl '${J}': ${Jz.join("|")}`}};let U=typeof X.body==="string"?X.body:void 0,K=typeof X.assignee==="string"?X.assignee:void 0,W=typeof X.status==="string"?X.status:void 0,V=typeof X.attrs==="object"&&X.attrs!==null?X.attrs:void 0;return{ok:!0,data:{kind:Y,title:Z,body:U,priority:z,assignee:K,status:W,attrs:V,acl:J}}}function zw($){if(typeof $!=="object"||$===null)return{ok:!1,error:{code:"usage.body",msg:"the body must be a JSON object"}};let X=$,Z={};for(let z of $w)if(X[z]!==void 0)Z[z]=X[z];if(typeof Z.title==="string"){let z=Z.title.trim();if(z.length===0)return{ok:!1,error:{code:"usage.title",msg:"title must not be empty"}};if(z.length>jW)return{ok:!1,error:{code:"usage.title",msg:`title must be at most ${jW} characters`}};Z.title=z}if(Z.priority!==void 0&&!Zw.has(Number(Z.priority)))return{ok:!1,error:{code:"usage.priority",msg:"priority must be 0, 1, 2 or 3"}};if(typeof X.attrs==="object"&&X.attrs!==null)Z.attrs=X.attrs;let Y=Object.keys(X).filter((z)=>z!=="attrs"&&!$w.includes(z));if(Y.length>0)return{ok:!1,error:{code:"usage.field",msg:`these fields cannot be changed here: ${Y.join(", ")}`}};if(Object.keys(Z).length===0)return{ok:!1,error:{code:"usage.empty",msg:"nothing to change"}};return{ok:!0,data:Z}}async function s5($,X){let Z=await $.one(x.meta_get,["site_id"]);if(Z?.value!==void 0&&Z.value!=="")return Z.value;let Y=`srv-${n$(X).split("-").pop()??"0"}`;return await $.run(x.meta_set,["site_id",Y]),Y}function HZ0($,X,Z,Y,z){let J=[$.set(X,"kind",Y.kind),$.set(X,"scope",Z),$.set(X,"title",Y.title),$.set(X,"priority",Y.priority??2),$.set(X,"owner_id",z),$.set(X,"actor",z)];if(Y.acl!==void 0)J.push($.set(X,"acl",Y.acl));if(Y.body!==void 0)J.push($.set(X,"body",Y.body));if(J.push($.set(X,"status",BZ(Y.kind,Y.status??$z[Y.kind]))),Y.assignee!==void 0)J.push($.set(X,"assignee",Y.assignee));for(let[U,K]of Object.entries(Y.attrs??{}))J.push($.set(X,`attrs.${U}`,K));return J.push($.inc(X,"seen_count",1)),J}async function Jw($,X,Z,Y,z){return $.withTenant(X,async(J)=>{let U=await s5(J,Z),K=new o$(U,{clock:new u0}),W=n$(Z),V={actor:z,siteId:U,ops:K,now:()=>Date.now()};await p$(Q6(V),J);let G=HZ0(K,W,Z,Y,z),H=await p$(l4(V,G,1),J);return{id:W,applied:H.applied,collided:H.collided}})}async function Uw($,X,Z,Y,z,J){return $.withTenant(X,async(U)=>{let K=await U.one(x.node_head,[Y]);if(K===void 0||K.scope!==Z)return{ok:!1,error:{code:"notfound.node",msg:`no node ${Y} in workspace ${Z}`}};let W;try{W=jZ(K.kind,z)}catch(N){return{ok:!1,error:{code:"usage.value",msg:N instanceof U0?N.message:String(N)}}}if(W.length===0)return{ok:!1,error:{code:"usage.empty",msg:"nothing to change"}};let V=await s5(U,Z),G=new o$(V,{clock:new u0});return await p$(wZ({actor:J,siteId:V,ops:G,now:()=>Date.now()},()=>W.map(([N,Q])=>G.set(Y,N,Q)),Y,Z,(N)=>new U0("graph.clock_collision",`concurrent write to ${Y}.${N.field??N.op}`)),U),{ok:!0,data:{id:Y,changed:W.map(([N])=>N)}}})}function Kw($){if(typeof $!=="object"||$===null)return{ok:!1,error:{code:"usage.body",msg:"the body must be a JSON object"}};let X=$,Z=typeof X.from==="string"?X.from:"",Y=typeof X.to==="string"?X.to:"",z=typeof X.type==="string"?X.type:"";if(Z===""||Y==="")return{ok:!1,error:{code:"usage.endpoints",msg:"both 'from' and 'to' are required"}};if(Z===Y)return{ok:!1,error:{code:"usage.endpoints",msg:"an edge from a node to itself is not allowed"}};try{t6(z)}catch{return{ok:!1,error:{code:"usage.type",msg:`unknown edge type '${z}'`}}}let J=X.weight===void 0?void 0:Number(X.weight);if(J!==void 0&&!Number.isFinite(J))return{ok:!1,error:{code:"usage.weight",msg:"weight must be a number"}};let U=typeof X.attrs==="object"&&X.attrs!==null?X.attrs:void 0;return{ok:!0,data:{from:Z,to:Y,type:z,weight:J,attrs:U}}}async function Ww($,X,Z,Y){for(let z of[Z,Y]){let J=await $.one(x.node_head,[z]);if(J===void 0||J.scope!==X)return{code:"notfound.node",msg:`no node ${z} in workspace ${X}`}}return}async function Vw($,X,Z,Y,z){return $.withTenant(X,async(J)=>{let U=await Ww(J,Z,Y.from,Y.to);if(U!==void 0)return{ok:!1,error:U};let K=await s5(J,Z),W=new o$(K,{clock:new u0}),V={actor:z,siteId:K,ops:W,now:()=>Date.now()};try{await p$(BV(V,Y.from,Y.type,Y.to,Z,{weight:Y.weight,attrs:JSON.stringify(Y.attrs??{})},(G)=>new U0("graph.clock_collision",`concurrent write to edge ${G.entity_id}`)),J)}catch(G){if(G instanceof p0)return{ok:!1,error:{code:`precond.${G.code.replace("closure.","")}`,msg:G.message}};throw G}return{ok:!0,data:{from:Y.from,type:Y.type,to:Y.to}}})}async function Gw($,X,Z,Y,z){return $.withTenant(X,async(J)=>{let U=await Ww(J,Z,Y.from,Y.to);if(U!==void 0)return{ok:!1,error:U};let K=await s5(J,Z),W=new o$(K,{clock:new u0});return{ok:!0,data:{removed:await p$(xZ({actor:z,siteId:K,ops:W,now:()=>Date.now()},Y.from,Y.type,Y.to,Z),J)}}})}async function Qw($,X,Z,Y,z,J){if(!Number.isFinite(J)||J<=0||J>Xw)return{ok:!1,error:{code:"usage.lease",msg:`lease must be between 1 ms and ${Xw} ms`}};return $.withTenant(X,async(U)=>{let K=await U.one(x.node_head,[Y]);if(K===void 0||K.scope!==Z)return{ok:!1,error:{code:"notfound.node",msg:`no node ${Y} in workspace ${Z}`}};let W=await s5(U,Z),V=new o$(W,{clock:new u0}),H=await p$(hZ({actor:z,siteId:W,ops:V,now:()=>Date.now()},Y,z,J),U);if(H===void 0)return{ok:!1,error:{code:"conflict.claimed",msg:`task ${Y} is already taken or not open`}};let N={};try{N=typeof K.attrs==="string"&&K.attrs.length>0?JSON.parse(K.attrs):{}}catch{N={}}let Q=typeof N.type==="string"?N.type:K.kind;return{ok:!0,data:{...H,prev_status:K.status,type:Q,priority:Number(K.priority)}}})}var jW=500,Zw,$w,Hw,Xw=28800000;var OF=v(()=>{o();Zw=new Set([0,1,2,3]);$w=["title","body","status","priority","assignee","salience"];Hw=c8});function Nw($){if(typeof $!=="object"||$===null||Array.isArray($))return{ok:!1,error:{code:"usage.body",msg:"body must be a JSON object"}};let X=$,Z=X.site_id;if(typeof Z!=="string"||Z===""||Z.length>64)return{ok:!1,error:{code:"usage.site_id",msg:"'site_id' is required"}};let Y=EV(X.have);if(Y===void 0)return{ok:!1,error:{code:"usage.have",msg:"'have' must map site ids to non-negative clocks"}};let z=X.ops??[];if(!Array.isArray(z))return{ok:!1,error:{code:"usage.ops",msg:"'ops' must be an array"}};if(z.length>P8)return{ok:!1,error:{code:"usage.ops",msg:`a batch carries at most ${P8} operations, got ${z.length}`}};let J=[];for(let W=0;W<z.length;W++){let V=fV(z[W]);if(V===void 0)return{ok:!1,error:{code:"usage.ops",msg:`ops[${W}] is malformed`}};J.push(V)}let{want:U,dry:K}=X;if(U!==void 0&&typeof U!=="boolean")return{ok:!1,error:{code:"usage.want",msg:"'want' must be a boolean"}};if(K!==void 0&&typeof K!=="boolean")return{ok:!1,error:{code:"usage.dry",msg:"'dry' must be a boolean"}};if(K===!0&&Array.isArray(z)&&z.length>0)return{ok:!1,error:{code:"usage.dry",msg:"a dry run carries no operations: it changes nothing by definition"}};return{ok:!0,data:{site_id:Z,have:Y,ops:J,want:U!==!1,dry:K===!0}}}async function Lw($,X,Z,Y,z,J=Date.now()){return $.withTenant(X,async(U)=>{let K=await s5(U,Z),W={actor:z,siteId:K,ops:new o$(K,{clock:new u0}),now:()=>J},V=Y.dry===!0;if(Y.ops.length>0)await p$(l4(W,Y.ops,0),U);let G=Y.want===!1?{ops:[],more:!1}:await p$(tZ(Z,Y.have),U),H=await p$(eZ(Z),U);if(!V)await p$($2(Y.site_id,Y.have,0,J),U);return{site_id:K,accepted:V?[]:Y.ops.map((N)=>N.op_id),ops:G.ops,watermarks:H,more:G.more}})}var Bw=v(()=>{o();OF()});import{existsSync as QZ0}from"fs";import{join as NZ0}from"path";import{Database as LZ0}from"bun:sqlite";function qZ0($){if(!QZ0($))throw new r5("db.missing",`no database file: ${$}`);let X;try{X=new LZ0($,{readonly:!0})}catch(J){let U=J instanceof Error?J.message:String(J);throw new r5("db.open",`could not open the database read-only: ${U}`)}try{X.exec(`PRAGMA busy_timeout = ${TZ0}`),X.exec("PRAGMA query_only = 1")}catch{}let Z=new Set,Y=!1,z=()=>{if(Y)return;try{for(let J of X.query("SELECT name FROM sqlite_master WHERE type IN ('table','view')").all())Z.add(J.name)}catch{}Y=!0};return{one(J,U=[]){let K=X.query(J).get(...U);return K===null?void 0:K},all(J,U=[]){return X.query(J).all(...U)},has(J){return z(),Z.has(J)},meta(J){if(z(),!Z.has("myc_meta"))return;return this.one("SELECT value FROM myc_meta WHERE key = ?1",[J])?.value},close(){X.close()}}}function f3($,X){return $.one(X)?.n??0}function FZ0($){let X=[],Z=$.has("myc_health")?$.all("SELECT component, state, reason, since FROM myc_health ORDER BY component").map((V)=>({component:String(V.component),state:String(V.state),reason:String(V.reason??""),since:Number(V.since??0)})):[];for(let V of Z){if(V.state==="ok")continue;X.push({code:`health.${V.component}`,msg:`${V.component}: ${V.state}${V.reason.length>0?` \u2014 ${V.reason}`:""}`})}let Y=$.has("nodes")?f3($,"SELECT count(*) AS n FROM nodes WHERE deleted_at IS NULL"):0,z=$.meta("embed_fingerprint")??null;if(z===null)X.push({code:"embeddings.off",msg:"the embedding model has never written a vector (myc_meta.embed_fingerprint is empty) \u2014 "+"the vector branch of search and the absorb cosine are unavailable, semantics cut down to FTS"});let J=$.has("schema_migrations_vec")&&f3($,"SELECT count(*) AS n FROM schema_migrations_vec")>0;if(!J)X.push({code:"vector.unavailable",msg:"the sqlite-vec extension (vec0) was never loaded: vector migrations are not applied \u2014 "+"vector search is off, the other surfaces work"});let U=0;if($.has("nodes_vec"))try{U=f3($,"SELECT count(*) AS n FROM nodes_vec")}catch{}let K=$.has("jobs")?f3($,"SELECT count(*) AS n FROM jobs WHERE attempts < max_attempts"):0,W=$.has("jobs")?f3($,"SELECT count(*) AS n FROM jobs WHERE attempts >= max_attempts"):0;if(W>0)X.push({code:"jobs.failed",msg:`${W} background jobs ran out of attempts \u2014 some nodes will stay unprocessed`});return{ok:X.length===0,degraded:X.map((V)=>V.code),warn:X,nodes:Y,vectors:U,queue:K,failed:W,fts:$.has("nodes_fts")?"ok":"missing",vec:J?"ok":"unavailable",embed_fingerprint:z,components:Z}}function n6($,X,Z,Y={}){return A0({ok:!0,cmd:$,ws:X,ts:new Date().toISOString(),data:Z,meta:{degraded:[],...Y},warn:[]})}function A0($,X=200){return new Response(JSON.stringify($),{status:X,headers:{"content-type":"application/json; charset=utf-8"}})}function jZ0($){if($.db!==void 0)return $.db;return NZ0($.dir??process.cwd(),".myc","myc.db")}function Tw($){return`<!doctype html>
|
|
9605
9605
|
<html lang="en"><head><meta charset="utf-8"><title>myc \u2014 server sign-in</title>
|
|
9606
9606
|
<style>body{font:14px/1.5 ui-monospace,Menlo,monospace;margin:6rem auto;max-width:26rem}
|
|
9607
9607
|
input{width:100%;padding:.5rem;font:inherit} button{margin-top:.5rem;padding:.5rem 1rem;font:inherit}
|
|
@@ -9613,18 +9613,18 @@ ${$===null?"":`<p class="err">${$}</p>`}
|
|
|
9613
9613
|
<button type="submit">sign in</button>
|
|
9614
9614
|
</form>
|
|
9615
9615
|
<p>Ask whoever runs this server for a token: <code>myc serve --pg <url> --add-token <tenant>:<name></code></p>
|
|
9616
|
-
</body></html>`}function qw($,X,Z){let Y=$ instanceof Error?$.message:String($),z=$?.code,J=typeof z==="string"&&/^(ECONNREFUSED|ENOTFOUND|ECONNRESET|ETIMEDOUT|EHOSTUNREACH)$/.test(z)||/connect|connection|terminated|timeout|socket|closed/i.test(Y);return A0(J?{ok:!1,cmd:X,...Z===void 0?{}:{ws:Z},error:{code:"db.query",msg:Y}}:{ok:!1,cmd:X,...Z===void 0?{}:{ws:Z},error:{code:"internal.unexpected",msg:Y}},J?503:500)}function Fw($){let X=
|
|
9616
|
+
</body></html>`}function qw($,X,Z){let Y=$ instanceof Error?$.message:String($),z=$?.code,J=typeof z==="string"&&/^(ECONNREFUSED|ENOTFOUND|ECONNRESET|ETIMEDOUT|EHOSTUNREACH)$/.test(z)||/connect|connection|terminated|timeout|socket|closed/i.test(Y);return A0(J?{ok:!1,cmd:X,...Z===void 0?{}:{ws:Z},error:{code:"db.query",msg:Y}}:{ok:!1,cmd:X,...Z===void 0?{}:{ws:Z},error:{code:"internal.unexpected",msg:Y}},J?503:500)}function Fw($){let X=jZ0($),Z=Date.now(),Y=()=>qZ0(X),z=$.pg===void 0?void 0:NW($.pg),J=async(G)=>{try{return await U(G)}catch(H){return qw(H,"serve")}},U=async(G)=>{let H=new URL(G.url);if(H.pathname==="/v1/health"&&G.method==="GET")return A0({ok:!0,ver:BZ0,uptime_s:Math.round((Date.now()-Z)/1000),pid:process.pid});if(H.pathname==="/v1/readyz"&&G.method==="GET"){if(z===void 0)return A0({ok:!0,db:"sqlite"});try{return await z.raw("SELECT 1"),A0({ok:!0,db:"postgres"})}catch{return A0({ok:!1,error:{code:"db.unavailable"}},503)}}if(H.pathname==="/v1/auth/session"){if(z===void 0)return OW();if(G.method==="POST"){let L=await G.formData().catch(()=>null),B=typeof L?.get("token")==="string"?String(L.get("token")):null;if(!(await HF(z,B)).ok)return new Response(Tw("that token was not accepted"),{status:401,headers:{"content-type":"text/html; charset=utf-8"}});return new Response(null,{status:303,headers:{location:"/v1/admin","set-cookie":pb(B,ib(G))}})}if(G.method==="DELETE"||G.method==="GET")return new Response(null,{status:303,headers:{location:"/v1/admin","set-cookie":cb()}})}if(G.method!=="GET"&&TF(H.pathname)===null)return A0({ok:!1,error:{code:"usage.method",msg:"GET only"}},405);let N;if(z!==void 0){let L=await HF(z,mb(G));if(!L.ok){if((G.headers.get("accept")??"").includes("text/html"))return new Response(Tw(L.code==="denied.no_token"?null:"that token was not accepted"),{status:401,headers:{"content-type":"text/html; charset=utf-8"}});return A0({ok:!1,error:{code:L.code,msg:L.msg}},401)}N=L.principal}if(H.pathname==="/v1/health/db"){if(z!==void 0)try{let B=performance.now();await z.raw("SELECT 1");let T=Math.round((performance.now()-B)*100)/100,[q]=await z.raw(`SELECT max(v) AS v FROM (
|
|
9617
9617
|
SELECT max(version) AS v FROM schema_migrations
|
|
9618
9618
|
UNION ALL SELECT max(version) AS v FROM schema_migrations_compat
|
|
9619
9619
|
) t`),j=q?.v==null?null:Number(q.v),O=j===null?null:`v${j}`,A=j===null||$.schemaKnown===void 0?null:Math.max(0,$.schemaKnown-j);return A0({ok:!0,db:"postgres",latency_ms:T,schema:O,migrations_pending:A})}catch(B){let T=B instanceof Error?B.message:String(B);return A0({ok:!1,error:{code:"db.query",msg:T}},503)}let L;try{L=Y()}catch(B){let T=B instanceof r5?B:new r5("db.open",String(B));return A0({ok:!1,error:{code:T.code,msg:T.message}},503)}try{let B=performance.now();L.one("SELECT 1 AS v");let T=Math.round((performance.now()-B)*100)/100,q=L.has("schema_migrations")?L.one(L.has("schema_migrations_compat")?`SELECT max(v) AS v FROM (SELECT max(version) AS v FROM schema_migrations
|
|
9620
|
-
UNION ALL SELECT max(version) FROM schema_migrations_compat)`:"SELECT max(version) AS v FROM schema_migrations")?.v??null:null;return A0({ok:!0,db:"sqlite",latency_ms:T,schema:q===null?null:`v${q}`,migrations_pending:0})}catch(B){let T=B instanceof Error?B.message:String(B);return A0({ok:!1,error:{code:"db.query",msg:T}},503)}finally{L.close()}}if(H.pathname==="/v1/health/index"){let L;try{L=Y()}catch(B){let T=B instanceof r5?B:new r5("db.open",String(B));return A0({ok:!1,degraded:[T.code],warn:[{code:T.code,msg:T.message}]},503)}try{return A0(
|
|
9620
|
+
UNION ALL SELECT max(version) FROM schema_migrations_compat)`:"SELECT max(version) AS v FROM schema_migrations")?.v??null:null;return A0({ok:!0,db:"sqlite",latency_ms:T,schema:q===null?null:`v${q}`,migrations_pending:0})}catch(B){let T=B instanceof Error?B.message:String(B);return A0({ok:!1,error:{code:"db.query",msg:T}},503)}finally{L.close()}}if(H.pathname==="/v1/health/index"){let L;try{L=Y()}catch(B){let T=B instanceof r5?B:new r5("db.open",String(B));return A0({ok:!1,degraded:[T.code],warn:[{code:T.code,msg:T.message}]},503)}try{return A0(FZ0(L))}catch(B){let T=B instanceof Error?B.message:String(B);return A0({ok:!1,degraded:["db.query"],warn:[{code:"db.query",msg:T}]},503)}finally{L.close()}}if(H.pathname.startsWith("/v1/admin")){if(z===void 0)return OW();if(!VF(N,"admin"))return A0({ok:!1,error:{code:"denied.scope",msg:"this token has no 'admin' scope"}},403);try{if(H.pathname==="/v1/admin/overview"){let L=await LF(z);return A0({ok:!0,...L,degraded:L.warn.map((B)=>B.code)})}if(H.pathname==="/v1/admin/tenants")return A0({ok:!0,tenants:await BF(z)});if(H.pathname==="/v1/admin"||H.pathname==="/v1/admin/"){let[L,B]=await Promise.all([LF(z),BF(z)]);return new Response(db(L,B,N),{headers:{"content-type":"text/html; charset=utf-8"}})}}catch(L){let B=L instanceof Error?L.message:String(L);return A0({ok:!1,error:{code:"db.query",msg:B}},503)}}if(H.pathname==="/v1/ws"){if(z===void 0)return OW();let L=performance.now(),B=await sb(z,N.tenant,{owner:N.subject,team:"",agent:""});return n6("ws","",B,{took_ms:Math.round((performance.now()-L)*100)/100,count:B.length})}let Q=TF(H.pathname);if(Q!==null){if(z===void 0)return OW();let{ws:L,rest:B}=Q,T=N.tenant,q={owner:N?.subject??"",team:"",agent:""},j=$7(q);if(!xb(N,L))return A0({ok:!1,cmd:"ws",ws:L,error:{code:"notfound.ws",msg:`no workspace ${L}`}},404);let O=performance.now(),A=()=>Math.round((performance.now()-O)*100)/100;try{let R=(F)=>VF(N,F)?void 0:A0({ok:!1,cmd:"ws",ws:L,error:{code:"denied.scope",msg:`this token has no '${F}' scope`}},403);if((B==="/sync"||B==="/sync/")&&G.method==="POST"){let F=R("sync");if(F!==void 0)return F;let P=Nw(await G.json().catch(()=>null));if(!P.ok)return A0({ok:!1,cmd:"sync",ws:L,error:P.error},400);let _=await Lw(z,T,L,P.data,N.subject);return n6("sync",L,_,{took_ms:A(),pushed:P.data.ops.length,pulled:_.ops.length})}if((B==="/nodes"||B==="/nodes/")&&G.method==="POST"){let F=R("write");if(F!==void 0)return F;let P=await G.json().catch(()=>null),_=Yw(P);if(!_.ok)return A0({ok:!1,cmd:"node",ws:L,error:_.error},400);let M=await Jw(z,T,L,_.data,N.subject),[E]=await z.withTenant(T,async(b)=>[await b.one(M4.ws_node_get,[L,M.id,...j])]);return n6("node",L,E===void 0?{id:M.id}:FW(E),{took_ms:A(),applied:M.applied,collided:M.collided})}if((B==="/prime"||B==="/prime/")&&G.method==="GET"){let F=H.searchParams,P=await tb(z,T,L,F.get("session")??"",F.get("repo")??"",t9(F.get("n"),qF,FF),q);return n6("prime",L,P,{took_ms:A()})}if((B==="/ready"||B==="/ready/")&&G.method==="GET"){let F=H.searchParams,P=t9(F.get("n"),qF,FF),_=await jF(z,T,L,P,q,F.get("repo")??"");return n6("ready",L,_.items,{took_ms:A(),count:_.items.length,total:_.total})}if(B==="/ready/claim"&&G.method==="POST"){let F=R("claim");if(F!==void 0)return F;let P=await G.json().catch(()=>null),_=typeof P?.id==="string"?P.id:"";if(_==="")return A0({ok:!1,cmd:"claim",ws:L,error:{code:"usage.id",msg:"'id' is required"}},400);let M=P?.lease_minutes,E=M===void 0?Hw:Number(M)*60000,b=await Qw(z,T,L,_,N.subject,E);if(!b.ok){let k=b.error.code==="notfound.node"?404:b.error.code==="usage.lease"?400:409;return A0({ok:!1,cmd:"claim",ws:L,error:b.error},k)}return n6("claim",L,b.data,{took_ms:A()})}if(B==="/edges"&&(G.method==="POST"||G.method==="DELETE")){let F=R("write");if(F!==void 0)return F;let P=await G.json().catch(()=>null),_=Kw(P);if(!_.ok)return A0({ok:!1,cmd:"edge",ws:L,error:_.error},400);let M=G.method==="POST"?await Vw(z,T,L,_.data,N.subject):await Gw(z,T,L,_.data,N.subject);if(!M.ok)return A0({ok:!1,cmd:"edge",ws:L,error:M.error},M.error.code.startsWith("notfound.")?404:409);return n6("edge",L,M.data,{took_ms:A()})}let D=/^\/nodes\/([^/]+)$/.exec(B);if(D!==null&&G.method==="PATCH"){let F=R("write");if(F!==void 0)return F;let P=await G.json().catch(()=>null),_=zw(P);if(!_.ok)return A0({ok:!1,cmd:"node",ws:L,error:_.error},400);let M=decodeURIComponent(D[1]),E=await Uw(z,T,L,M,_.data,N.subject);if(!E.ok)return A0({ok:!1,cmd:"node",ws:L,error:E.error},E.error.code==="notfound.node"?404:400);let[b]=await z.withTenant(T,async(k)=>[await k.one(M4.ws_node_get,[L,M,...j])]);return n6("node",L,b===void 0?{id:M}:FW(b),{took_ms:A(),changed:E.data.changed})}if(G.method!=="GET")return A0({ok:!1,cmd:"ws",ws:L,error:{code:"usage.method",msg:`${G.method} is not supported on ${H.pathname}`}},405);if(B==="/nodes"||B==="/nodes/"){let F=H.searchParams,P=t9(F.get("limit"),ob,ab),_=t9(F.get("offset"),0,Number.MAX_SAFE_INTEGER),M=[L,F.get("kind")??"",F.get("status")??"",t9(F.get("since"),0,Number.MAX_SAFE_INTEGER)],[E,b]=await z.withTenant(T,async(k)=>[await k.all(M4.ws_nodes_list,[...M,P,_,...j]),await k.one(M4.ws_nodes_count,[...M,...j])]);return n6("nodes",L,E,{took_ms:A(),count:E.length,total:Number(b?.n??0),limit:P,offset:_})}if(D!==null){let F=decodeURIComponent(D[1]),[P,_]=await z.withTenant(T,async(M)=>[await M.one(M4.ws_node_get,[L,F,...j]),await M.all(M4.ws_node_edges,[L,F])]);if(P===void 0)return A0({ok:!1,cmd:"node",ws:L,error:{code:"notfound.node",msg:`no node ${F} in workspace ${L}`}},404);return n6("node",L,{...FW(P),edges:_},{took_ms:A()})}}catch(R){return qw(R,"ws",L)}return A0({ok:!1,cmd:"ws",ws:L,error:{code:"notfound.route",msg:`no route ${H.pathname}`}},404)}return A0({ok:!1,error:{code:"notfound.route",msg:`no route ${H.pathname}`}},404)},K=Bun.serve({port:$.port,hostname:$.host??"127.0.0.1",development:!1,fetch:J}),W=K.hostname??"127.0.0.1",V=K.port??$.port;return{url:`http://${W}:${V}`,port:V,host:W,dbPath:X,stop(){z?.close(),K.stop(!0)}}}var BZ0,r5,TZ0=2000,OW=()=>A0({ok:!1,error:{code:"precond.no_pg",msg:"this route needs a Postgres server: start with --pg <url>"}},404);var jw=v(()=>{zF();o();rb();eb();Bw();OF();NF();BZ0=X2;r5=class r5 extends Error{code;constructor($,X){super(X);this.code=$;this.name="HttpDbError"}}});var Cw={};s(Cw,{createServeCommand:()=>AZ0,bootstrapTenant:()=>Ow});function x8($,X,Z,Y){return{ok:!1,code:$,msg:X,exit:Z,hint:Y}}function OZ0(){return new Promise(($)=>{let X=(z)=>()=>{process.off("SIGINT",Z),process.off("SIGTERM",Y),$(z)},Z=X("SIGINT"),Y=X("SIGTERM");process.once("SIGINT",Z),process.once("SIGTERM",Y)})}function d6($,X){let Z=$.flags[X];return typeof Z==="string"&&Z.length>0?Z:void 0}function CZ0($,X){let Z=$.flags[X];if(typeof Z==="number")return Z;if(typeof Z==="string"){let Y=Number(Z);return Number.isFinite(Y)?Y:void 0}return}async function Ow($,X){let Z=(X.MYC_BOOTSTRAP_TENANT??"").trim();if(Z==="")return;let Y=[];if((await $.raw(`INSERT INTO tenants (id, title, created_at) VALUES ($1, '', $2)
|
|
9621
9621
|
ON CONFLICT (id) DO NOTHING RETURNING id`,[Z,Date.now()])).length>0)Y.push(`bootstrap tenant ${Z} registered`);let J=(X.MYC_BOOTSTRAP_TOKEN??"").trim();if(J!==""){let U=await $.raw("SELECT count(*) AS n FROM api_tokens WHERE tenant_id = $1 AND revoked_at IS NULL",[Z]);if(Number(U[0]?.n??0)===0){let K=await QF($,Z,J,{role:"owner"});Y.push(`bootstrap token ${K.id} for ${J} @ ${Z} \xB7 owner`,K.token,"This is the only time the secret is shown, and it is in the container log:","a real install drops MYC_BOOTSTRAP_* and mints tokens by hand.")}}return Y.length===0?void 0:`${Y.join(`
|
|
9622
9622
|
`)}
|
|
9623
|
-
`}function
|
|
9623
|
+
`}function AZ0($={write:(X)=>process.stdout.write(X),wait:OZ0}){return{name:"serve",summary:"run the team server: HTTP API and the admin page over Postgres",flags:[{name:"port",value:"number",description:"port (default 8080)"},{name:"host",value:"string",description:"bind address (default 127.0.0.1; use 0.0.0.0 behind a proxy)"},{name:"pg",value:"string",description:"Postgres URL; without it the server is a local health slice over SQLite"},{name:"add-tenant",value:"string",description:"register a tenant: <id>[:title]; tokens are issued under it"},{name:"add-token",value:"string",description:"mint an access token: <tenant>:<name>; the secret is printed once"},{name:"role",value:"string",description:`role of the new token: ${BW.join("|")} (default member)`},{name:"scopes",value:"string",list:!0,description:`narrow the role's rights: comma-separated ${TW.join(",")} (default: whatever the role means)`},{name:"token-ws",value:"string",description:"bind the new token to one workspace (default: every workspace of the tenant)"},{name:"revoke-token",value:"string",description:"revoke a token by its id"},{name:"tokens",description:"list tokens: who holds them and when each was last used, never the secrets"},{name:"apply-schema",description:"create the schema in an EMPTY database and exit; an existing one is left alone"},{name:"migrate",description:"bring an existing database up to this binary's schema and exit; says what it applied"},{name:"health-probe",description:"ask a server already running on this host whether it is alive, and exit 0 or 1"}],help:"The team server is closed by default: every route except the liveness probe (/v1/health) needs an access token, and the admin page at /v1/admin asks for one in a form and then keeps it in an HttpOnly, SameSite=Strict cookie.\n\nA token is issued per person or agent under one tenant: `--add-token acme:anna` prints the "+"secret once and stores only its sha256 \u2014 a copy of the database gives no access, and "+"nobody can read the secret back. Revoking is one row: `--revoke-token tok_\u2026`.\n\n"+`TLS is the deployment's job, not the server's: put it behind a reverse proxy and let it set X-Forwarded-Proto, so the session cookie is issued with Secure.
|
|
9624
9624
|
|
|
9625
9625
|
`+"Two probes answer two different questions and neither needs a token: /v1/health is liveness \u2014 the "+"process is up, and it deliberately never touches the database, so someone else's outage does not get "+`the container restarted; /v1/readyz is readiness \u2014 the database answers, so work can be accepted.
|
|
9626
9626
|
|
|
9627
|
-
`+"Without --pg there are no tenants and no tokens: the server then serves the health trio over the local SQLite workspace and binds 127.0.0.1, as `myc viz` does.",handler:async(X)=>{let Z=
|
|
9627
|
+
`+"Without --pg there are no tenants and no tokens: the server then serves the health trio over the local SQLite workspace and binds 127.0.0.1, as `myc viz` does.",handler:async(X)=>{let Z=CZ0(X,"port")??Number(process.env.MYC_SERVE_PORT??8080);if(X.flags["health-probe"]===!0){let H=`http://127.0.0.1:${Z}/v1/health`;try{let N=await fetch(H,{signal:AbortSignal.timeout(2000)});if(!N.ok)return x8("degraded.not_alive",`${H} answered ${N.status}`,6);let Q=await N.json();return{ok:!0,data:{alive:Q.ok===!0,uptime_s:Q.uptime_s??null,url:H}}}catch(N){let Q=N instanceof Error?N.message:String(N);return x8("degraded.not_alive",`${H} did not answer: ${Q}`,6)}}let Y=d6(X,"pg")??process.env.MYC_PG_URL,z=d6(X,"add-tenant"),J=d6(X,"add-token"),U=d6(X,"revoke-token"),K=X.flags.tokens===!0,W=X.flags["apply-schema"]===!0,V=X.flags.migrate===!0;if((J!==void 0||z!==void 0||U!==void 0||K||W||V)&&Y===void 0)return x8("precond.no_pg","tokens live in Postgres: pass --pg <url> (or MYC_PG_URL)",5);let G;try{if(Y!==void 0)G=NW(Y);if(W){let[T]=await G.raw("SELECT to_regclass('public.nodes')::text AS t");if(T?.t!==null&&T?.t!==void 0)return{ok:!0,data:{applied:!1,reason:"the database already has a schema"}};await G.raw(`SELECT set_config('myc.by_version', '${E0.replace(/'/g,"''")}', false);
|
|
9628
9628
|
${fb}`);let[q]=await G.raw("SELECT max(version) AS v FROM schema_migrations");return{ok:!0,data:{applied:!0,schema:q?.v==null?null:Number(q.v)}}}if(V){if(await y3(G)===0)return x8("precond.no_schema","this database has no schema at all: there is nothing to migrate",5,"myc serve --pg <url> --apply-schema");if(!await JF(G))return x8("precond.privileges","migrations run as the superuser, like --apply-schema: under the application role a data migration silently changes nothing and still records the version",5,"myc serve --pg postgres://postgres:\u2026@host/myc --migrate");return{ok:!0,data:await Sb(G)}}if(z!==void 0){let T=z.indexOf(":"),q=T<0?z:z.slice(0,T),j=T<0?"":z.slice(T+1);if(q.length===0)return x8("usage.invalid",`--add-tenant expects <id>[:title], got '${z}'`,2);let O=await G.raw(`INSERT INTO tenants (id, title, created_at) VALUES ($1, $2, $3)
|
|
9629
9629
|
ON CONFLICT (id) DO NOTHING RETURNING id`,[q,j,Date.now()]);return{ok:!0,data:{tenant:q,title:j,created:O.length>0}}}if(J!==void 0){let T=J.indexOf(":");if(T<=0||T===J.length-1)return x8("usage.invalid",`--add-token expects <tenant>:<name>, got '${J}'`,2);let q=J.slice(0,T),j=J.slice(T+1);if((await G.raw("SELECT id FROM tenants WHERE id = $1",[q])).length===0)return x8("notfound.tenant",`no tenant '${q}' on this server`,3,`register it first: myc serve --pg <url> --add-tenant ${q}`);let A=d6(X,"role")??"member";if(!KF(A))return x8("usage.invalid",`unknown role '${A}': ${BW.join("|")}`,2);let R=d6(X,"scopes"),D=R===void 0?void 0:WF(R);if(D!==void 0&&D.length===0)return x8("usage.invalid",`--scopes '${R}' has nothing known in it: ${TW.join(",")}`,2);let F=await QF(G,q,j,{role:A,...D===void 0?{}:{scopes:D},...d6(X,"token-ws")===void 0?{}:{ws:d6(X,"token-ws")}});return{ok:!0,data:{id:F.id,tenant:q,subject:j,token:F.token,role:F.role,scopes:F.scopes.join(","),ws:F.ws}}}if(U!==void 0){if(!await ub(G,U))return x8("notfound.token",`no live token with id '${U}'`,3);return{ok:!0,data:{id:U,revoked:!0}}}if(K)return{ok:!0,data:{tokens:await lb(G)}};if(G!==void 0){let T=await y3(G).catch(()=>null),q=UF();if(T!==null&&T>0&&T<q)return x8("precond.schema",`the database is at schema ${T}, this myc knows ${q} \u2014 it would write through a schema it does not have`,5,"myc serve --pg <url> --migrate")}let H=G===void 0?void 0:await Ow(G,$.env??process.env);if(H!==void 0&&!X.globals.json&&!X.globals.ndjson)$.write(H);let N=Date.now(),Q=Fw({port:Z,schemaKnown:UF(),...d6(X,"host")!==void 0?{host:d6(X,"host")}:{},...X.globals.directory!==void 0?{dir:X.globals.directory}:{},...X.globals.db!==void 0?{db:X.globals.db}:{},...Y!==void 0?{pg:Y}:{}});if(!X.globals.json&&!X.globals.ndjson&&!X.globals.quiet)$.write(`myc serve \xB7 ${Y===void 0?"sqlite (local health slice)":"postgres (team server)"}
|
|
9630
9630
|
${Q.url}${Y===void 0?"":` admin: ${Q.url}/v1/admin`}
|
|
@@ -9644,23 +9644,23 @@ This is the only time the secret is shown: the server keeps its sha256, not the
|
|
|
9644
9644
|
`;if(typeof Z.applied==="boolean")return Z.applied===!0?`schema created
|
|
9645
9645
|
`:`schema left alone: ${String(Z.reason)}
|
|
9646
9646
|
`;let Y=X;return`stopped on ${Y.signal} after ${Math.round(Y.uptime_ms/1000)}s
|
|
9647
|
-
`}}}var Aw=v(()=>{zF();yb();gb();NF();jw();v8();V0()});import{closeSync as
|
|
9648
|
-
`),Y=Z===-1?$:$.slice(0,Z);return{rc:/^\d+$/.test(Y)?Number(Y):null,output:Z===-1?"":$.slice(Z+1),at:X}}function Mw($){try{let X=
|
|
9647
|
+
`}}}var Aw=v(()=>{zF();yb();gb();NF();jw();v8();V0()});import{closeSync as PZ0,existsSync as DZ0,mkdirSync as MZ0,openSync as RZ0,readFileSync as _Z0,rmSync as IZ0,statSync as kZ0,writeSync as EZ0}from"fs";import{join as vZ0}from"path";function Dw($,X){let Z=$.indexOf(`
|
|
9648
|
+
`),Y=Z===-1?$:$.slice(0,Z);return{rc:/^\d+$/.test(Y)?Number(Y):null,output:Z===-1?"":$.slice(Z+1),at:X}}function Mw($){try{let X=kZ0($).mtimeMs;return Dw(_Z0($,"utf8"),X)}catch{return null}}async function Rw($){let X=performance.now(),Z=Date.now(),Y=()=>Math.round((performance.now()-X)*10)/10,z=(L)=>({started:!1,finished:!1,current:null,waitedMs:Y(),startedAt:Z,error:L});if(($.platform??process.platform)==="win32")return z("win32");let J;try{MZ0($.tmpDir,{recursive:!0}),J=vZ0($.tmpDir,`pass-${process.pid}-${Date.now()}-${SZ0++}.in`);let L=RZ0(J,"w",384);try{let B=0;while(B<$.payload.length)B+=EZ0(L,$.payload,B)}finally{PZ0(L)}}catch(L){return z(Pw(L))}let U=$.windowMs>0,K;try{K=Bun.spawn([fZ0,"-c",yZ0,"myc-statusline-pass",$.command,J,$.resultFile],{stdin:"ignore",stdout:U?"pipe":"ignore",stderr:"ignore",detached:!0,env:{...$.env,[oK]:"1"}})}catch(L){return IZ0(J,{force:!0}),z(Pw(L))}if(!U)return K.unref(),{started:!0,finished:!1,current:null,waitedMs:Y(),startedAt:Z};let W=K.stdout.getReader(),V=[],G=!1,H,N=new Promise((L)=>{H=setTimeout(()=>L("timeout"),$.windowMs)});try{for(;;){let L=await Promise.race([W.read(),N]);if(L==="timeout")break;if(L.done){G=!0;break}V.push(L.value)}}catch{G=!0}finally{if(H!==void 0)clearTimeout(H);if(!G)W.cancel().catch(()=>{});K.unref()}let Q=Buffer.concat(V).toString("utf8");return{started:!0,finished:G,current:G&&Q.length>0?Dw(Q,0):null,waitedMs:Y(),startedAt:Z}}function Pw($){return $ instanceof Error?$.message:String($)}var CF=0,yZ0=`exec 3<"$2" || exit 1; ( exec 0<&3 3<&-; out=$(/bin/sh -c "$1" 2>/dev/null); rc=$?; printf '%s\\n%s' "$rc" "$out"; exec 1>&-; rm -f "$2"; printf '%s\\n%s' "$rc" "$out" > "$3.$$" && mv -f "$3.$$" "$3" ) &`,fZ0,SZ0=0;var _w=v(()=>{q3();fZ0=DZ0("/bin/dash")?"/bin/dash":"/bin/sh"});import{closeSync as gZ0,existsSync as bZ0,fstatSync as wZ0,openSync as xZ0,readdirSync as hZ0,readSync as Iw}from"fs";import{basename as mZ0,dirname as uZ0,join as kw}from"path";function yw(){return{total:0,useful:0,empty:0,refusal:0,error:0}}function dZ0($){let X=[],Z=[],Y="",z=!1,J=null,U=[],K=$.length,W=()=>{if(z)Z.push(Y);Y="",z=!1},V=()=>{if(W(),Z.length>0)X.push(Z);Z=[]};for(let G=0;G<K;G++){let H=$[G];if(J!==null){if(H===J)J=null;else if(H==="\\"&&J==='"'&&G+1<K)Y+=$[++G];else Y+=H;continue}if(H==="'"||H==='"'){J=H,z=!0;continue}if(H==="\\"&&G+1<K){if($[G+1]!==`
|
|
9649
9649
|
`)Y+=$[G+1];G++,z=z||$[G]!==`
|
|
9650
9650
|
`;continue}if(H===" "||H==="\t"){W();continue}if(H==="#"&&!z){let N=$.indexOf(`
|
|
9651
9651
|
`,G);G=(N===-1?K:N)-1;continue}if(H===`
|
|
9652
|
-
`){if(V(),U.length>0)G=
|
|
9653
|
-
;|&()<>`.includes(J))break;z+=J,Z++}return{word:z,tabs:Y,end:Z}}function
|
|
9654
|
-
`,Y),U=J===-1?$.length:J,K=z.tabs?$.slice(Y,U).replace(/^\t+/,""):$.slice(Y,U);if(Y=J===-1?$.length:J+1,K===z.word)break}return Y}function
|
|
9655
|
-
`);return""}function
|
|
9656
|
-
${typeof K.stderr==="string"?K.stderr:""}`}else z=typeof Y==="string"?Y:gw(X.content);let J=fw(z);if(X.is_error===!0)return J??"error";if(J!==null)return J;let U=
|
|
9652
|
+
`){if(V(),U.length>0)G=aZ0($,G+1,U)-1,U.length=0;continue}if(H==="<"&&$[G+1]==="<"){if($[G+2]==="<"){Y+="<<<",z=!0,G+=2;continue}W();let N=oZ0($,G+2);if(N.word.length>0)U.push({word:N.word,tabs:N.tabs});G=N.end-1;continue}if(H==="$"&&$[G+1]==="("&&$[G+2]==="("){let N=$.indexOf("))",G+3),Q=N===-1?K:N+2;Y+=$.slice(G,Q),z=!0,G=Q-1;continue}if(H==="$"&&$[G+1]==="("){V(),G++;continue}if(";|&(){}`".includes(H)){V();continue}Y+=H,z=!0}return V(),X}function oZ0($,X){let Z=X,Y=!1;if($[Z]==="-")Y=!0,Z++;while($[Z]===" "||$[Z]==="\t")Z++;let z="";while(Z<$.length){let J=$[Z];if(J==="'"||J==='"'){let U=$.indexOf(J,Z+1);if(U===-1){z+=$.slice(Z+1),Z=$.length;break}z+=$.slice(Z+1,U),Z=U+1;continue}if(J==="\\"&&Z+1<$.length){z+=$[Z+1],Z+=2;continue}if(`
|
|
9653
|
+
;|&()<>`.includes(J))break;z+=J,Z++}return{word:z,tabs:Y,end:Z}}function aZ0($,X,Z){let Y=X;for(let z of Z)while(Y<$.length){let J=$.indexOf(`
|
|
9654
|
+
`,Y),U=J===-1?$.length:J,K=z.tabs?$.slice(Y,U).replace(/^\t+/,""):$.slice(Y,U);if(Y=J===-1?$.length:J+1,K===z.word)break}return Y}function eZ0($){let X=$.slice($.lastIndexOf("/")+1);return X==="myc"||X==="myc.exe"}function $20(){if(AF===null){let $=new i3;V9($),AF=new Set($.top.map((X)=>X.name))}return AF}function X20($,X=$20()){for(let Z of dZ0($)){let Y=0;while(Y<Z.length&&(sZ0.test(Z[Y])||rZ0.has(Z[Y])))Y++;let z=Z[Y];if(z===void 0)continue;if(!eZ0(z)){if(z!=="bun"&&!z.endsWith("/bun"))continue;let K=Y+1;if(Z[K]==="run")K++;if(Z[K]===void 0||!/(?:^|\/)cli\/src\/main\.ts$/.test(Z[K]))continue;Y=K}let J=[];for(let K=Y+1;K<Z.length&&J.length<2;K++){let W=Z[K];if(tZ0.has(W)){K++;continue}if(W.startsWith("-")||/^\d*[<>]/.test(W))continue;J.push(W)}let U=J[0]??"";if(U!==""&&!X.has(U))continue;return{cmd:U==="code"&&J[1]!==void 0?`code ${J[1]}`:U}}return null}function Z20($){let X=$.slice(DF.length).replace(/^myc_/,"");return X.startsWith("code_")?`code ${X.slice(5)}`:X}function Ew($){let X=$.split(".",1)[0]??"";return Y20.has(X)?"refusal":"error"}function fw($){let X=$.replace(MF,""),Z=z20.exec(X);if(Z!==null)return Ew(`${Z[1]}.`);let Y=J20.exec(X);if(Y!==null)try{let z=JSON.parse(Y[1]).error?.code;return typeof z==="string"?Ew(z):"error"}catch{return"error"}return null}function K20($){if(Array.isArray($))return $.length;return typeof $==="number"&&Number.isFinite($)?$:void 0}function Sw($,X){if(X===null||typeof X!=="object")return;let Z=X,Y=(z)=>{let J=K20(z);return J===void 0?void 0:J===0};switch($){case"recall":case"search":case"list":return Y(Z.rows??Z.shown);case"code search":case"code grep":return Y(Z.hits);case"code symbol":return Y(Z.defs);case"callers":return Y(Z.edges??Z.total_edges);case"ready":if(Z.claimed!==void 0&&Z.claimed!==null)return!1;return Y(Z.items);case"skeleton":return Y(Z.entries);case"code map":return Y(Z.files);case"prime":return Z.empty===!0;default:return}}function G20($,X){let Z=X.replace(MF,"");if(V20.test(Z))return"empty";let Y=W20[$];if(Y!==void 0){let z=Y.exec(Z);if(z!==null)return Number(z[1])===0?"empty":"useful"}return"useful"}function gw($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((X)=>X!==null&&typeof X==="object"&&typeof X.text==="string"?X.text:"").join(`
|
|
9655
|
+
`);return""}function H20($){let X=$.trimStart();if(!X.startsWith("{"))return;try{return JSON.parse(X)}catch{return}}function Q20($,X,Z){let Y=gw(X.content);if(X.is_error===!0)return fw(Y)??"error";let z=Z.mcpMeta,J=z!==null&&typeof z==="object"&&"structuredContent"in z?z.structuredContent:H20(Y);return Sw($,J)===!0?"empty":"useful"}function N20($,X,Z){let Y=Z.toolUseResult,z;if(Y!==null&&typeof Y==="object"){let K=Y;if(K.interrupted===!0)return"error";z=`${typeof K.stdout==="string"?K.stdout:""}
|
|
9656
|
+
${typeof K.stderr==="string"?K.stderr:""}`}else z=typeof Y==="string"?Y:gw(X.content);let J=fw(z);if(X.is_error===!0)return J??"error";if(J!==null)return J;let U=U20.exec(z.replace(MF,""));if(U!==null)try{let K=JSON.parse(U[1]);return Sw($,K.data)===!0?"empty":"useful"}catch{}return G20($,z)}function L20($){if($===null||typeof $!=="object")return[];let X=$.message;if(X===null||typeof X!=="object")return[];let Z=X.content;return Array.isArray(Z)?Z:[]}function B20($,X){$.total++,$[X]++}function T20($){let X=Object.keys($);for(let Z=0;Z<X.length-lZ0;Z++)delete $[X[Z]]}function q20($,X){let Z=$.indexOf(pZ0)!==-1&&($.indexOf(cZ0)!==-1||$.indexOf(iZ0)!==-1),Y=!1;if($.indexOf(nZ0)!==-1){for(let J of Object.keys(X.pending))if($.indexOf(J)!==-1){Y=!0;break}}if(!Z&&!Y)return;let z;try{z=JSON.parse($.toString("utf8"))}catch{return}for(let J of L20(z))if(J.type==="tool_use"&&typeof J.id==="string"&&typeof J.name==="string"){if(J.name.startsWith(DF))X.pending[J.id]={via:"mcp",cmd:Z20(J.name)};else if(J.name==="Bash"){let U=J.input?.command,K=typeof U==="string"?X20(U):null;if(K!==null)X.pending[J.id]={via:"cli",cmd:K.cmd}}}else if(J.type==="tool_result"&&typeof J.tool_use_id==="string"){let U=X.pending[J.tool_use_id];if(U===void 0)continue;delete X.pending[J.tool_use_id];let K=z;B20(X.counts,U.via==="mcp"?Q20(U.cmd,J,K):N20(U.cmd,J,K))}T20(X.pending)}function F20($){return{offset:0,ino:$,pending:{},counts:yw()}}function j20($,X,Z){let Y;try{Y=xZ0($,"r")}catch{return{cur:X,read:0,behind:0}}try{let z=wZ0(Y),J=Number(z.ino),U=X!==void 0&&X.ino===J&&X.offset<=z.size?X:F20(J),K=z.size-U.offset;if(K<=0||Z<=0)return{cur:U,read:0,behind:Math.max(0,K)};let W=Math.min(K,Z),V=Buffer.allocUnsafe(W),G=Iw(Y,V,0,W,U.offset),H=V.subarray(0,G).lastIndexOf(10);while(H===-1&&W<K)W=Math.min(K,W*2),V=Buffer.allocUnsafe(W),G=Iw(Y,V,0,W,U.offset),H=V.subarray(0,G).lastIndexOf(10);if(H===-1)return{cur:U,read:0,behind:K};let N=0;while(N<=H){let Q=V.indexOf(10,N),L=Q===-1||Q>H?H:Q;if(L>N)q20(V.subarray(N,L),U);N=L+1}return U.offset+=H+1,{cur:U,read:H+1,behind:K-(H+1)}}finally{gZ0(Y)}}function O20($){let X=kw(uZ0($),mZ0($,".jsonl"),"subagents");try{return hZ0(X).filter((Z)=>Z.endsWith(".jsonl")).sort().map((Z)=>kw(X,Z))}catch{return[]}}function C20($,X,Z){return $!==null&&$.v===1&&$.transcript===X&&($.classifier??1)===vw&&($.build??"")===Z}function bw($,X,Z=PF,Y=""){let z=performance.now(),J={v:1,classifier:vw,build:Y,transcript:X,files:{}},U=C20($,X,Y)?{...J,files:{...$.files}}:J,K=!bZ0(X),W=Z,V=0,G=0;for(let Q of K?[]:[X,...O20(X)]){let L=j20(Q,U.files[Q],W);if(L.cur!==void 0)U.files[Q]=L.cur;V+=L.read,G+=L.behind,W-=L.read}let H=yw(),N=0;for(let Q of Object.values(U.files))H.total+=Q.counts.total,H.useful+=Q.counts.useful,H.empty+=Q.counts.empty,H.refusal+=Q.counts.refusal,H.error+=Q.counts.error,N+=Object.keys(Q.pending).length;return{state:U,report:{counts:H,pending:N,readBytes:V,behindBytes:G,files:Object.keys(U.files).length,missing:K,tookMs:Math.round((performance.now()-z)*10)/10}}}var vw=3,PF=8388608,lZ0=64,DF="mcp__myc__",pZ0,cZ0,iZ0,nZ0,sZ0,rZ0,tZ0,AF=null,Y20,MF,z20,J20,U20,W20,V20;var ww=v(()=>{$X();pZ0=Buffer.from('"tool_use"'),cZ0=Buffer.from(DF),iZ0=Buffer.from("myc"),nZ0=Buffer.from('"tool_result"');sZ0=/^[A-Za-z_][A-Za-z0-9_]*=/,rZ0=new Set(["time","command","exec","nohup","env","caffeinate","do","then","else","elif","if","while","until","!"]),tZ0=new Set(["-C","--directory","--db"]);Y20=new Set(["usage","notfound","precond","conflict","ws","denied"]),MF=/\x1b\[[0-9;]*m/g,z20=/(?:^|\n)myc: ([a-z]+)\.[a-z0-9_.]+: /,J20=/(?:^|\n)(\{"ok":false,.*)/,U20=/(?:^|\n)(\{"ok":true,.*)/;W20={recall:/^(\d+) (?:\u0438\u0437|of) \d+/m,search:/^(\d+) (?:\u0438\u0437|of) \d+/m,list:/^(\d+) (?:\u0438\u0437|of) \d+/m,ready:/^(\d+) ready\b/m,"code search":/^(\d+) (?:\u0444\u0430\u0439\u043B|file)/m,"code grep":/\u2014 (\d+) (?:\u0432\u0445\u043E\u0436\u0434\u0435\u043D|occurrence)/,callers:/(?:\u0433\u0440\u0443\u043F\u043F|groups) (\d+)/},V20=/(?:^|\n)WARN [a-z_]+\.empty: /});var tw={};s(tw,{statuslineCachePath:()=>s20,renderLine:()=>dw,readRunQueue:()=>aw,queueDbOf:()=>ow,defaultCacheDir:()=>nw,createStatuslineCommand:()=>n20,computeStatusline:()=>rw,STATS_TTL_MS:()=>pw,CODE_TTL_MS:()=>cw,CACHE_FORMAT:()=>RF});import{createHash as mw}from"crypto";import{existsSync as _F,mkdirSync as A20,readdirSync as P20,readFileSync as uw,renameSync as D20,rmSync as M20,statSync as R20,writeFileSync as _20}from"fs";import{hostname as I20,tmpdir as k20}from"os";import{join as g3,resolve as lw}from"path";import{isatty as E20}from"tty";function iw($,X){return g3($,`${mw("sha256").update(X).digest("hex").slice(0,20)}.json`)}function f20($,X,Z){let Y=mw("sha256").update(`f${y20}
|
|
9657
9657
|
${X}
|
|
9658
|
-
${Z}`).digest("hex").slice(0,20);return g3($,`${Y}.foreign`)}function
|
|
9658
|
+
${Z}`).digest("hex").slice(0,20);return g3($,`${Y}.foreign`)}function S20($,X){let Z={v:RF,build:X};try{let Y=JSON.parse(uw($,"utf8"));return Y!==null&&typeof Y==="object"&&Y.v===RF&&Y.build===X?Y:Z}catch{return Z}}function xw($,X,Z,Y){try{A20($,{recursive:!0});let z=!_F(X),J=`${X}.${process.pid}.tmp`;if(_20(J,JSON.stringify(Z)),D20(J,X),z)g20($,Y)}catch{}}function g20($,X){for(let Z of P20($)){let Y=g3($,Z);try{if(X-R20(Y).mtimeMs>v20)M20(Y,{force:!0})}catch{}}}function nw($=process.env){let X=$.MYC_STATUSLINE_CACHE;if(X!==void 0&&X.length>0)return X;let Z=typeof process.getuid==="function"?process.getuid():"u";return g3(k20(),`myc-statusline-${Z}`)}async function b20($,X,Z){let{collectTop:Y,readyQueries:z}=await Promise.resolve().then(() => (HK(),pB)),J=(U)=>$.driver.one(U,[$.scope,X])?.n??0;return{ready:Y($,1,Z,X).total,in_progress:J(z.ready_stats_in_progress),blocked:J(z.ready_stats_blocked),blocked_by_ancestor:J(z.ready_stats_blocked_anc)}}function dw($){let X=[];if($.context_pct!==null)X.push(`ctx ${$.context_pct}%`);if($.workspace===null)X.push($.workspace_error??"no myc workspace \u2014 run myc init");else{let Y=$.queue;if(Y!==null){let z=Y.in_progress>0?` \xB7 ${Y.in_progress} in progress`:"",J=Y.blocked_by_ancestor>0?` (+${Y.blocked_by_ancestor} via parent)`:"";X.push(`${Y.ready} ready${z} \xB7 ${Y.blocked} blocked${J}`)}else X.push("tasks: ?");X.push(h20($.code)),X.push($.memory!==null?CW($.memory,"note"):"notes: ?")}if(X.push(m20($.session)),$.run_queue!==null)X.push(w20($.run_queue));return`myc${$.degraded.length>0?` \u26A0 ${$.degraded.join(", ")}`:""} \u2502 ${X.join(" \u2502 ")}`}function w20($){let X=[];if($.running>0)X.push(`${$.running} running`);if($.waiting>0)X.push(`${$.waiting} waiting${$.mine_waiting!==null?` (mine ${$.mine_waiting})`:""}`);return`run queue ${X.join(" \xB7 ")}`}function ow($){let X=$.MYC_HOME??$.HOME;if(X===void 0||X.length===0)return null;return g3(X,".myc","queue.db")}async function aw($,X,Z){if($===null||!_F($))return null;let{Database:Y}=await import("bun:sqlite");try{(await Promise.resolve().then(() => (VZ(),Kj))).selectSqliteLibrary()}catch{}let z=new Y($,{readwrite:!0});try{z.exec("PRAGMA busy_timeout = 20");let J=z.query(x20).all();if(J.length===0)return null;let{liveness:U}=await Promise.resolve().then(() => (iK(),Bg)),K=I20(),W=0,V=0,G=null;for(let N of J){if(U(N,Z,K)==="dead")continue;if(N.state==="running"){W++;continue}if(V++,X.length>0&&N.session===X)G=Math.max(G??0,Z-N.enqueued_at)}if(W+V===0)return null;let{fmtAge:H}=await Promise.resolve().then(() => (j0(),m2));return{running:W,waiting:V,mine_waiting_ms:G,mine_waiting:G===null?null:H(G)}}finally{z.close()}}function CW($,X){return`${$} ${X}${$===1?"":"s"}`}function h20($){if($===null)return"code: ?";if($.state==="none")return"no code index";let X=`${CW($.files,"file")} \xB7 ${CW($.symbols,"symbol")}`;if($.state==="indexing")return`${X} \xB7 indexing`;if($.state==="queued")return`${X} \xB7 ${CW($.queued,"file")} queued`;let Z=$.refresh==="running"?" \xB7 refreshing":$.refresh==="queued"?" \xB7 refresh queued":$.refresh==="retry"?" \xB7 refresh retrying":$.refresh==="failed"?" \xB7 refresh failed":$.stale?" \xB7 stale":"";return`${X} \xB7 ${$.age} ago${Z}`}function m20($){if($===null)return"no session";let X=$.behind_bytes>0?" (counting)":"";return`${$.counts.useful}/${$.counts.total} useful calls${X}`}function u20($){if($.length===0)return{};try{let X=JSON.parse(Buffer.from($).toString("utf8"));if(X===null||typeof X!=="object")return{};let Z=(U)=>typeof U==="string"&&U.length>0?U:void 0,Y=(U)=>U!==null&&typeof U==="object"?U:void 0,z=Y(X.workspace),J=Y(X.context_window)?.used_percentage;return{session_id:Z(X.session_id),transcript_path:Z(X.transcript_path),cwd:Z(X.cwd),current_dir:z!==void 0?Z(z.current_dir):void 0,context_pct:typeof J==="number"&&Number.isFinite(J)?Math.min(100,Math.max(0,Math.round(J))):void 0}}catch{return{}}}function l20(){if(E20(0))return null;try{return uw(0)}catch{return new Uint8Array(0)}}function i20($,X){if($.flags["no-pass"]===!0)return{command:null,source:null,skipped:"disabled"};let Z=$.flags.then,Y=typeof Z==="string"?Z:void 0,z=(U,K)=>{if(U===null)return{command:null,source:null,skipped:"none"};if(C4(U))return{command:null,source:K,skipped:"ours"};return{command:U,source:K}};if(Y!==void 0&&Y.trim().length>0)return z(Y,"project");let J=Z8(T3(c9(X)).value);if(J!==null&&C4(J)){let U=$W(X);if(U!==void 0)return z(Z8(U.previous),"user-previous")}return z(J,"user")}function sw($){let X=$.flags.scope;if(X===void 0)return"project";return X==="project"||X==="user"?X:null}function n20($={}){let X={...p20(),...$};return{name:"statusline",summary:"one-line status for Claude Code's statusLine: context fill, queue, code index, memory, useful myc calls",flags:c20,help:`Reads the host's statusLine JSON on stdin and prints one line: the context window fill the host reports (ctx N%, from context_window.used_percentage; no segment when the host gives none), tasks ready / in progress / blocked, code index files, symbols and age, memory nodes in this repo's reach, and how many of THIS session's calls to the tool were useful out of how many (counted from the host's transcript, incrementally); when the machine-wide \`myc run\` queue is not empty, how many commands run and wait there and how long THIS session has waited. The same stdin bytes go to the statusLine that was there before (${Dq}, the user one, or \u2014 when the user line is myc's own \u2014 the one it replaced, recorded in `+"~/.myc/wire-user.json), detached: never waited for (unless --wait-ms) and never killed; the output of its last completed run is printed above ours. --scope user is the line of Claude Code's user layer: in a myc workspace (a git worktree included) it is the full line, outside one it prints nothing of its own. Always exits 0. Installed by `myc wire --status-line` (or `myc wire --scope user --status-line`).",handler:async(Z)=>{if(sw(Z)===null)return{ok:!1,code:"usage.invalid",msg:"--scope takes project or user",exit:2};let Y=await rw(Z,X);if(X.selfExit){let z=Z.globals.json?s7(fX("statusline",Y,void 0,Z.diagnostics)):hw(Y);await d20(z)}return{ok:!0,data:Y}},renderHuman:(Z)=>hw(Z)}}function hw($){return $.lines.length>0?`${$.lines.join(`
|
|
9659
9659
|
`)}
|
|
9660
|
-
`:""}async function
|
|
9660
|
+
`:""}async function d20($){let X=W9();process.exitCode=0,process.stdout.write($),await X.stdout(),process.exit(0)}function o20($){try{return"dbPath"in K$($)}catch{return!1}}async function rw($,X){let Z=performance.now(),Y=X.now(),z=$.flags["wait-ms"],J=Math.max(0,typeof z==="number"?z:CF),U=sw($)??"project";if((X.env[oK]??"").length>0)return{scope:U,silent:"nested",line:"",lines:[],context_pct:null,workspace:null,repo:"",queue:null,code:null,memory:null,degraded:[],session:null,run_queue:null,foreign:{source:null,started:!1,finished:!1,from:null,rc:null,shown:!1,waited_ms:0,window_ms:J,skipped:"nested"},cache:{stats:"none",code:"none"},took_ms:Math.round((performance.now()-Z)*10)/10};let K=X.readStdin(),W=K??new Uint8Array(0),V=u20(W),G=lw($.globals.directory??V.current_dir??V.cwd??process.cwd()),H=V.transcript_path??(V.session_id!==void 0?`session:${V.session_id}`:`dir:${G}`),N=K===null?{command:null,source:null,skipped:"tty"}:i20($,X.env),Q=N.command!==null?f20(X.cacheDir,H,N.command):null,L=N.command!==null&&Q!==null?Rw({command:N.command,payload:W,windowMs:J,env:X.env,tmpDir:X.cacheDir,resultFile:Q,platform:X.platform}):null,B=U==="user"&&$.globals.db===void 0&&!o20(G)?"no-workspace":void 0,T,q;try{T=B!==void 0?{workspace:null,repo:"",queue:null,code:null,memory:null,degraded:[],session:null,cache:{stats:"none",code:"none"}}:await a20($,X,V,G,H,Y)}catch(M){q=M instanceof Error?M.message:String(M),T={workspace:null,workspace_error:`status line failed: ${q}`,repo:"",queue:null,code:null,memory:null,degraded:[],session:null,cache:{stats:"none",code:"none"}}}let j=null;if(B===void 0)try{let M=X.queueDb!==void 0?X.queueDb:ow(X.env);j=await aw(M,V.session_id??"",Y)}catch(M){let E=M instanceof Error?M.message.split(`
|
|
9661
9661
|
`)[0].slice(0,40):String(M);T={...T,degraded:[...T.degraded,`run queue unreadable: ${E}`]}}let O=L!==null?await L:null,A=O?.current??(Q!==null?Mw(Q):null),R=null;if(O?.current)R="current";else if(A!==null)R=O!==null&&A.at>=O.startedAt?"current":"previous";let D={source:N.source,started:O?.started??!1,finished:O?.finished??!1,from:R,rc:A?.rc??null,shown:A!==null&&A.rc===0&&A.output.trim().length>0,waited_ms:O?.waitedMs??0,window_ms:J,...N.skipped!==void 0?{skipped:N.skipped}:O?.error!==void 0?{skipped:O.error}:{}},F=V.context_pct??null,P=B!==void 0?"":dw({...T,context_pct:F,run_queue:j,foreign:D}),_=[...D.shown&&A!==null?A.output.split(`
|
|
9662
|
-
`).map((M)=>M.trimEnd()).filter((M)=>M.trim().length>0):[],...P.length>0?[P]:[]];return{scope:U,...B!==void 0?{silent:B}:{},context_pct:F,...T,run_queue:j,foreign:D,line:P,lines:_,took_ms:Math.round((performance.now()-Z)*10)/10,...q!==void 0?{error:q}:{}}}async function
|
|
9663
|
-
`)[0].slice(0,60)}`,repo:"",queue:null,code:null,memory:null,degraded:V,session:W,cache:{stats:"none",code:"none"}};let H=G.handle;try{let{fmtAge:N,repoTarget:Q}=await Promise.resolve().then(() => (j0(),m2)),L=Q(H),B=Z.session_id??"",T=lw(H.mycDir),q=`${T}|${H.scope}|${L}|${B}`,j="miss",O,A=H.driver.one(S3.sl_seq,[])?.s??0,R=K.stats;if(R!==void 0&&R.key===q&&R.seq===A&&J-R.at<pw&&J>=R.at)O=R,j="hit";else{let w=H.driver.one(S3.sl_anchors_bad,[H.scope,L]);O={key:q,seq:A,at:J,queue:await
|
|
9662
|
+
`).map((M)=>M.trimEnd()).filter((M)=>M.trim().length>0):[],...P.length>0?[P]:[]];return{scope:U,...B!==void 0?{silent:B}:{},context_pct:F,...T,run_queue:j,foreign:D,line:P,lines:_,took_ms:Math.round((performance.now()-Z)*10)/10,...q!==void 0?{error:q}:{}}}async function a20($,X,Z,Y,z,J){let U=iw(X.cacheDir,z),K=S20(U,X.build),W=null;if(Z.transcript_path!==void 0){let N=bw(K.session??null,Z.transcript_path,X.scanBytes,X.build);K.session=N.state;let Q=N.report;W={transcript:Z.transcript_path,counts:Q.counts,pending:Q.pending,read_bytes:Q.readBytes,behind_bytes:Q.behindBytes,files:Q.files,took_ms:Q.tookMs}}let V=[];if(!_F(gX(Z$,X.env)))V.push("no embedding model");let G;try{G=await X.openStore({...$,globals:{...$.globals,directory:Y}})}catch(N){G={ok:!1,failure:{ok:!1,code:"io.open",msg:N instanceof Error?N.message:String(N),exit:1}}}if(!G.ok)return xw(X.cacheDir,U,K,J),{workspace:null,workspace_error:G.failure.code.startsWith("ws.")?"no myc workspace \u2014 run myc init":`database unavailable: ${G.failure.msg.split(`
|
|
9663
|
+
`)[0].slice(0,60)}`,repo:"",queue:null,code:null,memory:null,degraded:V,session:W,cache:{stats:"none",code:"none"}};let H=G.handle;try{let{fmtAge:N,repoTarget:Q}=await Promise.resolve().then(() => (j0(),m2)),L=Q(H),B=Z.session_id??"",T=lw(H.mycDir),q=`${T}|${H.scope}|${L}|${B}`,j="miss",O,A=H.driver.one(S3.sl_seq,[])?.s??0,R=K.stats;if(R!==void 0&&R.key===q&&R.seq===A&&J-R.at<pw&&J>=R.at)O=R,j="hit";else{let w=H.driver.one(S3.sl_anchors_bad,[H.scope,L]);O={key:q,seq:A,at:J,queue:await b20(H,L,J),memory:H.driver.one(S3.sl_memory,[H.scope,L,B])?.n??0,anchors_stale:w?.stale??0,anchors_lost:w?.lost??0,jobs_dead:H.driver.one(S3.sl_jobs_dead,[])?.n??0},K.stats=O}let D=H.driver.one(S3.sl_code_jobs,[J])??{queued:0,leased:0},F=`${T}|${L}`,P="miss",_,M=K.code;if(M!==void 0&&M.key===F&&D.queued===0&&J-M.at<cw&&J>=M.at)_=M,P="hit";else{let{indexScope:w}=await Promise.resolve().then(() => (v6(),E6)),{coveringIndex:h}=await Promise.resolve().then(() => LM),u=w(H.driver.database,h(H.driver.database,L)??L);_={key:F,at:J,files:u.files,symbols:u.defs,l1_files:u.l1Files,indexed_at:u.indexedAt},K.code=_}let{indexFreshness:E,refreshAfterMs:b}=await Promise.resolve().then(() => pJ),k=_.files>0?E(H.driver.database,J,b(X.env)):null,y=k!==null&&k.refreshedAt>0?k.refreshedAt:_.indexed_at,g={state:D.leased>0?"indexing":D.queued>0?"queued":_.files===0?"none":"ok",files:_.files,symbols:_.symbols,indexed_at:_.indexed_at,refreshed_at:y,age:N(J-y),stale:k?.stale??!1,refresh:k?.job?.state??null,queued:D.queued};if(_.l1_files>0&&_.symbols===0&&D.leased===0)V.push("no grammars");let S=[];if(O.anchors_lost>0)S.push(`${O.anchors_lost} lost`);if(O.anchors_stale>0)S.push(`${O.anchors_stale} stale`);if(S.length>0){let w=O.anchors_lost+O.anchors_stale;V.push(`${S.join(", ")} anchor${w===1?"":"s"}`)}if(O.jobs_dead>0)V.push(`${O.jobs_dead} failed job${O.jobs_dead===1?"":"s"}`);return xw(X.cacheDir,U,K,J),{workspace:H.wsDir,repo:L,queue:O.queue,code:g,memory:O.memory,degraded:V,session:W,cache:{stats:j,code:P}}}finally{H.close()}}function s20($,X){return iw($,X)}var pw=30000,cw=60000,v20=604800000,RF=3,y20=1,S3,x20="SELECT state, session, pid, host, lease_expires, enqueued_at FROM run_queue",p20=()=>({openStore:async($,X)=>(await Promise.resolve().then(() => (j0(),m2))).openStore($,X),now:Date.now,env:process.env,readStdin:l20,cacheDir:nw(),selfExit:!0,platform:process.platform,scanBytes:PF,build:E0}),c20;var ew=v(()=>{o();Y4();K8();V0();v8();q3();_w();ww();R8();S3=Z0({sl_seq:{name:"sl_seq",sql:"SELECT coalesce(max(seq), 0) AS s FROM oplog",params:[]},sl_memory:{name:"sl_memory",sql:`SELECT count(*) AS n FROM nodes
|
|
9664
9664
|
WHERE scope = ?1 AND kind IN ('note','task') AND deleted_at IS NULL
|
|
9665
9665
|
AND ${k0("nodes")}
|
|
9666
9666
|
AND CASE kind WHEN 'note' THEN coalesce(json_extract(attrs,'$.type'),'') <> 'comment'
|
|
@@ -9670,8 +9670,8 @@ ${Z}`).digest("hex").slice(0,20);return g3($,`${Y}.foreign`)}function k20($,X){l
|
|
|
9670
9670
|
AND ${Y7("nodes")}`,params:["scope","repo","session"]},sl_anchors_bad:{name:"sl_anchors_bad",sql:`SELECT sum(status = 'stale') AS stale, sum(status = 'lost') AS lost FROM nodes
|
|
9671
9671
|
WHERE scope = ?1 AND kind = 'anchor' AND status IN ('stale','lost') AND deleted_at IS NULL
|
|
9672
9672
|
AND ${r$("nodes",2)}`,params:["scope","repo"]},sl_jobs_dead:{name:"sl_jobs_dead",sql:"SELECT count(*) AS n FROM jobs WHERE attempts >= max_attempts",params:[]},sl_code_jobs:{name:"sl_code_jobs",sql:`SELECT count(*) AS queued, coalesce(sum(lease_expires > ?1), 0) AS leased
|
|
9673
|
-
FROM jobs WHERE kind = 'code_index' AND attempts < max_attempts`,params:["now"]}});h20=[{name:"scope",value:"string",description:"project (default) or user \u2014 the line of Claude Code's user layer (myc wire --scope user --status-line): "+"outside a myc workspace it prints nothing of its own, and still hands the input on"},{name:"then",value:"string",description:"the project statusLine command we replaced: gets the same stdin"},{name:"wait-ms",value:"number",description:`wait up to N ms for THIS render's foreign output (default ${CF}: never wait, show its last completed run)`},{name:"no-pass",description:"do not hand the input to any foreign statusLine"}]});function AW($){if($!=="agent")throw Error(`profile '${$}' is not implemented yet (myc-zdk); available: agent`);return x3}var R4,b3,IF,w3,x3;var kF=v(()=>{R4={type:"string",description:"workspace; M0: single, ignored"},b3=[{name:"myc_prime",description:"Project start packet: ready queue, work in progress, core and recent decisions. "+"Call at session start and again right after context compaction \u2014 "+"replaces reading the README, plans and task history.",inputSchema:{type:"object",properties:{budget:{type:"integer",default:2000,minimum:200,maximum:8000,description:"answer budget in chars"},ws:R4},additionalProperties:!1}},{name:"myc_ready",description:"Tasks with no open blockers \u2014 what you can take right now. "+"With claim=true it atomically takes the top one (or the one in id) and returns "+"its description, deps and anchors at once \u2014 then just work, no extra calls.",inputSchema:{type:"object",properties:{n:{type:"integer",default:5,minimum:1,maximum:50},claim:{type:"boolean",default:!1,description:"atomically take a task and return its context"},id:{type:"string",description:"take a specific task (only with claim=true)"},kind:{type:"array",items:{type:"string",enum:["task","bug","epic","chore"]},maxItems:1},priority:{type:"array",items:{type:"string",enum:["P0","P1","P2","P3"]},maxItems:1},tag:{type:"array",items:{type:"string"},maxItems:1},lease_minutes:{type:"integer",default:30,minimum:5,maximum:480,description:"how long the task stays yours before the lease expires"},why:{type:"boolean",default:!1,description:"explain the sort order"},review:{type:"boolean",default:!1,description:"compaction candidates awaiting myc_update confirm/reject, not tasks"},ws:R4},additionalProperties:!1}},{name:"myc_update",description:"Every task state change in one tool: claim, release, close, reopen, assign, priority, note, extend; confirm/reject a compaction candidate. "+"close, reopen and reject require a reason \u2014 "+"it goes into project memory and later sessions see it.",inputSchema:{type:"object",required:["id","op"],properties:{id:{type:"string"},op:{type:"string",enum:["claim","release","close","reopen","assign","priority","note","extend","confirm","reject"],description:"cancel is left out on purpose: cancelling is a human judgment, say in your report that the work is not needed"},reason:{type:"string",description:"required for close, reopen, reject"},outcome:{type:"string",enum:["done","wontfix","duplicate","superseded"],default:"done",description:"how the task ended; for op=close"},duplicate_of:{type:"string",description:"canonical node for outcome=duplicate"},assignee:{type:"string"},priority:{type:"string",enum:["P0","P1","P2","P3"]},note:{type:"string",description:"note text for op=note"},lease_minutes:{type:"integer",minimum:5,maximum:480},steal:{type:"boolean",default:!1,description:"take over an expired lease"},verify:{type:"string",enum:["tests","review","human","none"],default:"none",description:"what proves the work: recorded with the close"},cost:{type:"object",description:"filled in by the host: tokens_in, tokens_out, model, retries",properties:{tokens_in:{type:"integer"},tokens_out:{type:"integer"},model:{type:"string"},retries:{type:"integer"}},additionalProperties:!1},ws:R4},additionalProperties:!1}},{name:"myc_create",description:"Create a node: task, bug, epic, memory, decision \u2014 same as CLI `myc create`. "+"For work items and structured nodes; to record a conclusion or fact prefer myc_remember, to change an existing node use myc_update.",inputSchema:{type:"object",required:["title"],properties:{title:{type:"string",minLength:1},kind:{type:"string",enum:["task","bug","epic","memory","decision","document","skill","message"],default:"task"},priority:{type:"string",enum:["P0","P1","P2","P3"],description:"tasks only"},parent:{type:"string",description:"parent node id \u2014 a child edge is added"},dep:{type:"array",items:{type:"string"},description:"ids that block the new node"},assign:{type:"string"},body:{type:"string"},tag:{type:"array",items:{type:"string"}},ws:R4},additionalProperties:!1}},{name:"myc_recall",needsVector:!0,description:"Search project memory in your own words: facts, decisions, tasks, episodes. "+"The answer is ranked and cut to the budget \u2014 read from the top and stop. "+"WARN/degraded in the answer = part of the index is down, quality is lower than usual.",inputSchema:{type:"object",required:["query"],properties:{query:{type:"string",minLength:2},n:{type:"integer",default:6,minimum:1,maximum:50,description:"how many nodes at most"},budget:{type:"integer",default:2000,minimum:200,maximum:8000,description:"answer budget in chars"},kind:{type:"array",items:{type:"string"},description:"task,bug,epic,memory,decision,document,skill,message"},layer:{type:"array",items:{type:"string",enum:["L0","L1","L2","L3"]},description:"default L1-L3"},tag:{type:"array",items:{type:"string"}},since:{type:"string",description:"e.g. 7d, 3w, 12h"},anchor:{type:"string",description:"file path \u2014 narrow to nodes anchored there"},mode:{type:"string",enum:["hybrid","vec","bm25"],default:"hybrid",description:"hybrid is default; vec \u2014 meaning only, bm25 \u2014 words only"},ws:R4},additionalProperties:!1}},{name:"myc_remember",description:"Record a conclusion, decision or fact so later sessions know it. One claim at a time, concrete, with its reason. No raw code or secrets. A contradiction gets flagged, it does not overwrite the old one.",inputSchema:{type:"object",required:["text"],properties:{text:{type:"string",minLength:8,maxLength:8000},tag:{type:"array",items:{type:"string"},maxItems:8},anchor:{type:"array",items:{type:"string"},maxItems:1,description:"path or path:start-end"},layer:{type:"string",enum:["L1","L2","L3"],default:"L1",description:"L1 fact, L2 decision, L3 constant (only with human consent)"},source:{type:"string",description:"url, file path, task id"},absorb:{type:"boolean",default:!0,description:"false \u2014 write as is, without checking against what is known"},ws:R4},additionalProperties:!1}},{name:"myc_show",description:"Full content of one or more nodes at once: body, deps, links, code anchors. Pass the list of ids in one call, not one by one.",inputSchema:{type:"object",required:["ids"],properties:{ids:{type:"array",items:{type:"string"},minItems:1,maxItems:20},depth:{type:"integer",enum:[0,1],default:0,description:"1 \u2014 titles of neighbours along edges"},source:{type:"boolean",default:!1,description:"pull in the code at the anchors (not lost ones)"},fields:{type:"array",items:{type:"string"},description:"limit fields \u2014 saves tokens"},ws:R4},additionalProperties:!1}},{name:"myc_link",description:"Create or remove a link between nodes: blocks/blocked-by (dependency), relates-to, duplicates, supersedes, contradicts, replies-to, derived-from, "+"part-of. supersedes and duplicates require a reason \u2014 history is not rewritten.",inputSchema:{type:"object",required:["from","type","to"],properties:{from:{type:"string"},to:{type:"string"},type:{type:"string",enum:["blocks","blocked-by","relates-to","duplicates","supersedes","contradicts","replies-to","derived-from","part-of"]},reason:{type:"string",description:"required for supersedes and duplicates"},remove:{type:"boolean",default:!1},ws:R4},additionalProperties:!1}}],IF=["call","new","type","import","read","prop"],w3=[{name:"myc_code_search",description:"Find code by a question in your own words when you don't know the name: files by rank "+"and the symbols matched in them with path:line \u2014 read from the top. Search is lexical: "+"the closer your words are to the code, the better. Know the name \u2014 myc_code_symbol; "+"need ALL occurrences \u2014 myc_code_grep.",inputSchema:{type:"object",required:["query"],properties:{query:{type:"string",minLength:1},limit:{type:"integer",default:10,minimum:1,description:"files"}},additionalProperties:!1}},{name:"myc_code_grep",description:"Every occurrence of a string in the repo's files, with its owner (function, class) \u2014 "+"exhaustive, unlike search. For editing a constant, SQL, a key, an error text. Reads the disk, so it never lags behind the code; the occurrence count is full even when groups are cut.",inputSchema:{type:"object",required:["literal"],properties:{literal:{type:"string",minLength:1},ignore_case:{type:"boolean",default:!1},lang:{type:"array",items:{type:"string"},description:"ts, py, md\u2026"},in:{type:"array",items:{type:"string"},description:"dirs/files from the repo root"},limit:{type:"integer",default:60,minimum:1,description:"groups"}},additionalProperties:!1}},{name:"myc_code_symbol",description:"Where a symbol with this exact name is defined: path:span, kind, export, mention "+"count \u2014 and which tasks and memory facts are anchored to that span. "+"The cheapest answer when you know the name.",inputSchema:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1}},additionalProperties:!1}},{name:"myc_callers",description:"Who calls a symbol (in) or what it calls (out): one edge per caller, "+'with the code lines inside. depth N or "all" \u2014 the blast radius of an edit, '+"before renaming or changing a signature. The graph is by name: WARN callers.ambiguous \u2014 "+"same-name symbols are merged.",inputSchema:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1},direction:{type:"string",enum:["in","out"],default:"in",description:"in \u2014 who calls this symbol; out \u2014 what it calls"},depth:{default:1,description:'1, N or "all"'},kind:{type:"array",items:{type:"string",enum:[...IF,"all"]},description:"default: all for in, call+new for out"},limit:{type:"integer",default:40,minimum:1,description:"groups"}},additionalProperties:!1}},{name:"myc_skeleton",description:"A file's API instead of reading it whole: declarations with signatures and spans, nesting by indent, and how many times cheaper this is than the file. Then read "+"the span you need, not the file. WARN skeleton.stale \u2014 the file changed after indexing.",inputSchema:{type:"object",required:["path"],properties:{path:{type:"string",minLength:1,description:"from the repo root"},exported:{type:"boolean",default:!1,description:"only what is visible outside"}},additionalProperties:!1}},{name:"myc_code_map",description:"Map of an unfamiliar repo: directories by weight, their hub symbols and who depends on whom by import. One call to get oriented, then myc_code_search and myc_callers.",inputSchema:{type:"object",properties:{top:{type:"integer",default:14,minimum:1,description:"directories"}},additionalProperties:!1}}],x3=[...b3,...w3]});function EF($){return Math.ceil($.length/3)}function vF($){let X=$.name.length+$.description.length,Z=(Y)=>{if(Array.isArray(Y)){for(let z of Y)Z(z);return}if(typeof Y==="object"&&Y!==null)for(let[z,J]of Object.entries(Y))if(z==="description"&&typeof J==="string")X+=J.length;else Z(J)};return Z($.inputSchema),X}function zx($){let X=$.reduce((Z,Y)=>Z+vF(Y),0);return EF(" ".repeat(X))}var $x=1100,Xx=727,Zx=727,Yx=1827;import{existsSync as Ux,readFileSync as n20}from"fs";import{dirname as d20,join as Kx,resolve as Jx}from"path";import{Database as o20}from"bun:sqlite";function fF($,X,Z){let Y=Z?.extensions===!0,z=I$(),J;if(Y)try{if(!l$().vec.loaded&&z.locked!==null)J=z.locked}catch(Q){J=Q instanceof Error?Q.message:String(Q)}let U=new o20($,{create:!0});try{if(Y&&J===void 0)q8(U);for(let Q of j6)U.exec(Q)}catch(Q){throw U.close(),Q}let K=Y&&J===void 0&&v4()?.vec.loaded===!0,W=y7(U,X),V=new Map,G=(Q)=>{let L=V.get(Q.name);if(L===void 0)L=U.prepare(Q.sql),V.set(Q.name,L);return L},H=0,N={dialect:"sqlite",database:U,wal:W,vec0:K,vec0Reason:J,one(Q,L){let B=G(Q).get(...L);return B===null?void 0:B},all(Q,L){return G(Q).all(...L)},run(Q,L){let B=G(Q).run(...L);if(H===0)W.afterCommit();return{changes:Number(B.changes)}},tx(Q,L){if(H>0)throw Error("nested transactions are not supported");H++,U.exec(Q==="immediate"?"BEGIN IMMEDIATE":"BEGIN");try{let B=L(N);return U.exec("COMMIT"),W.afterCommit(),B}catch(B){try{U.exec("ROLLBACK")}catch{}throw B}finally{H--}},close(){V.clear(),U.close()}};return N}function a20($){let X=Kx($,"workspace.toml");if(!Ux(X))return"myc";try{for(let Z of n20(X,"utf8").split(`
|
|
9674
|
-
`)){let Y=/^slug\s*=\s*"([a-z][a-z0-9]{1,7})"/.exec(Z.trim());if(Y)return Y[1]}}catch{}return"myc"}function
|
|
9673
|
+
FROM jobs WHERE kind = 'code_index' AND attempts < max_attempts`,params:["now"]}});c20=[{name:"scope",value:"string",description:"project (default) or user \u2014 the line of Claude Code's user layer (myc wire --scope user --status-line): "+"outside a myc workspace it prints nothing of its own, and still hands the input on"},{name:"then",value:"string",description:"the project statusLine command we replaced: gets the same stdin"},{name:"wait-ms",value:"number",description:`wait up to N ms for THIS render's foreign output (default ${CF}: never wait, show its last completed run)`},{name:"no-pass",description:"do not hand the input to any foreign statusLine"}]});function AW($){if($!=="agent")throw Error(`profile '${$}' is not implemented yet (myc-zdk); available: agent`);return x3}var R4,b3,IF,w3,x3;var kF=v(()=>{R4={type:"string",description:"workspace; M0: single, ignored"},b3=[{name:"myc_prime",description:"Project start packet: ready queue, work in progress, core and recent decisions. "+"Call at session start and again right after context compaction \u2014 "+"replaces reading the README, plans and task history.",inputSchema:{type:"object",properties:{budget:{type:"integer",default:2000,minimum:200,maximum:8000,description:"answer budget in chars"},ws:R4},additionalProperties:!1}},{name:"myc_ready",description:"Tasks with no open blockers \u2014 what you can take right now. "+"With claim=true it atomically takes the top one (or the one in id) and returns "+"its description, deps and anchors at once \u2014 then just work, no extra calls.",inputSchema:{type:"object",properties:{n:{type:"integer",default:5,minimum:1,maximum:50},claim:{type:"boolean",default:!1,description:"atomically take a task and return its context"},id:{type:"string",description:"take a specific task (only with claim=true)"},kind:{type:"array",items:{type:"string",enum:["task","bug","epic","chore"]},maxItems:1},priority:{type:"array",items:{type:"string",enum:["P0","P1","P2","P3"]},maxItems:1},tag:{type:"array",items:{type:"string"},maxItems:1},lease_minutes:{type:"integer",default:30,minimum:5,maximum:480,description:"how long the task stays yours before the lease expires"},why:{type:"boolean",default:!1,description:"explain the sort order"},review:{type:"boolean",default:!1,description:"compaction candidates awaiting myc_update confirm/reject, not tasks"},ws:R4},additionalProperties:!1}},{name:"myc_update",description:"Every task state change in one tool: claim, release, close, reopen, assign, priority, note, extend; confirm/reject a compaction candidate. "+"close, reopen and reject require a reason \u2014 "+"it goes into project memory and later sessions see it.",inputSchema:{type:"object",required:["id","op"],properties:{id:{type:"string"},op:{type:"string",enum:["claim","release","close","reopen","assign","priority","note","extend","confirm","reject"],description:"cancel is left out on purpose: cancelling is a human judgment, say in your report that the work is not needed"},reason:{type:"string",description:"required for close, reopen, reject"},outcome:{type:"string",enum:["done","wontfix","duplicate","superseded"],default:"done",description:"how the task ended; for op=close"},duplicate_of:{type:"string",description:"canonical node for outcome=duplicate"},assignee:{type:"string"},priority:{type:"string",enum:["P0","P1","P2","P3"]},note:{type:"string",description:"note text for op=note"},lease_minutes:{type:"integer",minimum:5,maximum:480},steal:{type:"boolean",default:!1,description:"take over an expired lease"},verify:{type:"string",enum:["tests","review","human","none"],default:"none",description:"what proves the work: recorded with the close"},cost:{type:"object",description:"filled in by the host: tokens_in, tokens_out, model, retries",properties:{tokens_in:{type:"integer"},tokens_out:{type:"integer"},model:{type:"string"},retries:{type:"integer"}},additionalProperties:!1},ws:R4},additionalProperties:!1}},{name:"myc_create",description:"Create a node: task, bug, epic, memory, decision \u2014 same as CLI `myc create`. "+"For work items and structured nodes; to record a conclusion or fact prefer myc_remember, to change an existing node use myc_update.",inputSchema:{type:"object",required:["title"],properties:{title:{type:"string",minLength:1},kind:{type:"string",enum:["task","bug","epic","memory","decision","document","skill","message"],default:"task"},priority:{type:"string",enum:["P0","P1","P2","P3"],description:"tasks only"},parent:{type:"string",description:"parent node id \u2014 a child edge is added"},dep:{type:"array",items:{type:"string"},description:"ids that block the new node"},assign:{type:"string"},body:{type:"string"},tag:{type:"array",items:{type:"string"}},ws:R4},additionalProperties:!1}},{name:"myc_recall",needsVector:!0,description:"Search project memory in your own words: facts, decisions, tasks, episodes. "+"The answer is ranked and cut to the budget \u2014 read from the top and stop. "+"WARN/degraded in the answer = part of the index is down, quality is lower than usual.",inputSchema:{type:"object",required:["query"],properties:{query:{type:"string",minLength:2},n:{type:"integer",default:6,minimum:1,maximum:50,description:"how many nodes at most"},budget:{type:"integer",default:2000,minimum:200,maximum:8000,description:"answer budget in chars"},kind:{type:"array",items:{type:"string"},description:"task,bug,epic,memory,decision,document,skill,message"},layer:{type:"array",items:{type:"string",enum:["L0","L1","L2","L3"]},description:"default L1-L3"},tag:{type:"array",items:{type:"string"}},since:{type:"string",description:"e.g. 7d, 3w, 12h"},anchor:{type:"string",description:"file path \u2014 narrow to nodes anchored there"},mode:{type:"string",enum:["hybrid","vec","bm25"],default:"hybrid",description:"hybrid is default; vec \u2014 meaning only, bm25 \u2014 words only"},ws:R4},additionalProperties:!1}},{name:"myc_remember",description:"Record a conclusion, decision or fact so later sessions know it. One claim at a time, concrete, with its reason. No raw code or secrets. A contradiction gets flagged, it does not overwrite the old one.",inputSchema:{type:"object",required:["text"],properties:{text:{type:"string",minLength:8,maxLength:8000},tag:{type:"array",items:{type:"string"},maxItems:8},anchor:{type:"array",items:{type:"string"},maxItems:1,description:"path or path:start-end"},layer:{type:"string",enum:["L1","L2","L3"],default:"L1",description:"L1 fact, L2 decision, L3 constant (only with human consent)"},source:{type:"string",description:"url, file path, task id"},absorb:{type:"boolean",default:!0,description:"false \u2014 write as is, without checking against what is known"},ws:R4},additionalProperties:!1}},{name:"myc_show",description:"Full content of one or more nodes at once: body, deps, links, code anchors. Pass the list of ids in one call, not one by one.",inputSchema:{type:"object",required:["ids"],properties:{ids:{type:"array",items:{type:"string"},minItems:1,maxItems:20},depth:{type:"integer",enum:[0,1],default:0,description:"1 \u2014 titles of neighbours along edges"},source:{type:"boolean",default:!1,description:"pull in the code at the anchors (not lost ones)"},fields:{type:"array",items:{type:"string"},description:"limit fields \u2014 saves tokens"},ws:R4},additionalProperties:!1}},{name:"myc_link",description:"Create or remove a link between nodes: blocks/blocked-by (dependency), relates-to, duplicates, supersedes, contradicts, replies-to, derived-from, "+"part-of. supersedes and duplicates require a reason \u2014 history is not rewritten.",inputSchema:{type:"object",required:["from","type","to"],properties:{from:{type:"string"},to:{type:"string"},type:{type:"string",enum:["blocks","blocked-by","relates-to","duplicates","supersedes","contradicts","replies-to","derived-from","part-of"]},reason:{type:"string",description:"required for supersedes and duplicates"},remove:{type:"boolean",default:!1},ws:R4},additionalProperties:!1}}],IF=["call","new","type","import","read","prop"],w3=[{name:"myc_code_search",description:"Find code by a question in your own words when you don't know the name: files by rank "+"and the symbols matched in them with path:line \u2014 read from the top. Search is lexical: "+"the closer your words are to the code, the better. Know the name \u2014 myc_code_symbol; "+"need ALL occurrences \u2014 myc_code_grep.",inputSchema:{type:"object",required:["query"],properties:{query:{type:"string",minLength:1},limit:{type:"integer",default:10,minimum:1,description:"files"}},additionalProperties:!1}},{name:"myc_code_grep",description:"Every occurrence of a string in the repo's files, with its owner (function, class) \u2014 "+"exhaustive, unlike search. For editing a constant, SQL, a key, an error text. Reads the disk, so it never lags behind the code; the occurrence count is full even when groups are cut.",inputSchema:{type:"object",required:["literal"],properties:{literal:{type:"string",minLength:1},ignore_case:{type:"boolean",default:!1},lang:{type:"array",items:{type:"string"},description:"ts, py, md\u2026"},in:{type:"array",items:{type:"string"},description:"dirs/files from the repo root"},limit:{type:"integer",default:60,minimum:1,description:"groups"}},additionalProperties:!1}},{name:"myc_code_symbol",description:"Where a symbol with this exact name is defined: path:span, kind, export, mention "+"count \u2014 and which tasks and memory facts are anchored to that span. "+"The cheapest answer when you know the name.",inputSchema:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1}},additionalProperties:!1}},{name:"myc_callers",description:"Who calls a symbol (in) or what it calls (out): one edge per caller, "+'with the code lines inside. depth N or "all" \u2014 the blast radius of an edit, '+"before renaming or changing a signature. The graph is by name: WARN callers.ambiguous \u2014 "+"same-name symbols are merged.",inputSchema:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1},direction:{type:"string",enum:["in","out"],default:"in",description:"in \u2014 who calls this symbol; out \u2014 what it calls"},depth:{default:1,description:'1, N or "all"'},kind:{type:"array",items:{type:"string",enum:[...IF,"all"]},description:"default: all for in, call+new for out"},limit:{type:"integer",default:40,minimum:1,description:"groups"}},additionalProperties:!1}},{name:"myc_skeleton",description:"A file's API instead of reading it whole: declarations with signatures and spans, nesting by indent, and how many times cheaper this is than the file. Then read "+"the span you need, not the file. WARN skeleton.stale \u2014 the file changed after indexing.",inputSchema:{type:"object",required:["path"],properties:{path:{type:"string",minLength:1,description:"from the repo root"},exported:{type:"boolean",default:!1,description:"only what is visible outside"}},additionalProperties:!1}},{name:"myc_code_map",description:"Map of an unfamiliar repo: directories by weight, their hub symbols and who depends on whom by import. One call to get oriented, then myc_code_search and myc_callers.",inputSchema:{type:"object",properties:{top:{type:"integer",default:14,minimum:1,description:"directories"}},additionalProperties:!1}}],x3=[...b3,...w3]});function EF($){return Math.ceil($.length/3)}function vF($){let X=$.name.length+$.description.length,Z=(Y)=>{if(Array.isArray(Y)){for(let z of Y)Z(z);return}if(typeof Y==="object"&&Y!==null)for(let[z,J]of Object.entries(Y))if(z==="description"&&typeof J==="string")X+=J.length;else Z(J)};return Z($.inputSchema),X}function zx($){let X=$.reduce((Z,Y)=>Z+vF(Y),0);return EF(" ".repeat(X))}var $x=1100,Xx=727,Zx=727,Yx=1827;import{existsSync as Ux,readFileSync as r20}from"fs";import{dirname as t20,join as Kx,resolve as Jx}from"path";import{Database as e20}from"bun:sqlite";function fF($,X,Z){let Y=Z?.extensions===!0,z=I$(),J;if(Y)try{if(!l$().vec.loaded&&z.locked!==null)J=z.locked}catch(Q){J=Q instanceof Error?Q.message:String(Q)}let U=new e20($,{create:!0});try{if(Y&&J===void 0)q8(U);for(let Q of j6)U.exec(Q)}catch(Q){throw U.close(),Q}let K=Y&&J===void 0&&v4()?.vec.loaded===!0,W=y7(U,X),V=new Map,G=(Q)=>{let L=V.get(Q.name);if(L===void 0)L=U.prepare(Q.sql),V.set(Q.name,L);return L},H=0,N={dialect:"sqlite",database:U,wal:W,vec0:K,vec0Reason:J,one(Q,L){let B=G(Q).get(...L);return B===null?void 0:B},all(Q,L){return G(Q).all(...L)},run(Q,L){let B=G(Q).run(...L);if(H===0)W.afterCommit();return{changes:Number(B.changes)}},tx(Q,L){if(H>0)throw Error("nested transactions are not supported");H++,U.exec(Q==="immediate"?"BEGIN IMMEDIATE":"BEGIN");try{let B=L(N);return U.exec("COMMIT"),W.afterCommit(),B}catch(B){try{U.exec("ROLLBACK")}catch{}throw B}finally{H--}},close(){V.clear(),U.close()}};return N}function $Y0($){let X=Kx($,"workspace.toml");if(!Ux(X))return"myc";try{for(let Z of r20(X,"utf8").split(`
|
|
9674
|
+
`)){let Y=/^slug\s*=\s*"([a-z][a-z0-9]{1,7})"/.exec(Z.trim());if(Y)return Y[1]}}catch{}return"myc"}function XY0(){return process.env.MYC_ACTOR??process.env.USER??"agent"}async function e9($,X){let Z=X?.dbPath!==void 0?Jx(X.dbPath):Kx(Jx($??process.cwd()),".myc","myc.db");if(!Ux(Z))return{ok:!1,failure:{code:"ws.not_initialized",msg:`workspace not initialized: ${Z} is missing`,hint:"myc init"}};let Y=$Y0(t20(Z)),z=X$.reduce((U,K)=>Math.max(U,K.version),0),J;try{if(J=fF(Z,void 0,X),L6(J.database)!==z)await i8(J.database,{migrations:X$,writable:!0});if(J.vec0)await $5(J.database)}catch(U){if(U instanceof t$)return{ok:!1,failure:{code:"precond.schema",msg:U.message,hint:"myc doctor --schema"}};if(U instanceof m8||U instanceof L$)return{ok:!1,failure:{code:U.code,msg:U.message,hint:U.hint}};return{ok:!1,failure:{code:"conflict.busy",msg:`database unavailable: ${U instanceof Error?U.message:String(U)}`}}}try{let{siteId:U}=d8({meta:a7(J),dbPath:Z,mint:()=>n8(Y)}),K,W=J.one(yF.oplog_last_hlc,[]);if(W!==void 0){let{ts:H,ctr:N}=d$(BigInt(W.hlc));K=new u0({initial:{ts:H,ctr:N}})}let V=XY0(),G=new T6(J,{newId:()=>n$(Y),actor:V,siteId:U,...K!==void 0?{clock:K}:{}});return{ok:!0,handle:{driver:J,vec0:J.vec0,vec0Reason:J.vec0Reason,store:G,claims:new z7(G,{holder:V}),actor:V,scope:Y==="myc"?"":Y,slug:Y,close:()=>J.close()}}}catch(U){return J.close(),{ok:!1,failure:{code:"internal.store",msg:U instanceof Error?U.message:String(U)}}}}function _4($,X){let Z=$.store.getNode(X);if(Z!==void 0)return{ok:!0,node:Z};let Y=JX(X),z=$.driver.all(yF.id_prefix,[Y.lower,Y.upper]).map((U)=>U.id);if(z.length===0&&!X.includes("-")){let U=JX(`${$.slug}-${X}`);z=$.driver.all(yF.id_prefix,[U.lower,U.upper]).map((K)=>K.id)}if(z.length===0)return{ok:!1,failure:{code:"notfound.node",msg:`node ${X} not found`}};if(z.length>1)return{ok:!1,failure:{code:"usage.ambiguous_id",msg:`prefix '${X}' is ambiguous: ${z.join(", ")}`,hint:"use a longer prefix"}};let J=$.store.getNode(z[0]);if(J===void 0)return{ok:!1,failure:{code:"notfound.node",msg:`node ${X} not found`}};return{ok:!0,node:J}}var SF,yF,gF;var h3=v(()=>{o();n0();SF={oplog_last_hlc:{name:"oplog_last_hlc",sql:"SELECT CAST(hlc AS TEXT) AS hlc FROM oplog ORDER BY seq DESC LIMIT 1",params:[]},id_prefix:{name:"id_prefix",sql:`SELECT id FROM nodes
|
|
9675
9675
|
WHERE id >= ?1 AND id < ?2 AND deleted_at IS NULL
|
|
9676
9676
|
ORDER BY id LIMIT 4`,params:["lower","upper"]}},yF=SF;gF={"relates-to":"relates",duplicates:"duplicates",supersedes:"supersedes",contradicts:"contradicts","replies-to":"replies_to","derived-from":"derived_from","part-of":"parent"}});function m3($){return`${new Date($).toISOString().slice(11,19)}Z`}function t5($){let X=Math.max(0,$),Z=Math.floor(X/60000);if(Z<1)return`${Math.floor(X/1000)}s`;if(Z<60)return`${Z}m`;let Y=Math.floor(Z/60);if(Y<24)return`${Y}h`;return`${Math.floor(Y/24)}d`}function c$($){if($===void 0||$.length===0)return"";return`${$.map((X)=>`WARN ${X.code}: ${X.msg}`).join(`
|
|
9677
9677
|
`)}
|
|
@@ -9699,24 +9699,24 @@ ${$.took_ms} ms
|
|
|
9699
9699
|
`}function wF($){let X=(Y)=>Y.length===0?"\u2014":Y.map((z)=>z==="absorb"&&$.absorb_heuristic?"absorb(heuristic \u2014 chat-LLM off)":z).join(", "),Z=$.items.map((Y)=>{switch(Y.outcome){case"confirmed":return`${Y.id} confirmed \xB7 recall and prime return it now \xB7 queue ${X(Y.queue)}`;case"already_confirmed":return`${Y.id} already confirmed by ${Y.by||"?"} \xB7 nothing to do`;case"rejected":return`${Y.id} rejected \xB7 status retracted \xB7 reason: ${Y.reason??""}`;case"already_rejected":return`${Y.id} already rejected by ${Y.by||"?"} \xB7 nothing to do`}});return Z.push(`${$.changed} changed \xB7 ${$.took_ms} ms`),`${Z.join(`
|
|
9700
9700
|
`)}
|
|
9701
9701
|
`}function H$($,X=[]){let Z=[...$.meta.degraded??[],...X];return{took_ms:typeof $.meta.took_ms==="number"?$.meta.took_ms:$.data?.took_ms??0,degraded:Z}}function s0($,X){return{content:[{type:"text",text:$}],structuredContent:X}}function xF($,X,Z=void 0,Y={}){let z=`myc: ${$}: ${X}`;if(Z!==void 0)z+=`
|
|
9702
|
-
hint: ${Z}`;let J=c$(Y.warn);if(J.length>0)z=`${J}${z}`;return{content:[{type:"text",text:z}],isError:!0,...Y.structured!==void 0?{structuredContent:Y.structured}:{}}}function j$($,X){let Z=$[X];if(typeof Z!=="string"||Z.trim().length===0)throw new T0("usage.missing",`missing parameter '${X}'`);return Z}function u$($,X){let Z=$[X];if(Z===void 0)return;if(typeof Z!=="string")throw new T0("usage.invalid",`'${X}' must be a string`);return Z}function i$($,X){let Z=$[X];if(Z===void 0)return[];if(!Array.isArray(Z)||Z.some((Y)=>typeof Y!=="string"))throw new T0("usage.invalid",`'${X}' must be an array of strings`);return Z}function DW($,X){if($.length>1)throw new T0("usage.invalid",`'${X}': M0 takes a single value, got ${$.length}`);return $[0]}function $Z($,X,Z,Y,z){let J=$[X];if(J===void 0)return Z;if(typeof J!=="number"||!Number.isFinite(J))throw new T0("usage.invalid",`'${X}' must be a number`);return Math.max(Y,Math.min(z,Math.floor(J)))}function I4($,X){return $[X]===!0}async function Q$($,X){return Tx($,[...X,"--json"])}async function Tx($,X){let Z;try{Z=await $(X)}catch(Y){throw new T0("internal.unexpected",Y instanceof Error?Y.message:String(Y))}try{return JSON.parse(Z.stdout)}catch{throw new T0("internal.unexpected",`engine returned non-JSON (code ${Z.code}): ${Z.stderr??Z.stdout.slice(0,200)}`)}}async function e5($,X){return(await $(X)).stdout}function N$($,X={}){let Z=$.error??{code:"internal.unexpected",msg:"engine returned an error without an envelope",exit:1};return xF(Z.code,Z.msg,Z.hint,{warn:$.warn??[],structured:X.structured})}async function MW($,X){let Y=await($.openStore??(()=>e9()))();if(!Y.ok){let z=Y.failure;throw new T0(z.code,z.msg,z.hint)}try{return await X(Y.handle)}finally{Y.handle.close()}}function RW($,X){return{took_ms:Math.max(1,Math.round(performance.now()-X)),degraded:[],seq:$.store.lastSeq}}async function Nx($,X,Z){let Y=performance.now();return MW($,(z)=>{let J=_4(z,X);if(!J.ok)throw new T0(J.failure.code,J.failure.msg,J.failure.hint);let U=z.store.createNode(c7({text:Z,scope:z.scope,actor:z.actor}));return z.store.addEdge(U.id,"replies_to",J.node.id),{noteId:U.id,targetId:J.node.id,meta:RW(z,Y)}})}async function
|
|
9703
|
-
${B}`;return s0(q,{claimed:{...N,lease_until:new Date(N.lease_expires).toISOString(),...T!==void 0?{title:T.title,body:T.body,deps:T.blocked_by,anchors:T.anchors,links:T.links,related:T.related}:{}},meta:H$(H)})}let K=await Q$($.runCli,["ready","--claim","--lease",`${Y}m`,...U]);if(!K.ok)return N$(K);let W=K.data,V=`${c$(K.warn??[])}${Wx(W)}`,G=W.claimed;return s0(V,{ready:[],claimed:G!==void 0?{...G,lease_until:new Date(G.lease_expires).toISOString()}:null,counts:{ready:W.ready,blocked:W.blocked,in_progress:W.in_progress},meta:H$(K)})}async function
|
|
9702
|
+
hint: ${Z}`;let J=c$(Y.warn);if(J.length>0)z=`${J}${z}`;return{content:[{type:"text",text:z}],isError:!0,...Y.structured!==void 0?{structuredContent:Y.structured}:{}}}function j$($,X){let Z=$[X];if(typeof Z!=="string"||Z.trim().length===0)throw new T0("usage.missing",`missing parameter '${X}'`);return Z}function u$($,X){let Z=$[X];if(Z===void 0)return;if(typeof Z!=="string")throw new T0("usage.invalid",`'${X}' must be a string`);return Z}function i$($,X){let Z=$[X];if(Z===void 0)return[];if(!Array.isArray(Z)||Z.some((Y)=>typeof Y!=="string"))throw new T0("usage.invalid",`'${X}' must be an array of strings`);return Z}function DW($,X){if($.length>1)throw new T0("usage.invalid",`'${X}': M0 takes a single value, got ${$.length}`);return $[0]}function $Z($,X,Z,Y,z){let J=$[X];if(J===void 0)return Z;if(typeof J!=="number"||!Number.isFinite(J))throw new T0("usage.invalid",`'${X}' must be a number`);return Math.max(Y,Math.min(z,Math.floor(J)))}function I4($,X){return $[X]===!0}async function Q$($,X){return Tx($,[...X,"--json"])}async function Tx($,X){let Z;try{Z=await $(X)}catch(Y){throw new T0("internal.unexpected",Y instanceof Error?Y.message:String(Y))}try{return JSON.parse(Z.stdout)}catch{throw new T0("internal.unexpected",`engine returned non-JSON (code ${Z.code}): ${Z.stderr??Z.stdout.slice(0,200)}`)}}async function e5($,X){return(await $(X)).stdout}function N$($,X={}){let Z=$.error??{code:"internal.unexpected",msg:"engine returned an error without an envelope",exit:1};return xF(Z.code,Z.msg,Z.hint,{warn:$.warn??[],structured:X.structured})}async function MW($,X){let Y=await($.openStore??(()=>e9()))();if(!Y.ok){let z=Y.failure;throw new T0(z.code,z.msg,z.hint)}try{return await X(Y.handle)}finally{Y.handle.close()}}function RW($,X){return{took_ms:Math.max(1,Math.round(performance.now()-X)),degraded:[],seq:$.store.lastSeq}}async function Nx($,X,Z){let Y=performance.now();return MW($,(z)=>{let J=_4(z,X);if(!J.ok)throw new T0(J.failure.code,J.failure.msg,J.failure.hint);let U=z.store.createNode(c7({text:Z,scope:z.scope,actor:z.actor}));return z.store.addEdge(U.id,"replies_to",J.node.id),{noteId:U.id,targetId:J.node.id,meta:RW(z,Y)}})}async function ZY0($,X){let Z=$Z(X,"budget",2000,200,8000),Y=["prime","--budget",String(Z)],z=await Q$($.runCli,Y);if(!z.ok)return N$(z);let J=await e5($.runCli,Y);return s0(`${c$(z.warn??[])}${J}`,{...z.data,meta:H$(z)})}function YY0($){let X=[],Z=DW(i$($,"kind"),"kind");if(Z!==void 0)X.push("--kind",Z);let Y=DW(i$($,"priority"),"priority");if(Y!==void 0)X.push("--priority",Y);let z=DW(i$($,"tag"),"tag");if(z!==void 0)X.push("--tag",z);if(I4($,"why"))X.push("--why");return X}async function qx($,X){let Z=await Q$($.runCli,["ready","--n","1"]),Y=Z.ok?Z.data.items??[]:[];return N$(X,{structured:{ready:Y,counts:Z.ok?{ready:Z.data.ready??0,blocked:Z.data.blocked??0,in_progress:Z.data.in_progress??0}:void 0,meta:H$(X)}})}async function zY0($,X){let Z=$Z(X,"n",5,1,50),Y=$Z(X,"lease_minutes",30,5,480),z=I4(X,"claim"),J=u$(X,"id"),U=YY0(X);if(I4(X,"review")){if(z||J!==void 0||U.length>0)throw new T0("usage.invalid","'review' lists compaction candidates, not tasks: claim, id, kind, priority, tag and why do not apply",'confirm or reject a candidate: myc_update {op:"confirm"|"reject", id}');let H=["review","--limit",String(Z)],[N,Q]=await Promise.all([e5($.runCli,H),Q$($.runCli,H)]);if(!Q.ok)return N$(Q);return s0(N,{...Q.data,meta:H$(Q)})}if(!z){if(J!==void 0)throw new T0("usage.invalid","'id' only makes sense with claim=true");let H=["ready","--n",String(Z),...U],[N,Q]=await Promise.all([e5($.runCli,H),Q$($.runCli,H)]);if(!Q.ok)return N$(Q);return s0(N,{...Q.data,meta:H$(Q)})}if(J!==void 0){let H=await Q$($.runCli,["claim",J,"--lease",`${Y}m`]);if(!H.ok){if(H.error?.code==="conflict.claimed")return qx($,H);return N$(H)}let N=H.data,Q=["show",N.id,"--depth","1"],[L,B]=await Promise.all([Q$($.runCli,Q),e5($.runCli,Q)]),T=L.ok&&L.data!==null?L.data:void 0,q=`${c$(H.warn??[])}${bF(N)}
|
|
9703
|
+
${B}`;return s0(q,{claimed:{...N,lease_until:new Date(N.lease_expires).toISOString(),...T!==void 0?{title:T.title,body:T.body,deps:T.blocked_by,anchors:T.anchors,links:T.links,related:T.related}:{}},meta:H$(H)})}let K=await Q$($.runCli,["ready","--claim","--lease",`${Y}m`,...U]);if(!K.ok)return N$(K);let W=K.data,V=`${c$(K.warn??[])}${Wx(W)}`,G=W.claimed;return s0(V,{ready:[],claimed:G!==void 0?{...G,lease_until:new Date(G.lease_expires).toISOString()}:null,counts:{ready:W.ready,blocked:W.blocked,in_progress:W.in_progress},meta:H$(K)})}async function UY0($,X){let Z=j$(X,"op"),Y=JY0[Z];if(Y!==void 0)throw new T0("precond.human_only",`op '${Z}' is not available to agents: ${Y}`);if(!Lx.includes(Z))throw new T0("usage.invalid",`invalid op '${Z}'; allowed: ${Lx.join(", ")}`,"myc_update only changes the state of an EXISTING node: to create one use myc_create, to record a conclusion or fact use myc_remember");let z=j$(X,"id"),J=$Z(X,"lease_minutes",30,5,480);switch(Z){case"claim":{let U=["claim",z,"--lease",`${J}m`];if(I4(X,"steal"))U.push("--steal");let K=await Q$($.runCli,U);if(!K.ok){if(K.error?.code==="conflict.claimed")return qx($,K);return N$(K)}let W=K.data,V=`${c$(K.warn??[])}${bF(W)}`;return s0(V,{id:W.id,status:"in_progress",previous:W.prev_status,assignee:W.holder,lease_until:new Date(W.lease_expires).toISOString(),meta:H$(K)})}case"close":{let U=j$(X,"reason"),K=["close",z,"--reason",U],W=u$(X,"outcome");if(W!==void 0)K.push("--outcome",W);let V=u$(X,"verify");if(V!==void 0)K.push("--verify",V);let G=u$(X,"duplicate_of");if(G!==void 0)K.push("--dup",G);let H=X.cost;if(H!==void 0){if(typeof H!=="object"||H===null)throw new T0("usage.invalid","'cost' must be an object");let B=H;if(typeof B.tokens_in==="number")K.push("--cost-in",String(B.tokens_in));if(typeof B.tokens_out==="number")K.push("--cost-out",String(B.tokens_out));if(typeof B.model==="string")K.push("--model",B.model);if(typeof B.retries==="number")K.push("--retries",String(B.retries))}let N=await Q$($.runCli,K);if(!N.ok)return N$(N);let Q=N.data,L=`${c$(N.warn??[])}${Vx(Q)}`;return s0(L,{id:Q.id,status:Q.status,previous:"in_progress",assignee:Q.closed_by,unblocked:Q.unblocked,meta:H$(N)})}case"reopen":{let U=j$(X,"reason"),K=await Q$($.runCli,["update",z,"--status","open"]);if(!K.ok)return N$(K);let W=K.data,V=`${c$(K.warn??[])}${PW(W)}`,G=[];try{let H=await Nx($,z,`reopen: ${U}`);V+=`reason saved as note ${H.noteId}
|
|
9704
9704
|
`}catch(H){G.push("note.unwritten"),V+=`WARN note.unwritten: reopen reason not saved: ${H instanceof Error?H.message:String(H)}
|
|
9705
9705
|
`}return s0(V,{id:W.id,status:W.status,previous:"closed",meta:H$(K,G)})}case"assign":{let U=j$(X,"assignee"),K=await Q$($.runCli,["update",z,"--assign",U]);if(!K.ok)return N$(K);let W=K.data;return s0(`${c$(K.warn??[])}${PW(W)}`,{id:W.id,status:W.status,assignee:U,meta:H$(K)})}case"priority":{let U=j$(X,"priority"),K=await Q$($.runCli,["update",z,"--priority",U]);if(!K.ok)return N$(K);let W=K.data;return s0(`${c$(K.warn??[])}${PW(W)}`,{id:W.id,status:W.status,priority:U,meta:H$(K)})}case"note":{let U=j$(X,"note"),K=await Nx($,z,U),W=`${K.noteId} note \u2192 ${K.targetId}
|
|
9706
9706
|
`;return s0(W,{id:K.targetId,note_id:K.noteId,status:"noted",meta:K.meta})}case"release":{let U=performance.now();return MW($,(K)=>{let W=_4(K,z);if(!W.ok)throw new T0(W.failure.code,W.failure.msg,W.failure.hint);let V=K.store.leaseOf(W.node.id);if(V===void 0||V.holder.length===0)throw new T0("precond.no_lease",`${W.node.id} has no lease \u2014 nothing to release`);if(!K.store.releaseLease(W.node.id,V.holder,V.epoch))throw new T0("conflict.release",`lease on ${W.node.id} changed \u2014 retry`);if(W.node.status==="in_progress")K.store.updateNode(W.node.id,{status:"open"});let G=`released ${W.node.id} \xB7 lease of ${V.holder} dropped, status open
|
|
9707
9707
|
`;return s0(G,{id:W.node.id,status:"open",previous:"in_progress",assignee:null,lease_until:null,meta:RW(K,U)})})}case"confirm":{let U=await Q$($.runCli,["review","confirm",z]);if(!U.ok)return N$(U);let K=U.data,W=K.items[0];return s0(`${c$(U.warn??[])}${wF(K)}`,{id:W?.id??z,review:"confirmed",changed:K.changed>0,queued:W?.queue??[],meta:H$(U)})}case"reject":{let U=j$(X,"reason"),K=await Q$($.runCli,["review","reject",z,"--reason",U]);if(!K.ok)return N$(K);let W=K.data,V=W.items[0];return s0(`${c$(K.warn??[])}${wF(W)}`,{id:V?.id??z,review:"rejected",status:"retracted",changed:W.changed>0,reason:U,meta:H$(K)})}case"extend":{let U=performance.now();return MW($,(K)=>{let W=_4(K,z);if(!W.ok)throw new T0(W.failure.code,W.failure.msg,W.failure.hint);let V=K.store.leaseOf(W.node.id);if(V===void 0||V.holder.length===0)throw new T0("precond.no_lease",`${W.node.id} has no lease \u2014 nothing to extend`);if(V.holder!==K.actor)throw new T0("conflict.claimed",`${W.node.id} is held by ${V.holder} \u2014 only the holder can extend it`,'myc_update {op:"claim", steal:true} once the lease expires');let G=J*60000,H=K.store.renewLease(W.node.id,V.holder,V.epoch,G);if(H===void 0)throw new T0("conflict.release",`lease on ${W.node.id} changed \u2014 retry`);let N=`renewed ${W.node.id} by ${V.holder} \xB7 lease ${t5(G)} until ${m3(H)}
|
|
9708
|
-
`;return s0(N,{id:W.node.id,status:W.node.status,assignee:V.holder,lease_until:new Date(H).toISOString(),meta:RW(K,U)})})}}throw new T0("usage.invalid",`op '${Z}' is not supported`)}async function
|
|
9708
|
+
`;return s0(N,{id:W.node.id,status:W.node.status,assignee:V.holder,lease_until:new Date(H).toISOString(),meta:RW(K,U)})})}}throw new T0("usage.invalid",`op '${Z}' is not supported`)}async function KY0($,X){let Y=["create",j$(X,"title"),"--kind",u$(X,"kind")??"task"],z=u$(X,"priority");if(z!==void 0)Y.push("--priority",z);let J=u$(X,"parent");if(J!==void 0)Y.push("--parent",J);let U=u$(X,"assign");if(U!==void 0)Y.push("--assign",U);let K=u$(X,"body");if(K!==void 0)Y.push("--body",K);let W=i$(X,"dep");if(W.length>0)Y.push("--dep",W.join(","));let V=i$(X,"tag");if(V.length>0)Y.push("--tag",V.join(","));let G=await Q$($.runCli,Y);if(!G.ok)return N$(G);let H=G.data;return s0(`${c$(G.warn??[])}${Gx(H)}`,{...H,meta:H$(G)})}async function WY0($,X){let Z=j$(X,"query");if(Z.trim().length<2)throw new T0("usage.invalid","query is shorter than two characters");let Y=$Z(X,"n",6,1,50),z=$Z(X,"budget",2000,200,8000),J=["recall",Z,"--limit",String(Y),"--budget",String(z)],U=i$(X,"kind");if(U.length>0)J.push("--kind",U.join(","));let K=i$(X,"layer");if(K.length>0)J.push("--layer",K.length===1?K[0]:`${K[0]}..${K[K.length-1]}`);let W=i$(X,"tag");if(W.length>0)J.push("--tag",W.join(","));let V=u$(X,"since");if(V!==void 0)J.push("--since",V);let G=u$(X,"anchor");if(G!==void 0)J.push("--anchor",G);let H=u$(X,"mode");if(H!==void 0)J.push("--mode",H);let[N,Q]=await Promise.all([e5($.runCli,J),Q$($.runCli,J)]);if(!Q.ok)return N$(Q);return s0(N,{...Q.data,meta:H$(Q)})}async function VY0($,X){let Z=j$(X,"text");if(Z.trim().length<8)throw new T0("usage.invalid","fact is shorter than 8 characters \u2014 be more specific");let Y=["remember",Z],z=i$(X,"tag");if(z.length>0)Y.push("--tag",z.join(","));let J=i$(X,"anchor"),U=DW(J,"anchor");if(U!==void 0)Y.push("--anchor",U);let K=u$(X,"layer");if(K!==void 0)Y.push("--layer",K);let W=u$(X,"source");if(W!==void 0)Y.push("--source",W);let V=X.absorb!==!1;if(!V)Y.push("--no-absorb");let G=await Q$($.runCli,Y);if(!G.ok)return N$(G);let H=G.data,N=[],Q=c$(G.warn??[]);if(H.absorb_heuristic)N.push("llm.chat.off"),Q+=`WARN llm.chat.off: absorb classification is heuristic \u2014 chat LLM is off
|
|
9709
9709
|
`;let L=H.duplicate_of!==void 0,B=L?`${H.id} duplicate \xB7 exact repeat${H.review_confirmed===!0?" of an unconfirmed compaction candidate \u2014 confirmed now, recall and prime return it":""}, seen_count ${H.seen_count??"?"}
|
|
9710
|
-
`:"";return s0(`${Q}${B}${L?"":Qx(H)}`,{id:H.id,verdict:L?"duplicate":"new",verdict_source:!V?"skipped":H.absorb_heuristic?"heuristic":"llm",written:!L,...H.review_confirmed===!0?{review_confirmed:!0}:{},redacted:0,queued:H.queue,meta:H$(G,N)})}async function
|
|
9710
|
+
`:"";return s0(`${Q}${B}${L?"":Qx(H)}`,{id:H.id,verdict:L?"duplicate":"new",verdict_source:!V?"skipped":H.absorb_heuristic?"heuristic":"llm",written:!L,...H.review_confirmed===!0?{review_confirmed:!0}:{},redacted:0,queued:H.queue,meta:H$(G,N)})}async function GY0($,X){let Z=i$(X,"ids");if(Z.length===0)throw new T0("usage.missing","missing parameter 'ids' (1..20)");if(Z.length>20)throw new T0("usage.invalid",`up to 20 nodes per call, got ${Z.length}`);let Y=["show",Z.join(",")],z=X.depth;if(z!==void 0){if(z!==0&&z!==1)throw new T0("usage.invalid","'depth' takes 0 or 1");Y.push("--depth",String(z))}if(I4(X,"source"))Y.push("--source");let J=i$(X,"fields");if(J.length>0)Y.push("--field",J.join(","));let[U,K]=await Promise.all([e5($.runCli,Y),Q$($.runCli,Y)]);if(!K.ok)return N$(K);let W=K.data??{},V=Array.isArray(W.nodes)?W.nodes:[W],G={...W};return delete G.nodes,delete G.took_ms,s0(U,{nodes:V,...Array.isArray(W.nodes)?G:{},meta:H$(K)})}async function HY0($,X){let Z=j$(X,"from"),Y=j$(X,"to"),z=j$(X,"type");if(!Bx.includes(z))throw new T0("usage.invalid",`invalid type '${z}'; allowed: ${Bx.join(", ")}`);let J=u$(X,"reason");if((z==="supersedes"||z==="duplicates")&&J===void 0)throw new T0("usage.missing",`${z} requires a reason \u2014 history is not rewritten`);let U=I4(X,"remove");if(z==="blocks"||z==="blocked-by"){let W=U?["dep","rm",Z,z,Y]:["dep","add",Z,z,Y],V=await Q$($.runCli,W);if(!V.ok)return N$(V);let G=V.data,H=`${c$(V.warn??[])}${Hx(G)}`;return s0(H,{ok:!0,edge:{from:G.src,type:z,to:G.dst},effects:G.left_ready===!0?[`${G.left_ready_id} left ready`]:G.back_ready===!0?[`${G.back_ready_id} is ready again`]:[],meta:H$(V)})}let K=performance.now();return MW($,(W)=>{let V=_4(W,Z);if(!V.ok)throw new T0(V.failure.code,V.failure.msg,V.failure.hint);let G=_4(W,Y);if(!G.ok)throw new T0(G.failure.code,G.failure.msg,G.failure.hint);let H=gF[z],N=V.node.id,Q=G.node.id,L=[];if(U){if(!W.store.removeEdge(N,H,Q))throw new T0("notfound.edge",`no edge ${N} ${z} ${Q}`)}else{let T=W.store.getEdge(N,H,Q);if(T!==void 0&&T.deleted_at===null)throw new T0("conflict.edge_exists",`edge ${N} ${z} ${Q} already exists`);try{W.store.addEdge(N,H,Q,{...J!==void 0?{attrs:{reason:J}}:{}})}catch(q){throw new T0("usage.invalid",q instanceof Error?q.message:String(q))}if(z==="supersedes")W.store.updateNode(Q,{attrs:{superseded_by:N}}),L.push(`${Q} marked superseded_by ${N}; the old node is kept`);if(J!==void 0)L.push(`reason: ${J}`)}let B=U?`${z} ${N} \u2192 ${Q} removed
|
|
9711
9711
|
`:`${N} ${z} ${Q}${L.length>0?`
|
|
9712
9712
|
effects ${L.join(" \xB7 ")}`:""}
|
|
9713
|
-
`;return s0(B,{ok:!0,edge:{from:N,type:z,to:Q},effects:L,meta:RW(W,K)})})}async function XZ($,X,Z){let Y=Z!==void 0?["--",Z]:[],[z,J]=await Promise.all([e5($.runCli,[...X,...Y]),Tx($.runCli,[...X,"--json",...Y])]);if(!J.ok)return N$(J);return s0(z,{...J.data,meta:H$(J)})}function
|
|
9713
|
+
`;return s0(B,{ok:!0,edge:{from:N,type:z,to:Q},effects:L,meta:RW(W,K)})})}async function XZ($,X,Z){let Y=Z!==void 0?["--",Z]:[],[z,J]=await Promise.all([e5($.runCli,[...X,...Y]),Tx($.runCli,[...X,"--json",...Y])]);if(!J.ok)return N$(J);return s0(z,{...J.data,meta:H$(J)})}function QY0($,X){let Z=$[X];if(typeof Z!=="string"||Z.length===0)throw new T0("usage.missing",`missing parameter '${X}'`);return Z}function _W($,X){let Z=$[X];if(Z===void 0)return;if(typeof Z!=="number"||!Number.isInteger(Z)||Z<1)throw new T0("usage.invalid",`'${X}' must be an integer >= 1`);return String(Z)}function u3($,X,Z){if(Z!==void 0)$.push(X,Z)}async function NY0($,X){let Z=j$(X,"query"),Y=["code","search"];return u3(Y,"--limit",_W(X,"limit")),XZ($,Y,Z)}async function LY0($,X){let Z=QY0(X,"literal"),Y=["code","grep"];if(I4(X,"ignore_case"))Y.push("--ignore-case");let z=i$(X,"lang");if(z.length>0)Y.push("--lang",z.join(","));let J=i$(X,"in");if(J.length>0)Y.push("--in",J.join(","));return u3(Y,"--limit",_W(X,"limit")),XZ($,Y,Z)}async function BY0($,X){return XZ($,["code","symbol"],j$(X,"name"))}async function TY0($,X){let Z=j$(X,"name"),Y=["callers"];u3(Y,"--direction",u$(X,"direction"));let z=X.depth;if(z!==void 0){if(typeof z!=="number"&&typeof z!=="string")throw new T0("usage.invalid",`'depth' must be an integer >= 1 or "all"`);Y.push("--depth",String(z))}let J=i$(X,"kind");if(J.length>0)Y.push("--kind",J.join(","));return u3(Y,"--limit",_W(X,"limit")),XZ($,Y,Z)}async function qY0($,X){let Z=j$(X,"path"),Y=["skeleton"];if(I4(X,"exported"))Y.push("--exported");return XZ($,Y,Z)}async function FY0($,X){let Z=["code","map"];return u3(Z,"--top",_W(X,"top")),XZ($,Z)}function IW($){return async(X,Z)=>{let Y=jY0[X];if(Y===void 0)throw new k4(`unknown tool '${X}'`);try{return await Y($,Z)}catch(z){if(z instanceof T0)return xF(z.code,z.message,z.hint);return xF("internal.unexpected",z instanceof Error?z.message:String(z))}}}var k4,T0,Lx,JY0,Bx,jY0;var kW=v(()=>{o();h3();k4=class k4 extends Error{};T0=class T0 extends Error{code;hint;constructor($,X,Z){super(X);this.code=$;this.hint=Z}};Lx=["claim","release","close","reopen","assign","priority","note","extend","confirm","reject"],JY0={cancel:"cancelling decides whether the work is needed AT ALL \u2014 that is a human judgment (S54), "+"and it is terminal: a cancelled blocker immediately releases dependent tasks into the ready queue. If the work looks unnecessary, say so in your report and leave the decision to a human; it can be cancelled from the CLI (`myc update <id> --status cancelled`) or from the web UI"};Bx=["blocks","blocked-by",...Object.keys(gF)];jY0={myc_prime:ZY0,myc_ready:zY0,myc_update:UY0,myc_create:KY0,myc_recall:WY0,myc_remember:VY0,myc_show:GY0,myc_link:HY0,myc_code_search:NY0,myc_code_grep:LY0,myc_code_symbol:BY0,myc_callers:TY0,myc_skeleton:qY0,myc_code_map:FY0}});function Fx($,X){return`${JSON.stringify({jsonrpc:"2.0",id:$,result:X})}
|
|
9714
9714
|
`}function ZZ($,X){return`${JSON.stringify({jsonrpc:"2.0",id:$,error:X})}
|
|
9715
9715
|
`}class zZ{opts;#$;constructor($){this.opts=$}async#X(){if(this.#$!==void 0)return this.#$;let $=this.opts.instructions;if($===void 0)return;let X=typeof $==="function"?await $():$;return this.#$=X,X}async handleLine($){let X;try{X=JSON.parse($)}catch{return ZZ(null,{code:-32700,message:"parse error: not JSON"})}if(Array.isArray(X)||typeof X!=="object"||X===null)return ZZ(null,{code:-32600,message:"invalid request: single object expected"});let Z=X,Y=Z.id??null,z=Z.method;if(typeof z!=="string")return ZZ(Y,{code:-32600,message:"invalid request: no method"});let J=Z.id===void 0;try{let U=await this.#Z(z,Z.params,J);if(J)return null;if(U===void 0)return Fx(Y,{});return Fx(Y,U)}catch(U){if(J)return null;if(U instanceof k4)return ZZ(Y,{code:-32602,message:U.message});if(U instanceof YZ)return ZZ(Y,{code:U.code,message:U.message});return ZZ(Y,{code:-32603,message:U instanceof Error?U.message:String(U)})}}async#Z($,X,Z){switch($){case"initialize":{if(Z)return;let Y=await this.#X();return{protocolVersion:hF,capabilities:{tools:{}},serverInfo:{name:this.opts.name??"myc",version:this.opts.version??"0.0.0"},...Y!==void 0?{instructions:Y}:{}}}case"notifications/initialized":case"notifications/cancelled":return;case"ping":return{};case"tools/list":return{tools:this.opts.tools};case"tools/call":{if(typeof X!=="object"||X===null)throw new YZ(-32602,"tools/call: params required");let Y=X,z=Y.name;if(typeof z!=="string")throw new YZ(-32602,"tools/call: 'name' required");let J=Y.arguments;if(J!==void 0&&(typeof J!=="object"||J===null||Array.isArray(J)))throw new YZ(-32602,"tools/call: 'arguments' must be an object");return await this.opts.dispatch(z,J??{})}default:if($.startsWith("notifications/"))return;throw new YZ(-32601,`method not found: ${$}`)}}}async function l3($,X,Z){let Y=X.getReader(),z=new TextDecoder,J="";try{for(;;){let{done:K,value:W}=await Y.read();if(K)break;J+=z.decode(W,{stream:!0});let V;while((V=J.indexOf(`
|
|
9716
|
-
`))>=0){let G=J.slice(0,V).trim();if(J=J.slice(V+1),G.length===0)continue;let H=await $.handleLine(G);if(H!==null)Z(H)}}let U=J.trim();if(U.length>0){let K=await $.handleLine(U);if(K!==null)Z(K)}}finally{Y.releaseLock()}}var hF="2025-06-18",YZ;var mF=v(()=>{kW();YZ=class YZ extends Error{code;constructor($,X){super(X);this.code=$}}});import{existsSync as Ax,readFileSync as jx,statSync as
|
|
9716
|
+
`))>=0){let G=J.slice(0,V).trim();if(J=J.slice(V+1),G.length===0)continue;let H=await $.handleLine(G);if(H!==null)Z(H)}}let U=J.trim();if(U.length>0){let K=await $.handleLine(U);if(K!==null)Z(K)}}finally{Y.releaseLock()}}var hF="2025-06-18",YZ;var mF=v(()=>{kW();YZ=class YZ extends Error{code;constructor($,X){super(X);this.code=$}}});import{existsSync as Ax,readFileSync as jx,statSync as OY0}from"fs";import{homedir as CY0}from"os";import{basename as Ox,dirname as p3,join as EW,relative as AY0,resolve as JZ}from"path";function Cx($){let X=JZ(process.env.MYC_HOME??CY0()),Z=[],Y=JZ($),z=!1;for(;;){if(z&&Y===X)break;if(Z.push(Y),Ax(EW(Y,".myc","myc.db")))return{hit:Y,dirs:Z};let J=p3(Y);if(J===Y)break;Y=J,z=!0}return{hit:void 0,dirs:Z}}function PY0($){let X=EW($,".git");try{if(!OY0(X).isFile())return}catch{return}let Z;try{let z=/^gitdir:\s*(.+?)\s*$/m.exec(jx(X,"utf8"));if(z===null)return;Z=JZ($,z[1])}catch{return}let Y;try{Y=JZ(Z,jx(EW(Z,"commondir"),"utf8").trim())}catch{if(Ox(p3(Z))!=="worktrees")return;if(Y=p3(p3(Z)),Ox(Y)!==".git")return}return p3(Y)}function vW($){let X=Cx($);if(X.hit!==void 0)return X.hit;for(let Z of X.dirs){let Y=PY0(Z);if(Y===void 0)continue;if(!Ax(Y))return;let z=AY0(Z,JZ($)),J=z.startsWith("..")||z.startsWith("/")?JZ($):z.length===0?Y:EW(Y,z);return Cx(J).hit}return}var uF=()=>{};import{existsSync as DY0}from"fs";import{basename as MY0,dirname as Px,join as RY0,resolve as lF}from"path";function Mx($){return $.map((X)=>X.name.replace(/^myc_/,"")).join("/")}async function _Y0($){try{let X=await $(["bootstrap","--budget","1500","--json"]),Z=JSON.parse(X.stdout);if(Z.ok&&typeof Z.data?.text==="string"&&Z.data.text.trim().length>0)return`${Dx}
|
|
9717
9717
|
|
|
9718
|
-
${Z.data.text}`}catch{}return Dx}function
|
|
9718
|
+
${Z.data.text}`}catch{}return Dx}function IY0($,X){let Z=[];if(X.directory!==void 0)Z.push("-C",X.directory);if(X.db!==void 0)Z.push("--db",X.db);return async(Y)=>{let z=await EY([...Z,...Y],$!==void 0?{registry:$}:{}),J=typeof z.stdout==="string"?z.stdout:[...z.stdout].join("");return{code:z.code,stdout:J,stderr:z.stderr}}}function Rx($){return $.some((X)=>X.needsVector===!0)}function kY0($){try{I$()}catch(X){return X instanceof Error?X.message:String(X)}if(!Rx($))return;try{l$();return}catch(X){return X instanceof Error?X.message:String(X)}}function pF($,X=process.env){if($.directory!==void 0)return $.directory;let Z=X.CLAUDE_PROJECT_DIR;return Z!==void 0&&Z.length>0?Z:void 0}function cF($,X){if($.db!==void 0){let Y=lF($.db);if(!DY0(Y))return;let z=Px(Y);return{wsDir:MY0(z)===".myc"?Px(z):z,dbPath:Y}}let Z=vW(X);return Z!==void 0?{wsDir:Z,dbPath:RY0(Z,".myc","myc.db")}:void 0}function _x($){return{name:"mcp",summary:"start MCP server on stdio (agent tool profile)",flags:[{name:"profile",value:"string",description:"agent (default); leader/full \u2014 separate task myc-zdk"}],help:"Starts the MCP server on stdio (NDJSON JSON-RPC 2.0). Profile agent \u2014 "+`${x3.length} tools: work \u2014 ${Mx(b3)}; `+`code \u2014 ${Mx(w3)} (\`myc code index\` builds the index). Working rules and the bootstrap block reach the client in initialize.instructions.`,handler:async(X)=>{let Z=X.flags.profile,Y=typeof Z==="string"?Z:"agent",z;try{z=AW(Y)}catch(H){return{ok:!1,code:"usage.invalid",msg:H instanceof Error?H.message:String(H),exit:2}}let J=pF(X.globals),U=cF(X.globals,J??process.cwd());if(U===void 0){let H=new zZ({tools:[],version:E0,dispatch:async(N)=>{throw new k4(`unknown tool '${N}': no myc workspace here`)}});return process.stderr.write(X.globals.db!==void 0?`myc mcp: no database at ${lF(X.globals.db)} (--db) \u2014 0 tools, stdio
|
|
9719
9719
|
`:`myc mcp: no myc workspace at ${lF(J??process.cwd())} \u2014 0 tools, stdio
|
|
9720
|
-
`),await l3(H,Bun.stdin.stream(),(N)=>{process.stdout.write(N)}),{ok:!0,data:null}}let K=Rx(z),W=
|
|
9720
|
+
`),await l3(H,Bun.stdin.stream(),(N)=>{process.stdout.write(N)}),{ok:!0,data:null}}let K=Rx(z),W=kY0(z),V=IY0($,{directory:J,db:X.globals.db}),G=new zZ({tools:z,version:E0,dispatch:IW({runCli:V,openStore:()=>e9(U.wsDir,{extensions:K,dbPath:U.dbPath})}),instructions:()=>_Y0(V)});if(process.stderr.write(`myc mcp: profile ${Y}, ${z.length} tools, stdio
|
|
9721
9721
|
`),W!==void 0)process.stderr.write(`myc mcp: SQLite / extension runtime failed to load, vector search unavailable: ${W}
|
|
9722
|
-
`);return await l3(G,Bun.stdin.stream(),(H)=>{process.stdout.write(H)}),{ok:!0,data:null}}}}var Dx;var Ix=v(()=>{v8();n0();kW();mF();h3();uF();kF();Dx="myc \u2014 this project's memory and tasks. Rules: start the session with myc_prime "+"and repeat it right after context compaction; take work with myc_ready{claim:true} "+"(one call \u2014 the task is yours, with all its context); before changing code, look "+"for context with myc_recall; write conclusions and decisions right away with myc_remember \u2014 "+"otherwise the next session won't know them. Ask the code tools about the code itself "+"instead of reading whole files: myc_code_map \u2014 orientation, myc_code_search and "+"myc_code_symbol \u2014 find, myc_skeleton \u2014 a file's API, myc_callers \u2014 blast radius "+"of an edit, myc_code_grep \u2014 every occurrence. WARN/degraded in an answer is not noise, "+"it means part of the system is down."});var kx={};s(kx,{toolsForProfile:()=>AW,toolDescriptionChars:()=>vF,serveStdio:()=>l3,resolveNode:()=>_4,profileDescriptionTokens:()=>zx,openMcpStore:()=>e9,mcpWorkspace:()=>cF,mcpQueries:()=>SF,mcpProjectDir:()=>pF,internalOpenDriver:()=>fF,findMcpWorkspace:()=>vW,estimateTokens:()=>EF,createMcpCommand:()=>_x,createDispatcher:()=>IW,WORK_TOOLS:()=>b3,UnknownToolError:()=>k4,McpServer:()=>zZ,MCP_PROTOCOL_VERSION:()=>hF,GRAFT_TOOLS_TOKENS:()=>Xx,DESCRIPTION_TOKEN_BUDGET:()=>$x,CODE_TOOLS:()=>w3,CODE_REF_KINDS:()=>IF,CODE_DESCRIPTION_TOKEN_BUDGET:()=>Zx,AGENT_TOOLS:()=>x3,AGENT_PROFILE_TOKEN_BUDGET:()=>Yx});var Ex=v(()=>{kF();kW();mF();Ix();uF();h3();h3()});function V9($){let X=(Z,Y)=>$.registerLazy(Z,Y);X("init",()=>Promise.resolve().then(() => (fL(),Tk)).then((Z)=>Z.createInitCommand())),X("models",()=>Promise.resolve().then(() => (Pk(),Ak)).then((Z)=>Z.modelsCommand)),X("model",()=>Promise.resolve().then(() => (BE(),LE)).then((Z)=>Z.modelCommand)),X("create",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createCreateCommand())),X("task",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createTaskCommand())),X("bug",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createBugCommand())),X("epic",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createEpicCommand())),X("msg",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createMsgCommand())),X("comment",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createCommentCommand())),X("update",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createUpdateCommand())),X("claim",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createClaimCommand())),X("release",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createReleaseCommand())),X("close",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createCloseCommand())),X("move",()=>Promise.resolve().then(() => (rE(),sE)).then((Z)=>Z.createMoveCommand())),X("attempt",()=>Promise.resolve().then(() => (UK(),gB)).then((Z)=>Z.createAttemptCommand())),X("report",()=>Promise.resolve().then(() => (UK(),gB)).then((Z)=>Z.createReportCommand())),X("show",()=>Promise.resolve().then(() => (zv(),Yv)).then((Z)=>Z.createShowCommand())),X("list",()=>Promise.resolve().then(() => (Uv(),Jv)).then((Z)=>Z.createListCommand())),X("dep",()=>Promise.resolve().then(() => (mB(),Lv)).then((Z)=>Z.createDepCommand())),X("link",()=>Promise.resolve().then(() => (Fv(),qv)).then((Z)=>Z.createLinkCommand())),X("ready",()=>Promise.resolve().then(() => (HK(),pB)).then((Z)=>Z.createReadyCommand())),X("prime",()=>Promise.resolve().then(() => (Ev(),kv)).then((Z)=>Z.createPrimeCommand())),X("viz",()=>Promise.resolve().then(() => (yy(),vy)).then((Z)=>Z.createVizCommand())),X("export",()=>Promise.resolve().then(() => (CK(),gy)).then((Z)=>Z.createExportCommand())),X("import",()=>Promise.resolve().then(() => (wy(),by)).then((Z)=>Z.createImportCommand())),X("sync",()=>Promise.resolve().then(() => (my(),hy)).then((Z)=>Z.createSyncCommand())),X("import-beads",()=>Promise.resolve().then(() => (Tf(),Bf)).then((Z)=>Z.createImportBeadsCommand())),X("merge-driver",()=>Promise.resolve().then(() => (Ff(),qf)).then((Z)=>Z.createMergeDriverCommand())),X("bootstrap",()=>Promise.resolve().then(() => (df(),nf)).then((Z)=>Z.createBootstrapCommand())),X("remember",()=>Promise.resolve().then(() => (nT(),ef)).then((Z)=>Z.createRememberCommand())),X("recall",()=>Promise.resolve().then(() => (WS(),KS)).then((Z)=>Z.createRecallCommand())),X("search",()=>Promise.resolve().then(() => (NS(),QS)).then((Z)=>Z.createSearchCommand())),X("embedd",()=>Promise.resolve().then(() => (WL(),TI)).then((Z)=>Z.createEmbeddCommand())),X("reindex",()=>Promise.resolve().then(() => (CS(),OS)).then((Z)=>Z.createReindexCommand())),X("anchor",()=>Promise.resolve().then(() => (k6(),J9)).then((Z)=>Z.createAnchorCommand())),X("code",()=>Promise.resolve().then(() => (PY(),n_)).then((Z)=>Z.createCodeCommand())),X("callers",()=>Promise.resolve().then(() => (DS(),PS)).then((Z)=>Z.createCallersCommand())),X("skeleton",()=>Promise.resolve().then(() => (_S(),RS)).then((Z)=>Z.createSkeletonCommand())),X("absorb",()=>Promise.resolve().then(() => (aQ(),NM)).then((Z)=>Z.createAbsorbCommand())),X("absorb-session",()=>Promise.resolve().then(() => (oS(),dS)).then((Z)=>Z.createAbsorbSessionCommand())),X("review",()=>Promise.resolve().then(() => (Ug(),Jg)).then((Z)=>Z.createReviewCommand())),X("run",()=>Promise.resolve().then(() => (Aq(),Cq)).then((Z)=>Z.createRunCommand())),X("queue",()=>Promise.resolve().then(() => (Aq(),Cq)).then((Z)=>Z.createQueueCommand())),X("doctor",()=>Promise.resolve().then(() => (_b(),Rb)).then((Z)=>Z.createDoctorCommand($))),X("version",()=>Promise.resolve().then(() => (Eb(),kb)).then((Z)=>Z.createVersionCommand())),X("serve",()=>Promise.resolve().then(() => (Aw(),Cw)).then((Z)=>Z.createServeCommand())),X("wire",()=>Promise.resolve().then(() => (GW(),rq)).then((Z)=>Z.createWireCommand($))),X("unwire",()=>Promise.resolve().then(() => (GW(),rq)).then((Z)=>Z.createUnwireCommand())),X("statusline",()=>Promise.resolve().then(() => (ew(),tw)).then((Z)=>Z.createStatuslineCommand())),X("mcp",()=>Promise.resolve().then(() => (Ex(),kx)).then((Z)=>Z.createMcpCommand($)))}$X();v8();V9(E7);W9();function
|
|
9722
|
+
`);return await l3(G,Bun.stdin.stream(),(H)=>{process.stdout.write(H)}),{ok:!0,data:null}}}}var Dx;var Ix=v(()=>{v8();n0();kW();mF();h3();uF();kF();Dx="myc \u2014 this project's memory and tasks. Rules: start the session with myc_prime "+"and repeat it right after context compaction; take work with myc_ready{claim:true} "+"(one call \u2014 the task is yours, with all its context); before changing code, look "+"for context with myc_recall; write conclusions and decisions right away with myc_remember \u2014 "+"otherwise the next session won't know them. Ask the code tools about the code itself "+"instead of reading whole files: myc_code_map \u2014 orientation, myc_code_search and "+"myc_code_symbol \u2014 find, myc_skeleton \u2014 a file's API, myc_callers \u2014 blast radius "+"of an edit, myc_code_grep \u2014 every occurrence. WARN/degraded in an answer is not noise, "+"it means part of the system is down."});var kx={};s(kx,{toolsForProfile:()=>AW,toolDescriptionChars:()=>vF,serveStdio:()=>l3,resolveNode:()=>_4,profileDescriptionTokens:()=>zx,openMcpStore:()=>e9,mcpWorkspace:()=>cF,mcpQueries:()=>SF,mcpProjectDir:()=>pF,internalOpenDriver:()=>fF,findMcpWorkspace:()=>vW,estimateTokens:()=>EF,createMcpCommand:()=>_x,createDispatcher:()=>IW,WORK_TOOLS:()=>b3,UnknownToolError:()=>k4,McpServer:()=>zZ,MCP_PROTOCOL_VERSION:()=>hF,GRAFT_TOOLS_TOKENS:()=>Xx,DESCRIPTION_TOKEN_BUDGET:()=>$x,CODE_TOOLS:()=>w3,CODE_REF_KINDS:()=>IF,CODE_DESCRIPTION_TOKEN_BUDGET:()=>Zx,AGENT_TOOLS:()=>x3,AGENT_PROFILE_TOKEN_BUDGET:()=>Yx});var Ex=v(()=>{kF();kW();mF();Ix();uF();h3();h3()});function V9($){let X=(Z,Y)=>$.registerLazy(Z,Y);X("init",()=>Promise.resolve().then(() => (fL(),Tk)).then((Z)=>Z.createInitCommand())),X("models",()=>Promise.resolve().then(() => (Pk(),Ak)).then((Z)=>Z.modelsCommand)),X("model",()=>Promise.resolve().then(() => (BE(),LE)).then((Z)=>Z.modelCommand)),X("create",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createCreateCommand())),X("task",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createTaskCommand())),X("bug",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createBugCommand())),X("epic",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createEpicCommand())),X("msg",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createMsgCommand())),X("comment",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createCommentCommand())),X("update",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createUpdateCommand())),X("claim",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createClaimCommand())),X("release",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createReleaseCommand())),X("close",()=>Promise.resolve().then(() => (L8(),X6)).then((Z)=>Z.createCloseCommand())),X("move",()=>Promise.resolve().then(() => (rE(),sE)).then((Z)=>Z.createMoveCommand())),X("attempt",()=>Promise.resolve().then(() => (UK(),gB)).then((Z)=>Z.createAttemptCommand())),X("report",()=>Promise.resolve().then(() => (UK(),gB)).then((Z)=>Z.createReportCommand())),X("show",()=>Promise.resolve().then(() => (zv(),Yv)).then((Z)=>Z.createShowCommand())),X("list",()=>Promise.resolve().then(() => (Uv(),Jv)).then((Z)=>Z.createListCommand())),X("dep",()=>Promise.resolve().then(() => (mB(),Lv)).then((Z)=>Z.createDepCommand())),X("link",()=>Promise.resolve().then(() => (Fv(),qv)).then((Z)=>Z.createLinkCommand())),X("ready",()=>Promise.resolve().then(() => (HK(),pB)).then((Z)=>Z.createReadyCommand())),X("prime",()=>Promise.resolve().then(() => (Ev(),kv)).then((Z)=>Z.createPrimeCommand())),X("viz",()=>Promise.resolve().then(() => (yy(),vy)).then((Z)=>Z.createVizCommand())),X("export",()=>Promise.resolve().then(() => (CK(),gy)).then((Z)=>Z.createExportCommand())),X("import",()=>Promise.resolve().then(() => (wy(),by)).then((Z)=>Z.createImportCommand())),X("sync",()=>Promise.resolve().then(() => (my(),hy)).then((Z)=>Z.createSyncCommand())),X("import-beads",()=>Promise.resolve().then(() => (Tf(),Bf)).then((Z)=>Z.createImportBeadsCommand())),X("merge-driver",()=>Promise.resolve().then(() => (Ff(),qf)).then((Z)=>Z.createMergeDriverCommand())),X("bootstrap",()=>Promise.resolve().then(() => (df(),nf)).then((Z)=>Z.createBootstrapCommand())),X("remember",()=>Promise.resolve().then(() => (nT(),ef)).then((Z)=>Z.createRememberCommand())),X("recall",()=>Promise.resolve().then(() => (WS(),KS)).then((Z)=>Z.createRecallCommand())),X("search",()=>Promise.resolve().then(() => (NS(),QS)).then((Z)=>Z.createSearchCommand())),X("embedd",()=>Promise.resolve().then(() => (WL(),TI)).then((Z)=>Z.createEmbeddCommand())),X("reindex",()=>Promise.resolve().then(() => (CS(),OS)).then((Z)=>Z.createReindexCommand())),X("anchor",()=>Promise.resolve().then(() => (k6(),J9)).then((Z)=>Z.createAnchorCommand())),X("code",()=>Promise.resolve().then(() => (PY(),n_)).then((Z)=>Z.createCodeCommand())),X("callers",()=>Promise.resolve().then(() => (DS(),PS)).then((Z)=>Z.createCallersCommand())),X("skeleton",()=>Promise.resolve().then(() => (_S(),RS)).then((Z)=>Z.createSkeletonCommand())),X("absorb",()=>Promise.resolve().then(() => (aQ(),NM)).then((Z)=>Z.createAbsorbCommand())),X("absorb-session",()=>Promise.resolve().then(() => (oS(),dS)).then((Z)=>Z.createAbsorbSessionCommand())),X("review",()=>Promise.resolve().then(() => (Ug(),Jg)).then((Z)=>Z.createReviewCommand())),X("run",()=>Promise.resolve().then(() => (Aq(),Cq)).then((Z)=>Z.createRunCommand())),X("queue",()=>Promise.resolve().then(() => (Aq(),Cq)).then((Z)=>Z.createQueueCommand())),X("doctor",()=>Promise.resolve().then(() => (_b(),Rb)).then((Z)=>Z.createDoctorCommand($))),X("version",()=>Promise.resolve().then(() => (Eb(),kb)).then((Z)=>Z.createVersionCommand())),X("serve",()=>Promise.resolve().then(() => (Aw(),Cw)).then((Z)=>Z.createServeCommand())),X("wire",()=>Promise.resolve().then(() => (GW(),rq)).then((Z)=>Z.createWireCommand($))),X("unwire",()=>Promise.resolve().then(() => (GW(),rq)).then((Z)=>Z.createUnwireCommand())),X("statusline",()=>Promise.resolve().then(() => (ew(),tw)).then((Z)=>Z.createStatuslineCommand())),X("mcp",()=>Promise.resolve().then(() => (Ex(),kx)).then((Z)=>Z.createMcpCommand($)))}$X();v8();V9(E7);W9();function EY0(){EY(process.argv.slice(2),{tty:process.stdout.isTTY===!0,env:process.env}).then(OL)}EY0();
|