@maind-dev/cli 0.183.0 → 0.183.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.js +2 -2
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -282,7 +282,7 @@ maind: and re-run \`maind launch claude\`. (Or launch without routing: \`maind l
|
|
|
282
282
|
`,stderr:""}}let n=["maind: dry-run \u2014 nothing installed, written, or spawned.",`maind: config ${e.configPath} (${e.configSource})`,`maind: switchyard detected: ${e.switchyardDetected?"yes":"no"}`,`maind: would run: ${e.argv.join(" ")}`].join(`
|
|
283
283
|
`);return{stdout:e.toml??`(using existing config: ${e.configPath})
|
|
284
284
|
`,stderr:n+`
|
|
285
|
-
`}}a(RT,"renderDryRun");import{createRequire as $4}from"node:module";function T4(){return"0.183.
|
|
285
|
+
`}}a(RT,"renderDryRun");import{createRequire as $4}from"node:module";function T4(){return"0.183.1";try{return $4(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a(T4,"resolveVersion");var ue=T4();var L4=5e3;function Rt(e){process.stderr.write(`maind: ${e}
|
|
286
286
|
`)}a(Rt,"err");function F4(e){return e instanceof Error?e.message:String(e)}a(F4,"msg");var B4=new Set(["--config","--route","--mcp-url"]);function AT(e){let t=a(o=>{let i=e.indexOf(o);if(!(i===-1||i+1>=e.length))return e[i+1]},"get"),n=a(o=>e.includes(o),"has"),r=null;for(let o=0;o<e.length;o++){let i=e[o];if(i.startsWith("-")){B4.has(i)&&o++;continue}r=i;break}return{agent:r,dryRun:n("--dry-run"),config:t("--config")??null,route:t("--route")??fT,direct:n("--direct"),noFallback:n("--no-fallback"),noInstall:n("--no-install"),json:n("--json"),mcpUrl:t("--mcp-url")??null}}a(AT,"parseLaunchArgs");var U4={probe(e,t){let n=ET(e,t,{stdio:["ignore","pipe","pipe"],encoding:"utf8",timeout:1e4}),r=n.status===0&&!n.error,o=typeof n.stdout=="string"?n.stdout.trim():"";return{ok:r,stdout:o.length>0?o:null}},install(e){return ET("uv",[...e],{stdio:["ignore","inherit","inherit"]}).status},spawnInteractive(e){let t=Date.now();return new Promise(n=>{let r=!1,o=C4(e[0],e.slice(1),{stdio:"inherit",env:process.env}),i=a(()=>{},"onSigint"),s=a(d=>()=>{try{o.kill(d)}catch{}},"makeForward"),l=s("SIGTERM"),c=s("SIGHUP");process.on("SIGINT",i),process.on("SIGTERM",l),process.on("SIGHUP",c);let u=a(()=>{process.removeListener("SIGINT",i),process.removeListener("SIGTERM",l),process.removeListener("SIGHUP",c)},"cleanup");o.on("error",d=>{r||(r=!0,u(),n({code:null,signal:null,elapsedMs:Date.now()-t,spawnError:d.message}))}),o.on("exit",(d,f)=>{r||(r=!0,u(),n({code:d,signal:f,elapsedMs:Date.now()-t,spawnError:null}))})})},async fetchTemplate(e,t){let n;try{n=Re()}catch(r){if(r instanceof Ue)return null;throw r}try{let r=new Pe({apiKey:n.apiKey,deviceId:n.deviceId,clientVersion:ue,mcpUrl:e??void 0,projectKey:t}),o=new Promise(s=>{setTimeout(()=>s(null),L4).unref()}),i=r.callTool("get_template",{template_id:pT}).then(s=>typeof s.template_body=="string"&&s.template_body.trim().length>0?s.template_body:null).catch(()=>null);return await Promise.race([i,o])}catch{return null}},writeConfig(e,t){let n=P4(e);n&&n!=="."&&N4(n,{recursive:!0}),D4(e,t,"utf8")},readFile(e){try{return M4(e,"utf8")}catch{return null}},fileExists(e){return I4(e)},repoRoot(){try{let e=O4("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return e.length>0?e:null}catch{return null}},projectKey(){return lt().projectKey},userConfigDir(){return li()},homeDir(){return j4()},env:process.env,platform:process.platform};function H4(e,t){return e!==null?eb(e,".maind",qy):eb(t,qy)}a(H4,"resolveRoutesPath");async function $T(e,t=U4){let n=mT(e.agent);if(n.kind==="unknown")return Rt(`usage: maind launch <agent> [--dry-run] [--config <path>] [--route <name>] [--direct] [--no-fallback] [--no-install] \u2014 supported: ${Vy.join(", ")}`),2;if(n.kind==="planned")return Rt(`agent '${n.agent}' is planned but not yet supported \u2014 v1 supports: ${Vy.join(", ")}.`),2;if(e.json&&!e.dryRun)return Rt("--json is only valid together with --dry-run (stdout belongs to the agent session)."),2;let r=n.agent;if(e.direct)return Rt(ST()),TT(t,Jy(r));let o=hT(t.env);o.warning!==null&&Rt(o.warning);let i,s,l;if(e.config!==null){if(!t.fileExists(e.config))return Rt(`config not found: ${e.config}`),2;let f=t.readFile(e.config);if(f===null||bT(f,e.route)===null)return Rt(`config ${e.config} is not valid routes TOML with a [routes.${e.route}] entry.`),2;i=e.config,s=null,l="flag"}else{let f=await t.fetchTemplate(e.mcpUrl,t.projectKey()),p=f===null?null:yT(f,e.route);if(s=gT(e.route,o,p),p!==null)l="template";else{l="builtin";let m=f===null?"no curated template (offline, unauthenticated, or not published)":`curated template unusable (missing route '${e.route}', or it pins its own targets)`;Rt(`using builtin routing policy (${m}).`)}i=H4(t.repoRoot(),t.userConfigDir())}let c=cd,u=t.probe(cd,["--version"]).ok;if(e.dryRun){let f={agent:r,configPath:i,configSource:l,toml:s,argv:Xy(c,r,e.route,i),backendKind:o.kind,switchyardDetected:u},p=RT(f,e.json);return p.stderr.length>0&&process.stderr.write(p.stderr),process.stdout.write(p.stdout),0}if(!u){if(e.noInstall)return Rt(`switchyard not found (--no-install). Install it with:
|
|
287
287
|
maind: ${ud}`),1;if(!t.probe("uv",["--version"]).ok)return Rt(_T()),1;if(Rt(wT()),t.install(dT),t.probe(cd,["--version"]).ok)u=!0;else{let f=eb(t.homeDir(),".local","bin",t.platform==="win32"?"switchyard.exe":"switchyard");t.probe(f,["--version"]).ok&&(c=f,u=!0)}if(!u)return Qy(t,e,r,vT())}if(l!=="flag"&&s!==null)try{t.writeConfig(i,s)}catch(f){return Rt(`could not write ${i}: ${F4(f)}`),1}let d=await t.spawnInteractive(Xy(c,r,e.route,i));return d.spawnError!==null?Qy(t,e,r,`could not start switchyard (${d.spawnError})`):kT(d.code,d.signal,d.elapsedMs)==="fallback-eligible"?Qy(t,e,r,`switchyard exited with code ${d.code} after ${(d.elapsedMs/1e3).toFixed(1)}s`):Zy(d.code,d.signal)}a($T,"runLaunch");async function Qy(e,t,n,r){return t.noFallback?(Rt(`${r} (--no-fallback set \u2014 not degrading to a direct spawn).`),1):(process.stderr.write(xT(r)+`
|
|
288
288
|
`),TT(e,Jy(n)))}a(Qy,"degradeOrFail");async function TT(e,t){let n=await e.spawnInteractive(t);return n.spawnError!==null?(Rt(`'${t[0]}' not found on PATH \u2014 install the agent CLI first (${n.spawnError}).`),1):Zy(n.code,n.signal)}a(TT,"spawnAndPropagate");var tb="tests:";function dd(e){if(!e)return null;let t=e.indexOf("=");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();return!n||!r?null:{gate:n,object:r}}a(dd,"parseOverride");function G4(e){return e==="open"||e==="warn"}a(G4,"objectCarriesOverride");async function fd(e,t,n){let r=[];for(let i of e)!t.has(i.gate)&&!i.gate.startsWith(tb)&&r.push(`--override ${i.gate}: not a gate declared in .maind/gates.json \u2014 only declared gates and test suites (tests:<dir>) take an override`+(t.size>0?` (declared: ${[...t].join(", ")})`:""));let o=new Map;for(let i of new Set(e.map(s=>s.object))){let s=null;try{s=await n(i)}catch{s=null}let l=s?.key??i;s===null?r.push(`--override \u2026=${i}: the object could not be resolved \u2014 no override without proof that it is open`):G4(s.status)?o.set(i,s):r.push(`--override \u2026=${l}: the object is ${s.status} \u2014 it no longer tracks a red gate`)}return r.length>0?{kind:"refused",lines:r}:{kind:"ok",resolved:o}}a(fd,"checkOverrides");function CT(e,t,n){let r=new Map(t.map(c=>[c.gate,c])),o=[],i=e.map(c=>{let u=r.get(c.id);if(!u)return c;let d=n.get(u.object);return!d||c.verdict!=="fail"||!c.blocking?c:(o.push({gate:c.id,object:d}),{...c,blocking:!1,note:`red, accepted \u2014 tracked by ${d.key??d.id}`})}),s=new Set(o.map(c=>c.gate)),l=t.filter(c=>!s.has(c.gate)).map(c=>({gate:c.gate,verdict:e.find(u=>u.id===c.gate)?.verdict??"absent"}));return{results:i,used:o,unused:l}}a(CT,"applyOverrides");function OT(e){return e.map(t=>t.verdict==="absent"?`--override ${t.gate}: the gate did not run \u2014 nothing was accepted`:`--override ${t.gate}: the gate is ${t.verdict==="pass"?"green":t.verdict}, not red \u2014 nothing was accepted, nothing recorded`)}a(OT,"unusedOverrideLines");var pd=["squash","merge","rebase"];function md(e){return typeof e=="string"&&pd.includes(e)}a(md,"isMergeMethod");function IT(e){if(typeof e!="object"||e===null)return null;let t=e,n=[[t.allow_squash_merge,"squash"],[t.allow_merge_commit,"merge"],[t.allow_rebase_merge,"rebase"]];return n.some(([r])=>typeof r!="boolean")?null:{allowed:n.filter(([r])=>r===!0).map(([,r])=>r),preferred:null}}a(IT,"githubMergeMethods");function NT(e){if(typeof e!="object"||e===null)return null;let t=e,n=t.merge_method,r=t.squash_option;if(n!=="merge"&&n!=="rebase_merge"&&n!=="ff")return null;let o=n==="ff"?"rebase":"merge";switch(r){case"always":return{allowed:["squash"],preferred:"squash"};case"never":return{allowed:[o],preferred:o};case"default_on":return{allowed:["squash",o],preferred:"squash"};case"default_off":return{allowed:["squash",o],preferred:o};default:return null}}a(NT,"gitlabMergeMethods");function nb(e){let{flag:t,configured:n,forge:r}=e,o=t??n;if(o){let s=t?"flag":"config";return r&&!r.allowed.includes(o)?{kind:"not-allowed",method:o,source:s,allowed:r.allowed}:{kind:"ok",method:o,source:s}}if(r?.preferred&&r.allowed.includes(r.preferred))return{kind:"ok",method:r.preferred,source:"forge"};let i=r?pd.find(s=>r.allowed.includes(s)):void 0;return i&&i!=="squash"?{kind:"ok",method:i,source:"forge"}:{kind:"ok",method:"squash",source:"default"}}a(nb,"chooseMergeMethod");var K4={squash:"squash",merge:"merge commit",rebase:"rebase"};function Bi(e){return K4[e]}a(Bi,"methodLabel");function rb(e){let t={flag:"--merge-method",config:"mergeMethod in .maind/feature.json",forge:"the forge's setting for this repository",default:"the default"};return`merges with ${Bi(e.method)} (${t[e.source]})`}a(rb,"methodLine");function ob(e){let t=e.source==="flag"?"--merge-method":"mergeMethod in .maind/feature.json",n=e.allowed.length>0?e.allowed.map(Bi).join(", "):"none";return[`${t} asks for ${Bi(e.method)}, and this repository's forge does not allow it (allowed: ${n}).`,"Nothing ran and nothing was merged."]}a(ob,"notAllowedLines");function hd(e){let t=e.merges.map(n=>n.slice(0,9)).join(", ");return[`a rebase merge replays every commit of ${e.branch} onto ${e.baseRef}, and ${e.branch} carries merge commits since ${e.baseRef} (${t})`+(e.ownBaseMerge?` \u2014 one of them is promote bringing ${e.baseRef} in before it assigns a number.`:"."),"How the forge rebases a merge commit is not documented, so promote does not hand it one. Nothing was pushed or merged.",` merge with --merge-method squash or --merge-method merge, or rebase ${e.branch} onto ${e.baseRef} yourself and push (the new head needs a new approval).`]}a(hd,"rebaseMergeCommitLines");import{readFileSync as nC}from"node:fs";import{join as rC}from"node:path";import{spawn as W4,spawnSync as q4}from"node:child_process";function ib(e){return e==="work"||e==="always"||e==="off"}a(ib,"isStayAwakeSetting");function V4(e,t){if(e.CI||e.NODE_TEST_CONTEXT)return"off";let n=e.MAIND_STAY_AWAKE?.trim().toLowerCase();return ib(n)?n:t??"work"}a(V4,"resolveStayAwake");function Y4(e,t,n,r){return e==="darwin"?r("caffeinate")?{cmd:"caffeinate",args:["-i","-w",String(t)]}:null:e==="linux"&&r("systemd-inhibit")&&r("tail")?{cmd:"systemd-inhibit",args:["--what=idle","--who=maind",`--why=${n}`,"--mode=block","tail",`--pid=${t}`,"-f","/dev/null"]}:null}a(Y4,"inhibitCommand");function z4(e,t,n){let r=null,o=a(()=>{if(e==="off"||r!==null)return;let s=Y4(n.platform,n.pid,t,n.has);s!==null&&(r=n.start(s.cmd,s.args))},"hold"),i=a(()=>{if(r!==null){try{r()}catch{}r=null}},"release");return{work:o,waiting:a(()=>{e!=="always"&&i()},"waiting"),end:i,holding:a(()=>r!==null,"holding")}}a(z4,"makeAwake");function X4(e){try{return q4("sh",["-c",`command -v ${e}`],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}a(X4,"hasBinary");var J4={platform:process.platform,pid:process.pid,has:X4,start:a((e,t)=>{try{let n=W4(e,[...t],{stdio:"ignore"});return n.on("error",()=>{}),n.unref(),typeof n.pid=="number"?()=>n.kill():null}catch{return null}},"start")},Po=null;function gd(e,t,n={}){let r=Po===null;return r&&(Po=z4(V4(n.env??process.env,e),t,n.deps??J4)),Po.work(),{end:a(()=>{r&&(Po?.end(),Po=null)},"end")}}a(gd,"beginAwake");function MT(){Po?.work()}a(MT,"awakeWork");function DT(){Po?.waiting()}a(DT,"awakeWaiting");import{execFileSync as oz}from"node:child_process";import{realpathSync as iz}from"node:fs";function yd(e,t){if(!e.ok)return{kind:"unchecked",reason:e.reason};let n=t.toLowerCase(),r=e.refs.find(o=>o.unresolved!==!0&&o.id?.toLowerCase()===n);return r===void 0?{kind:"unchecked",reason:"the server did not resolve the bound object"}:typeof r.hasPlan!="boolean"?{kind:"unchecked",reason:"the server does not report has_plan"}:r.hasPlan?{kind:"attached"}:{kind:"absent"}}a(yd,"serverPlanAnswer");var Wa="MAIND_GATE_OBJECT_REASON",Z4=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function Q4(e){if(e===null)return!1;let t=e.trim();return t.length<4?!1:!["1","true","yes","on","skip"].includes(t.toLowerCase())}a(Q4,"isReason");function bd(e){let t=ez(e);return t.kind!=="linked"&&Q4(e.overrideReason)?{kind:"overridden",reason:e.overrideReason.trim()}:t}a(bd,"classifyWorkObject");function ez(e){if(e.branch===null)return{kind:"detached"};let t=e.objectId?.trim()??"";return t.length===0?{kind:"missing",branch:e.branch}:Z4.test(t)?{kind:"linked",objectId:t,objectKey:e.objectKey?.trim()||null,planRevision:e.planRevision?.trim()||null}:{kind:"malformed",branch:e.branch,value:t}}a(ez,"judge");function kd(e){return e.kind==="linked"||e.kind==="overridden"}a(kd,"workObjectPasses");function jT(e,t,n){let r=a(o=>[" Link it, or say why not:",` git config branch.${o}.maindObject <object-uuid>`,` ${t}="<reason>" maind gate`],"fix");switch(e.kind){case"linked":{let o=`work object: ${e.objectKey?`${e.objectKey} \u2014 `:""}${e.objectId}`;if(e.planRevision)return[o,` plan attached (rev ${e.planRevision})`];let i=` maind object plan --object ${e.objectId} --file <plan.md>`,s=n??{kind:"unchecked",reason:"the server was not asked"};switch(s.kind){case"attached":return[o," plan attached (server)"];case"absent":return[o," no plan attached \u2014 advisory, never a failure. Attach the accepted plan:",i];case"unchecked":return[o,` plan not checked (${s.reason}) \u2014 no local marker; advisory, never a failure. If none is attached:`,i]}}case"overridden":return[`work object check overridden \u2014 reason: ${e.reason}`];case"missing":return[`branch ${e.branch} has no linked work object.`,...r(e.branch)];case"malformed":return[`branch ${e.branch}: "${e.value}" is not an object id.`," The check reads the id, never the display key \u2014 a key can be renamed, an id cannot.",...r(e.branch)];case"detached":return["detached HEAD \u2014 this check needs a branch to read the link from."]}}a(jT,"workObjectLines");function sb(e){return`${e.dir}\0${e.check??""}`}a(sb,"checkKey");function PT(e){return`${e.replace(/[/\\]+$/,"")}-apply`}a(PT,"applyCheckoutPath");function LT(e){return[...new Set(e.filter(t=>t.command!==null).map(t=>t.trigger))].sort()}a(LT,"applyTriggers");function st(e){return/^[A-Za-z0-9_./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}a(st,"shellQuote");function tz(e,t){let n=t.replace(/^\/+|\/+$/g,"");return n.length===0?e:`${e.replace(/\/+$/,"")}/${n}`}a(tz,"joinAbs");function nz(e){return e.endsWith("/")?e:`${e}/`}a(nz,"withPrefix");function rz(e){let t=new Set;for(let r of e){let o=/^((?:[^/]+\/)*?)supabase\/(?:migrations|functions)\//.exec(r);o&&t.add(o[1])}let n=[];for(let r of[...t].sort()){let o=r.replace(/\/$/,"");n.push({when:`${r}supabase/migrations/`,run:"supabase db push",check:"supabase migration list",cwd:o}),n.push({when:`${r}supabase/functions/`,run:"supabase functions deploy {name}",check:"supabase functions list",cwd:o,each:"dir"})}return n}a(rz,"defaultPostMergeSteps");function ab(e,t,n){let r=e.map(s=>s.trim()).filter(s=>s.length>0),o=t??rz(r),i=[];for(let s of o){let l=nz(s.when),c=r.filter(h=>h.startsWith(l));if(c.length===0)continue;let u=tz(n,s.cwd??""),d=`cd ${st(u)} && `,f=a((h,g)=>h===void 0?void 0:h.split("{name}").join(g),"fill");if(s.each!=="dir"){i.push({reason:`${c.length} file(s) under ${l}`+(s.note?` \u2014 ${s.note}`:""),command:s.run?d+s.run:null,trigger:l,dir:u,check:s.run&&s.check?s.check:null});continue}let p=[...new Set(c.map(h=>h.slice(l.length).split("/")[0]).filter(h=>h.length>0))].sort();for(let h of p.filter(g=>!g.startsWith("_"))){let g=f(s.note,h),b=f(s.run,h),k=f(s.check,h);i.push({reason:`${l}${h}/ changed`+(g?` \u2014 ${g}`:""),command:b?d+b:null,trigger:l,dir:u,check:b&&k?k:null})}let m=p.filter(h=>h.startsWith("_"));m.length>0&&i.push({reason:`${m.map(h=>`${l}${h}/`).join(", ")} changed \u2014 shared code, no target of its own: redeploy what imports it`,command:null,trigger:l,dir:u,check:null})}return i}a(ab,"postMergeActions");function FT(e,t,n={}){if(e.length===0)return[];let r=[],o=n.target??{kind:"main"},i=n.mainRoot??"the main checkout",s=n.ref??t;o.kind==="prepared"?(r.push(`the main checkout (${i}) does not hold the merged ${o.stale.join(", ")} \u2014 it is behind ${s} or changed locally, so the steps run in ${o.path} (detached at ${s}${o.reused?", reused":""}${o.provisioned>0?`, ${o.provisioned} declared path(s) provisioned from .maind/worktree-requirements`:""}).`),o.installFailed&&r.push(" postCreate failed there \u2014 a command that needs the install will fail until it runs."),r.push(` remove it when done: git -C ${st(i)} worktree remove ${st(o.path)}`)):o.kind==="unavailable"&&(r.push(`the main checkout (${i}) does not hold the merged ${o.stale.join(", ")}, and no apply checkout could be prepared at ${o.path}: ${o.reason}.`),r.push(` the commands below run against a stale tree until it is at ${s} \u2014 bring it there first.`)),r.push(`the merge on ${t} needs steps it did not run \u2014 they are yours (nothing was executed):`);for(let l of e){if(r.push(` \u2022 ${l.reason}`),!l.command)continue;let c=l.check?n.checks?.get(sb(l)):void 0;if(c&&!c.ok){r.push(` \u2716 check failed (${c.exit===null?"did not finish":`exit ${c.exit}`}): ${l.check}`);for(let u of c.tail)r.push(` | ${u}`);r.push(" the command fails the same way until that is fixed \u2014 then:")}else c&&r.push(` \u2713 checked: ${l.check}`);r.push(` ${l.command}`)}return r}a(FT,"postMergeLines");function qa(e,t){let n=e!==null&&e.trim().length>0;return t==="closes"?{kind:"decided",completes:!0}:t==="progress"?{kind:"decided",completes:!1}:n?{kind:"missing",objectId:e.trim()}:{kind:"decided",completes:!1}}a(qa,"decideCompletion");function BT(e,t){return[`${e} is bound to work object ${t}, and the merge will be reported there.`,"Does this pull request FINISH that object? Say so \u2014 neither answer is assumed:"," --closes-object it does: the merge is reported as completion"," --progress-only one step of several: the merge is logged, the object stays open","Nothing was merged."]}a(BT,"missingCompletionLines");function lb(e){if(!e.required)return null;let t=bd({branch:e.branch,objectId:e.boundObject,objectKey:null,overrideReason:e.overrideReason,planRevision:null});return kd(t)?null:[`${e.branch} has no linked work object, and this repository's gates require one (requireWorkObject, ADR-286).`,"The gate would refuse it at the very end \u2014 so it was not started. Either:"," bind it: maind object bind --object <uuid>",` or say why not: ${Ui}="<reason>" ${e.promoteCommand} --yes`,"Nothing was merged."]}a(lb,"unboundObjectLines");var Ui=Wa;function sn(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)}a(sn,"cwdInside");function Et(e,t){return`cd ${st(e)} && ${t}`}a(Et,"cleanupCommand");function UT(e){let t=[`PR #${e.prNumber} is already merged${e.mergedOn?` (${e.mergedOn})`:""} \u2014 nothing to promote.`];return e.leftover&&t.push("the worktree or local branch is still there \u2014 clean up:",` ${e.cleanup}`),t}a(UT,"alreadyMergedLines");function HT(e){return[`this process runs inside ${e.worktree} \u2014 removing it would pull the directory out from under the calling shell. Nothing was removed. Run it from the main checkout:`,` ${e.cleanup}`]}a(HT,"doneInsideLines");function GT(e){return[`the worktree stays for now \u2014 this process runs inside ${e.worktree}. A background run removes it once nothing stands in it any more (at the latest when this session ends), after the same checks as done (merge proven, no local changes). Its log: ${e.log}`]}a(GT,"deferredCleanupLines");function KT(e){return[`the worktree was kept \u2014 this process runs inside ${e.worktree}, and removing it would pull the directory out from under the calling shell. Clean up from the main checkout:`,` ${Et(e.mainRoot,e.doneCommand)}`,` or, later, for every merged worktree at once: ${Et(e.mainRoot,"maind feature done --merged")}`]}a(KT,"keptWorktreeLines");async function cb(e,t){if(e!==null&&e.trim().length>0)return{kind:"bound",objectId:e.trim()};let n=t.prNumber(),r=t.slug();if(n===null||r===null)return{kind:"unbound"};let o=t.ref(r,n),i=null;try{i=await t.lookup(o)}catch{i=null}return i===null?{kind:"unbound"}:(t.write(i.id,i.key),{kind:"recovered",objectId:i.id,key:i.key,ref:o})}a(cb,"recoverBinding");async function Va(e,t){let n=t.prNumber(),r=t.slug();if(n===null||r===null)return{kind:"no-pr"};let o=t.ref(r,n),i=null;try{i=await t.lookup(o)}catch{i=null}if(i!==null)return i.id===e?{kind:"already",ref:o}:{kind:"mismatch",ref:o,other:i};await t.link(e,o);let s=null;try{s=await t.lookup(o)}catch{s=null}return s!==null&&s.id!==e?{kind:"mismatch",ref:o,other:s}:{kind:"link-attempted",ref:o}}a(Va,"ensurePrLinked");function Hi(e){let t=e.bound.key??e.bound.id,n=e.other.key??e.other.id,r=e.prNumber!==null?`PR #${e.prNumber}`:e.ref;return[`${e.branch} is bound to ${t}, but ${r} is linked to ${n} \u2014 the merge would be reported against the wrong object.`,e.phase==="ship"?"the branch is pushed and the pull request is open; promote will refuse it until this is settled.":"Nothing was merged.",` if the work belongs to ${n}: maind object bind --object ${e.other.id}`,` if it belongs to ${t}: the link is wrong \u2014 a person removes it on ${n}'s object page (the connector does not re-create a removed link), then ship again to link ${t}; retitle the pull request if its title names ${n}.`]}a(Hi,"linkMismatchLines");function WT(e,t){let n=t?.trim().toUpperCase()??null;return e.filter(r=>r.toUpperCase()!==n)}a(WT,"fanOutKeys");function qT(e,t){let n=st(t.mainRoot);switch(e.kind){case"done":{let r=e.cleared??[];return r.length===0?{suffix:`, ${t.base} fast-forwarded`,extra:[]}:{suffix:`, ${t.base} fast-forwarded`,extra:[` ${r.length} uncommitted file(s) in the main checkout already held exactly what the merge brings (${Su(r,5)}) \u2014 they stood in the way of the pull and now come from ${t.ref}. Nothing was lost.`]}}case"not-on-base":return{suffix:`, ${t.base} NOT fast-forwarded \u2014 the main checkout is on ${e.branch??"a detached HEAD"}, and promote does not switch it`,extra:[]};case"blocked":return{suffix:`, ${t.base} NOT fast-forwarded \u2014 uncommitted work in the main checkout overlaps ${e.files.length} file(s) of the merge`,extra:[` ${Su(e.files,5)}`,` usually a parallel session's work \u2014 theirs to commit or set aside, not promote's. Until then read the merged state with: git -C ${n} show ${t.ref}:<path> \u2014 the pull goes through once nothing overlaps.`,` ${e.landed!==void 0&&e.landed>0?`${e.landed} of them already hold exactly what the merge brings; the rest differ. `:""}What is left over rather than in progress: cd ${n} && maind feature unblock-main \u2014 it lists each file and changes nothing; with --yes it parks them in a backup ref and pulls.`]};case"failed":return{suffix:`, ${t.base} NOT fast-forwarded \u2014 git pull --ff-only refused in the main checkout (git -C ${n} status shows why)`,extra:[]}}}a(qT,"fastForwardLines");function sz(e){let t=[],n=null,r="";for(let o of e.split(`
|
|
@@ -576,7 +576,7 @@ ${n}
|
|
|
576
576
|
`)}clearProgress(){this.transient&&(this.transient=!1,this.write("\r\x1B[2K"))}progress(t){if(!this.live)return;this.clearProgress();let n=t.length>this.width-6?`${t.slice(0,this.width-7)}\u2026`:t;this.write(`${Fl}${this.style.dim(`\u2026 ${n}`)}`),this.transient=!0}gateFailure(t,n){this.gateFailures.set(t,n)}gate(t,n,r){this.open("Gate");let o=t.some(c=>c.verdict==="fail"&&c.blocking);this.row(o?"fail":r?"warn":"ok","",n);for(let c of t.filter(u=>u.verdict==="fail")){c.blocking?this.row("fail",c.id,c.note??""):this.row("warn",c.id,`failed, reported \u2014 non-blocking; ship and promote may continue.${c.note?` ${c.note}`:""}`);let u=dl(c);u.length>0&&this.output(u.join(`
|
|
577
577
|
`));let d=this.gateFailures.get(c.id);d&&this.output(d)}let i=t.filter(c=>c.verdict==="pass").map(c=>c.id);i.length>0&&this.row("ok",`${i.length} passed`,i.join(", "),!0);let s=new Set(Xd(t).map(c=>c.id));s.size>0&&this.row("note","not checked",`${[...s].join(", ")} \u2014 ${Jd}`);let l=new Map;for(let c of t.filter(u=>u.verdict==="not-checked"&&!s.has(u.id))){let u=c.note??"not checked";l.set(u,[...l.get(u)??[],c.id])}for(let[c,u]of l)this.row("note","not checked",`${u.join(", ")} \u2014 ${c}`);r&&this.row("note","","warning only \u2014 no blocking gate failed; ship and promote may continue.")}output(t){let n=t.split(`
|
|
578
578
|
`).filter(i=>i.trim()!==""),r=n.slice(-20),o=`${Fl} `;n.length>r.length&&this.line(`${o}${this.style.dim(`\u2026 ${n.length-r.length} earlier line(s)`)}`);for(let i of r)this.line(`${o}${this.style.dim("\u2502")} ${i}`)}callout(t,n,r){let o=this.style,i=t==="ok"?o.green:t==="warn"?o.yellow:o.red,s=` ${i("\u2503")} `;this.section=null,this.lastName=null,this.pendingTitle=null,this.line(),this.line(`${s}${o.bold(i(n))}`);for(let l of r)if("command"in l)this.line(`${s}${o.accent(l.command)}`);else if("link"in l)this.line(`${s}${o.bold(o.accent(`\u2192 ${o.link(l.link)}`))}`);else if("pre"in l)this.line(`${s}${l.pre}`);else for(let c of Ll(l.text,Math.max(24,this.width-4)))this.line(`${s}${c}`)}symbol(t){let n=this.style;switch(t){case"ok":return n.green("\u2713");case"fail":return n.red("\u2717");case"warn":return n.yellow("!");default:return n.dim("\xB7")}}header(t,n,r="maind feature ship"){this.clearProgress();let o=this.style;this.line(),this.line(`${o.bold(r)} ${o.accent(t)} ${o.dim("\u2192")} ${n}`)}open(t,n=""){this.section!==t&&(this.section=t,this.lastName=null,this.pendingTitle=` ${this.style.bold(t)}${n?` ${this.style.dim(n)}`:""}`)}row(t,n,r="",o=!1){let i=this.style,s=n!==""&&n===this.lastName;this.lastName=n===""?null:n;let l=n===""?"":(s?"":n).padEnd(Math.max(GD,n.length+1)),c=`${Fl}${this.symbol(t)} `,u=" ".repeat(Fl.length+2+(n===""?0:Math.max(GD,l.length))),{prose:d,command:f}=HD(r),p=Math.max(24,this.width-u.length),m=d===""?[]:Ll(d,p),h=m.shift()??"",g=t==="note"||o?i.dim:b=>b;this.line(`${c}${n===""?"":i.bold(l)}${g(h)}`.trimEnd());for(let b of m)this.line(`${u}${g(b)}`);f&&this.line(`${u}${i.accent(f)}`)}checkLine(t){let n=UZ(t);n?this.row(n.mark,n.name,n.detail):this.text(t)}text(t,n){if(n){this.row(n,"",t);return}let r=/^\s*/.exec(t)[0],o=`${Fl} ${r}`;if(HZ(t.trim())){this.line(`${o}${this.style.accent(t.trim())}`);return}let{prose:i,command:s}=HD(t.trim());for(let l of Ll(i,Math.max(24,this.width-o.length)))this.line(`${o}${l}`);s&&this.line(`${o}${this.style.accent(s)}`)}objectOutput(t,n){for(let r of t.split(`
|
|
579
|
-
`)){let o=r.replace(/^maind:\s*/,"").trim();if(o==="")continue;let i=n!=="unknown"&&n!==0,s=/\bHTTP [45]\d\d\b|\berror\b|could not|\bfailed\b/i.test(o);this.text(o,i||s?"warn":n==="unknown"?"note":"ok")}}say(t){t.trim()!==""&&(/^\s/.test(t)?this.text(t):this.text(t,"note"))}approval(t){let n=this.style,r="Your approval",o=`\u2192 ${t.url}`,i=t.lines??[`Merge approval requested for PR #${t.prNumber} at ${t.shortSha}.`,'Approve it in a browser session \u2014 it waits under "Waiting on you".'],s=this.width-2-4,l=Math.max(o.length,Math.min(s,Math.max(...i.map(p=>p.length)))),c=i.flatMap(p=>Ll(p,l)),u=l+4,d=a(p=>n.accent(p),"edge"),f=a(p=>{let m=" ".repeat(Math.max(0,l-UD(p)));return` ${d("\u2502")} ${p}${m} ${d("\u2502")}`},"pad");this.section=null,this.lastName=null,this.pendingTitle=null,this.line(),this.line(` ${d("\u256D\u2500 ")}${n.bold(r)} ${d(`${"\u2500".repeat(Math.max(0,u-r.length-3))}\u256E`)}`),this.line(f("")),this.line(f(n.bold(n.accent(`\u2192 ${n.link(t.url)}`)))),this.line(f(""));for(let p of c)this.line(f(p));this.line(` ${d(`\u2570${"\u2500".repeat(u)}\u256F`)}`)}next(t,n){let r=this.style;this.section=null,this.lastName=null,this.pendingTitle=null,this.line(),this.line(` ${r.bold("Next")} ${r.accent(t)}`);for(let o of Ll(n,Math.max(24,this.width-7)))this.line(` ${r.dim(o)}`)}stop(t){this.section=null,this.lastName=null,this.pendingTitle=null,this.line(),this.row("fail","",t)}};import{execFileSync as WZ}from"node:child_process";var qZ=6e4;function gs(e,t){let n=t.intervalMs??qZ,r=t.checkedBase,o=null;return()=>{let i=e.now();if(o!==null&&i-o<n||(o=i,!e.fetch()))return null;let s=e.baseTip();if(s===null||s===r)return null;let l=e.conflict();return l===null?null:(r=s,l.length>0?l:null)}}a(gs,"makeBaseWatch");function WD(e,t,n=6e4){try{return WZ("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:n}).trim()}catch{return null}}a(WD,"git");function yw(e,t,n){return WD(e,["rev-parse","--verify","--quiet",`${t}/${n}^{commit}`])}a(yw,"baseTipOf");function ys(e,t,n,r,o){return{fetch:a(()=>WD(e,["fetch","--quiet",t,n],12e4)!==null,"fetch"),baseTip:a(()=>yw(e,t,n),"baseTip"),conflict:a(()=>{let i=Yo(e,`${t}/${n}`,{verdict:Ld(e,`${t}/${n}`,r,o),ownOnly:[]}).verdict;return i.kind==="conflict"?i.files:i.kind==="clean"?[]:null},"conflict"),now:a(()=>Date.now(),"now")}}a(ys,"gitBaseWatchDeps");import{spawn as VZ}from"node:child_process";import{execFileSync as YZ}from"node:child_process";import{mkdirSync as zZ,openSync as XZ,readFileSync as JZ,rmSync as ZZ,writeFileSync as QZ}from"node:fs";import{isAbsolute as e7,join as t7,resolve as bw}from"node:path";var n7="maind-approval-watch.json",r7=6e4,o7=5*6e4,i7=24*60*6e4,s7=5*6e4;function qD(e,t){try{return YZ("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:6e4}).trim()}catch{return null}}a(qD,"git");function kw(e){let t=qD(e,["rev-parse","--git-path",n7]);return t?e7(t)?t:bw(e,t):null}a(kw,"markPath");var a7=/^[0-9a-f]{40}$|^[0-9a-f]{64}$/;function l7(e){try{let t=JSON.parse(e),n=typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0?t.pid:null,r=typeof t.head=="string"&&a7.test(t.head)?t.head:null,o=t.by==="watch"||t.by==="promote"?t.by:null,i=typeof t.startedAt=="string"?t.startedAt:null,s=typeof t.seenAt=="string"?t.seenAt:null;return t.v!==1||n===null||!r||!o||!i||!s?null:{v:1,pid:n,head:r,by:o,startedAt:i,seenAt:s}}catch{return null}}a(l7,"parseWatchMark");function pn(e){let t=kw(e);if(!t)return null;try{return l7(JZ(t,"utf8"))}catch{return null}}a(pn,"readWatch");function bs(e,t,n=Date.now()){let r=kw(e);if(!r)return!1;let o=pn(e),i=new Date(n).toISOString(),s={v:1,pid:t.pid,head:t.head,by:t.by,startedAt:o&&o.pid===t.pid&&o.head===t.head?o.startedAt:i,seenAt:i};try{return QZ(r,`${JSON.stringify(s)}
|
|
579
|
+
`)){let o=r.replace(/^maind:\s*/,"").trim();if(o==="")continue;let i=n!=="unknown"&&n!==0,s=/\bHTTP [45]\d\d\b|\berror\b|could not|\bfailed\b|\bnot (?:recorded|proposed)\b/i.test(o);this.text(o,i||s?"warn":n==="unknown"?"note":"ok")}}say(t){t.trim()!==""&&(/^\s/.test(t)?this.text(t):this.text(t,"note"))}approval(t){let n=this.style,r="Your approval",o=`\u2192 ${t.url}`,i=t.lines??[`Merge approval requested for PR #${t.prNumber} at ${t.shortSha}.`,'Approve it in a browser session \u2014 it waits under "Waiting on you".'],s=this.width-2-4,l=Math.max(o.length,Math.min(s,Math.max(...i.map(p=>p.length)))),c=i.flatMap(p=>Ll(p,l)),u=l+4,d=a(p=>n.accent(p),"edge"),f=a(p=>{let m=" ".repeat(Math.max(0,l-UD(p)));return` ${d("\u2502")} ${p}${m} ${d("\u2502")}`},"pad");this.section=null,this.lastName=null,this.pendingTitle=null,this.line(),this.line(` ${d("\u256D\u2500 ")}${n.bold(r)} ${d(`${"\u2500".repeat(Math.max(0,u-r.length-3))}\u256E`)}`),this.line(f("")),this.line(f(n.bold(n.accent(`\u2192 ${n.link(t.url)}`)))),this.line(f(""));for(let p of c)this.line(f(p));this.line(` ${d(`\u2570${"\u2500".repeat(u)}\u256F`)}`)}next(t,n){let r=this.style;this.section=null,this.lastName=null,this.pendingTitle=null,this.line(),this.line(` ${r.bold("Next")} ${r.accent(t)}`);for(let o of Ll(n,Math.max(24,this.width-7)))this.line(` ${r.dim(o)}`)}stop(t){this.section=null,this.lastName=null,this.pendingTitle=null,this.line(),this.row("fail","",t)}};import{execFileSync as WZ}from"node:child_process";var qZ=6e4;function gs(e,t){let n=t.intervalMs??qZ,r=t.checkedBase,o=null;return()=>{let i=e.now();if(o!==null&&i-o<n||(o=i,!e.fetch()))return null;let s=e.baseTip();if(s===null||s===r)return null;let l=e.conflict();return l===null?null:(r=s,l.length>0?l:null)}}a(gs,"makeBaseWatch");function WD(e,t,n=6e4){try{return WZ("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:n}).trim()}catch{return null}}a(WD,"git");function yw(e,t,n){return WD(e,["rev-parse","--verify","--quiet",`${t}/${n}^{commit}`])}a(yw,"baseTipOf");function ys(e,t,n,r,o){return{fetch:a(()=>WD(e,["fetch","--quiet",t,n],12e4)!==null,"fetch"),baseTip:a(()=>yw(e,t,n),"baseTip"),conflict:a(()=>{let i=Yo(e,`${t}/${n}`,{verdict:Ld(e,`${t}/${n}`,r,o),ownOnly:[]}).verdict;return i.kind==="conflict"?i.files:i.kind==="clean"?[]:null},"conflict"),now:a(()=>Date.now(),"now")}}a(ys,"gitBaseWatchDeps");import{spawn as VZ}from"node:child_process";import{execFileSync as YZ}from"node:child_process";import{mkdirSync as zZ,openSync as XZ,readFileSync as JZ,rmSync as ZZ,writeFileSync as QZ}from"node:fs";import{isAbsolute as e7,join as t7,resolve as bw}from"node:path";var n7="maind-approval-watch.json",r7=6e4,o7=5*6e4,i7=24*60*6e4,s7=5*6e4;function qD(e,t){try{return YZ("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:6e4}).trim()}catch{return null}}a(qD,"git");function kw(e){let t=qD(e,["rev-parse","--git-path",n7]);return t?e7(t)?t:bw(e,t):null}a(kw,"markPath");var a7=/^[0-9a-f]{40}$|^[0-9a-f]{64}$/;function l7(e){try{let t=JSON.parse(e),n=typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0?t.pid:null,r=typeof t.head=="string"&&a7.test(t.head)?t.head:null,o=t.by==="watch"||t.by==="promote"?t.by:null,i=typeof t.startedAt=="string"?t.startedAt:null,s=typeof t.seenAt=="string"?t.seenAt:null;return t.v!==1||n===null||!r||!o||!i||!s?null:{v:1,pid:n,head:r,by:o,startedAt:i,seenAt:s}}catch{return null}}a(l7,"parseWatchMark");function pn(e){let t=kw(e);if(!t)return null;try{return l7(JZ(t,"utf8"))}catch{return null}}a(pn,"readWatch");function bs(e,t,n=Date.now()){let r=kw(e);if(!r)return!1;let o=pn(e),i=new Date(n).toISOString(),s={v:1,pid:t.pid,head:t.head,by:t.by,startedAt:o&&o.pid===t.pid&&o.head===t.head?o.startedAt:i,seenAt:i};try{return QZ(r,`${JSON.stringify(s)}
|
|
580
580
|
`),!0}catch{return!1}}a(bs,"claimWatch");function Bl(e,t){let n=kw(e);if(!n)return;let r=pn(e);if(!(r===null||r.pid!==t.pid||r.head!==t.head))try{ZZ(n,{force:!0})}catch{}}a(Bl,"releaseWatch");function VD(e,t){return e!==null&&e.pid===t.pid&&e.head===t.head}a(VD,"ownsWatch");function Fr(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}a(Fr,"pidAlive");function Br(e,t,n,r=s7){if(e===null||e.head!==t)return!1;let o=Date.parse(e.seenAt);return!Number.isFinite(o)||n.now()-o>r?!1:n.alive(e.pid)}a(Br,"watchIsLive");async function YD(e,t){let n=e.tickMs??r7,r=e.stateEveryMs??o7,o=e.maxMs??i7,i=t.now(),s=null;for(;;){if(!t.treeExists())return{kind:"tree-gone"};if(!t.owns())return{kind:"superseded"};t.beat();let l=t.baseConflict();if(l!==null&&l.length>0)return t.owns()?{kind:"conflict",files:l}:{kind:"superseded"};let c=t.now();if(s===null||c-s>=r){s=c;let u=await t.readState();if(u!==null){if(u.state==="approved"||u.state==="declined"||u.state==="not_required")return{kind:"answered",state:u.state};if(u.state==="none")return{kind:"gone",prState:u.pr?.state??null}}}if(t.now()-i>=o)return{kind:"timeout"};await t.sleep(n)}}a(YD,"watchApproval");function zD(e){return e.length>3?`${e.slice(0,3).join(", ")} and ${e.length-3} more`:e.join(", ")}a(zD,"fileList");function XD(e){return`**Don't approve PR #${e.prNumber} at \`${e.shortSha}\` yet** \u2014 \`${e.base}\` moved while the merge approval was waiting, and this head now conflicts with it in ${zD(e.files)}. An approval of it could not be merged; the resolution is a new head that will be asked for again. (Noticed by the base watch that maind feature ship leaves behind.)`}a(XD,"conflictComment");function Ul(e,t){let n=`PR #${t.prNumber} at ${t.shortSha}`;switch(e.kind){case"conflict":return`${n}: ${t.base} moved, and the head now conflicts with it in ${zD(e.files)} \u2014 reported to the work object.`;case"answered":return e.state==="not_required"?`${n}: the organization no longer asks for merge approvals \u2014 nothing left to watch.`:`${n}: the merge question was answered (${e.state}) \u2014 nothing left to watch.`;case"gone":return`${n}: the merge question is gone${e.prState?` \u2014 the pull request is ${e.prState}`:" \u2014 a new head, or the pull request was closed"}.`;case"superseded":return`${n}: another run watches this branch now \u2014 leaving it to that one.`;case"tree-gone":return`${n}: the worktree is gone \u2014 nothing left to watch.`;case"timeout":return`${n}: still unanswered after 24 h \u2014 the watch ends; the next ship or promote starts a new one.`}}a(Ul,"watchOutcomeLine");function Uf(e){return e.questionOpen&&e.setting==="on"&&!e.ci&&!e.alreadyWatched}a(Uf,"shouldStartWatch");function c7(e){return e.byBranch?["feature","approval","--branch",e.branch,"--watch-base"]:["feature","approval",e.label,"--watch-base"]}a(c7,"approvalWatchArgs");function u7(e){let t=qD(e,["rev-parse","--git-common-dir"]);return t?t7(bw(e,t),"maind","approval-watch.log"):null}a(u7,"watchLogPath");function Hf(e,t,n=process.argv[1]){try{if(!n)return null;let r=u7(e);if(!r)return null;zZ(bw(r,".."),{recursive:!0});let o=XZ(r,"a"),i=VZ(process.execPath,[...process.execArgv,n,...c7(t)],{cwd:e,detached:!0,stdio:["ignore",o,o],env:process.env});return i.unref(),typeof i.pid=="number"?r:null}catch{return null}}a(Hf,"startApprovalWatch");import{execFileSync as Gl}from"node:child_process";import{existsSync as x7}from"node:fs";function JD(e,t,n=()=>null){if(e!==null)return e.trim()==="0"?{kind:"none",reason:"no required checks"}:{kind:"watch"};let r=t();if(r===null)return{kind:"unknown",reason:"neither query could be answered"};if(r.trim()==="0")return{kind:"none",reason:"no checks at all"};let o=n();return o!==null&&o.trim()==="0"?{kind:"none",reason:"checks exist, none required",checks:Number.parseInt(r.trim(),10)}:{kind:"unknown",reason:`${r.trim()} check(s) exist, but the required-query failed`}}a(JD,"classifyCheckCount");function ZD(e){switch(e.kind){case"watch":return"";case"none":return e.reason==="no checks at all"?"this repository reports NO checks at all \u2014 the merge rests on the local gate alone.":e.reason==="checks exist, none required"?`${e.checks??"some"} check(s) run on this PR, but none is required (no branch protection) \u2014 they are not waited for; the merge rests on the local gate.`:"no required checks are configured \u2014 nothing to wait for.";case"unknown":return`could not establish the required checks: ${e.reason}.`}}a(ZD,"checkCountLine");function QD(e,t){let n=new Set(t);return e.filter(r=>!n.has(r))}a(QD,"missingRequiredChecks");function ej(e){if(e===null)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let o=r;if(o?.type!=="required_status_checks")continue;let i=o.parameters?.required_status_checks;if(Array.isArray(i))for(let s of i){let l=s?.context;typeof l=="string"&&!n.includes(l)&&n.push(l)}}return n}catch{return null}}a(ej,"requiredContextsFromRules");function nj(e){let t=e.trim();return t.startsWith("/")||t.startsWith("./")||t.startsWith("../")||t.startsWith("file://")||/^[A-Za-z]:[\\/]/.test(t)}a(nj,"isLocalRemote");function d7(e){let t=Rn(e);if(!t)return null;let n=t.split("/")[0];return n&&n.length>0?n:null}a(d7,"hostOf");var f7="https://gitlab.com/gitlab-org/cli";function rj(e){if(!e.remoteUrl)return{ok:!1,reason:"no-remote",host:null,lines:[`there is no remote '${e.remote}' \u2014 nothing to push to, no pull request to open.`]};let t=d7(e.remoteUrl),n=t!==null&&t.includes("gitlab"),r=t!==null&&/bitbucket|gitea|forgejo|codeberg|azure|visualstudio/.test(t),o=e.glabInstalled===!0,i=a(l=>o&&(e.glabAuthenticatedFor?.(l)??!1),"glabFor");if(t==="github.com")return e.ghInstalled?e.ghAuthenticatedFor(t)?{ok:!0,host:t,kind:"github"}:{ok:!1,reason:"gh-unauthenticated",host:t,lines:["gh is not signed in to github.com \u2014 run: gh auth login"]}:{ok:!1,reason:"gh-missing",host:t,lines:["ship and promote work through the GitHub CLI, and gh is not installed \u2014 https://cli.github.com"]};if(t&&n)return o?i(t)?{ok:!0,host:t,kind:"gitlab"}:{ok:!1,reason:"glab-unauthenticated",host:t,lines:[`glab is not signed in to ${t} \u2014 run: glab auth login --hostname ${t}`]}:{ok:!1,reason:"glab-missing",host:t,lines:[`ship and promote work on GitLab through the GitLab CLI, and glab is not installed \u2014 ${f7}`,...tj(e,t,!0)]};if(t&&e.ghInstalled&&e.ghAuthenticatedFor(t))return{ok:!0,host:t,kind:"github"};if(t&&i(t))return{ok:!0,host:t,kind:"gitlab"};let s=t&&!r?` (if ${t} is GitHub Enterprise: gh auth login --hostname ${t}; if it is GitLab: glab auth login --hostname ${t}).`:".";return{ok:!1,reason:"not-github",host:t,lines:[`the remote '${e.remote}' points to ${t??e.remoteUrl}, which is neither GitHub nor GitLab as far as gh and glab know.`,"ship and promote open, check and merge pull requests through gh (GitHub) or glab (GitLab)"+s,...tj(e,t,!1)]}}a(rj,"judgeForge");function tj(e,t,n){let r=t!==null&&/bitbucket|gitea|forgejo|codeberg|azure|visualstudio/.test(t),o=`git push -o merge_request.create -u ${e.remote} ${e.branch}`;return[`Without it: push yourself (git push -u ${e.remote} ${e.branch}) and open the merge request on ${t??"your host"}.`,...n?[`On GitLab one step does both: ${o}`]:r?[]:[`If ${t??"it"} is GitLab, one step does both: ${o}`],"maind gate and maind review --gate work on any host."]}a(tj,"pushYourself");function Gf(e,t,n){return e.kind==="github"?`github:${t}#${n}`:`gitlab:${(e.host==="gitlab.com"?t:`${e.host}/${t}`).toLowerCase()}#${n}`}a(Gf,"forgeRef");var p7=/^\s*(?:(?:\[draft\]|\(draft\)|draft:)\s*)+/i;function oj(e){return e.replace(p7,"")}a(oj,"withoutDraftPrefix");var rr="projects/:fullpath";function ij(e){return e==="opened"?"OPEN":e==="merged"?"MERGED":e==="closed"||e==="locked"?"CLOSED":e.toUpperCase()}a(ij,"mrState");function m7(e,t){return t===!0||e==="conflict"?"CONFLICTING":typeof e!="string"?null:e==="checking"||e==="unchecked"||e==="preparing"?"UNKNOWN":"MERGEABLE"}a(m7,"mrMergeable");function ks(e){if(!e||typeof e.iid!="number"||typeof e.state!="string")return null;let t=e.draft===!0||e.work_in_progress===!0;return{number:e.iid,state:ij(e.state),baseRefName:typeof e.target_branch=="string"?e.target_branch:"",mergedAt:typeof e.merged_at=="string"?e.merged_at:null,headSha:typeof e.sha=="string"?e.sha:null,mergeable:m7(e.detailed_merge_status,e.has_conflicts),title:typeof e.title=="string"?t?oj(e.title):e.title:null,...typeof e.draft=="boolean"||typeof e.work_in_progress=="boolean"?{draft:t}:{}}}a(ks,"parseMr");function Kf(e){if(!e.ok)return null;try{return JSON.parse(e.out)}catch{return null}}a(Kf,"json");var sj=encodeURIComponent;function aj(e,t){return e==="success"?"green":e==="failed"||e==="canceled"?"red":e==="skipped"?t?"green":"red":null}a(aj,"pipelineVerdict");function Ur(e,t){let n=Kf(e(["api",rr],t));return!n||typeof n!="object"?null:{mergeMethods:NT(n),pathWithNamespace:typeof n.path_with_namespace=="string"?n.path_with_namespace:null,pipelineMustSucceed:n.only_allow_merge_if_pipeline_succeeds===!0,allowSkipped:n.allow_merge_on_skipped_pipeline===!0,removeSourceBranchAfterMerge:typeof n.remove_source_branch_after_merge=="boolean"?n.remove_source_branch_after_merge:null}}a(Ur,"readProject");function or(e,t,n,r){let o=Kf(e(["api",`${rr}/merge_requests?source_branch=${sj(n)}&state=${r}&order_by=created_at&sort=desc&per_page=1`],t));if(Array.isArray(o))return o[0]??null}a(or,"latestMr");function ws(e,t,n){let r=Kf(e(["api",`${rr}/merge_requests/${n}`],t));return r&&typeof r=="object"?r:null}a(ws,"mrByIid");function ww(e,t){let{run:n,note:r,pause:o}=t,i=t.checksTimeoutMs??30*6e4,s=null,l=a((c,u)=>ks(or(n,c,u,"all")??void 0),"prFor");return{...e,prFor:l,createPr(c,u,d,f,p){let m=Ur(n,c)?.removeSourceBranchAfterMerge===!0,h=p?.draft===!0,g=n(f?["api","-X","POST",`${rr}/merge_requests`,"-f",`source_branch=${u}`,"-f",`target_branch=${d}`,"-f",`title=${h?`Draft: ${f.title}`:f.title}`,"-f",`description=${f.body.length>0?f.body:f.title}`,...m?["-F","remove_source_branch=true"]:[]]:["mr","create","--fill","--yes","--source-branch",u,"--target-branch",d,...h?["--draft"]:[],...m?["--remove-source-branch"]:[]],c);return s=g.ok?null:g.err,g.ok?ks(or(n,c,u,"opened")??void 0):null},awaitRequiredChecks(c,u){let d=Ur(n,c);if(d===null)return r("the GitLab project settings could not be read \u2014 whether a pipeline must pass is unknown."),"unknown";if(!d.pipelineMustSucceed)return r("this GitLab project does not require a passing pipeline to merge \u2014 none is waited for; the merge rests on the local gate."),"none";let f=l(c,u);if(!f)return"unknown";let p=15e3;for(let m=0;m<=i;m+=p){let h=ws(n,c,f.number),g=h?.head_pipeline??null;if(g&&(typeof h?.sha!="string"||g.sha===h.sha)){let b=aj(g.status,d.allowSkipped);if(b!==null)return b}m<i&&o(p)}return r("the pipeline for the merge request's head did not finish within 30 minutes."),"unknown"},pause:o,mergePr(c,u,d,f){let p=l(c,u);if(!p)return!1;for(let m=1;m<=3;m+=1){let h=n(["api","-X","PUT",`${rr}/merge_requests/${p.number}/merge`,"-F",`squash=${f==="squash"}`,...d?["-f",`sha=${d}`]:[]],c);if(h.ok)return!0;s=h.err,m<3&&o(5e3)}return!1},mergeMethods(c){return Ur(n,c)?.mergeMethods??null},markReady(c,u){let d=or(n,c,u,"opened");return!d||typeof d.iid!="number"||typeof d.title!="string"?!1:d.draft!==!0&&d.work_in_progress!==!0?!0:n(["api","-X","PUT",`${rr}/merge_requests/${d.iid}`,"-f",`title=${oj(d.title)}`],c).ok},openPrsOnBase(c,u){return h7(n(["api",`${rr}/merge_requests?target_branch=${sj(u)}&state=opened&per_page=100`],c),u)},retargetPr(c,u,d){return n(["api","-X","PUT",`${rr}/merge_requests/${u}`,"-f",`target_branch=${d}`],c).ok},remoteSlugFor(c){return Ur(n,c)?.pathWithNamespace??null},lastPrError(){return s}}}a(ww,"gitlabOutwardOps");function h7(e,t){let n=Kf(e);if(!Array.isArray(n))return null;let r=[];for(let o of n){if(typeof o.iid!="number"||typeof o.source_branch!="string")return null;o.target_branch!==void 0&&o.target_branch!==t||r.push({number:o.iid,headRefName:o.source_branch})}return r}a(h7,"parseStackedMrs");function lj(e,t,n){let r=or(e,t,n,"opened");if(r!==void 0){if(r===null)return null;if(typeof r.iid=="number")return{number:r.iid,url:typeof r.web_url=="string"?r.web_url:null}}}a(lj,"gitlabOpenMr");function cj(e,t,n){let r=or(e,t,n,"merged");return!r||typeof r.state!="string"?null:{state:ij(r.state),headSha:typeof r.sha=="string"?r.sha:null}}a(cj,"gitlabMergedMr");function uj(e,t,n){let r=ws(e,t,n),o=typeof r?.merge_commit_sha=="string"?r.merge_commit_sha:typeof r?.squash_commit_sha=="string"?r.squash_commit_sha:r?.state==="merged"&&typeof r?.sha=="string"?r.sha:null;return o&&/^[0-9a-f]{40}$/.test(o)?o:null}a(uj,"gitlabMergeCommit");function dj(e,t,n,r){let o=ks(or(e.run,t,n,"opened")??void 0);if(!o)return;let i=Ur(e.run,t)?.pipelineMustSucceed===!0;for(let s=0;s<60;s+=1){let l=ws(e.run,t,o.number);if(l?.sha===r&&(!i||l.head_pipeline?.sha===r))return;e.pause(3e3)}e.note("GitLab did not show the release commit as the merge request's head within 3 minutes \u2014 the merge may be refused.")}a(dj,"gitlabAwaitHead");function fj(e,t,n,r,o=10){let i=ks(or(e.run,t,n,"opened")??void 0);if(!i)return;for(let l=0;l<o;l+=1)if(l>0&&e.pause(3e3),ws(e.run,t,i.number)?.head_pipeline?.sha===r)return;let s=e.run(["api","-X","POST",`${rr}/merge_requests/${i.number}/pipelines`],t);e.note(s.ok?`the head ${r.slice(0,9)} had no pipeline after the switch to ready \u2014 started a merge request pipeline for it.`:`the head ${r.slice(0,9)} has no pipeline, and starting one failed${s.err?` (${s.err.split(`
|
|
581
581
|
`)[0]})`:""} \u2014 does the project's CI run merge request pipelines?`)}a(fj,"gitlabAwaitReady");function pj(e,t,n){let r=ks(or(e,t,n,"opened")??void 0);if(!r)return null;let o=ws(e,t,r.number);if(!o)return null;let i=o.head_pipeline??null;if(!i||typeof o.sha=="string"&&i.sha!==o.sha)return[];let s=typeof i.status=="string"?i.status:"";return[{name:"pipeline",workflow:Gk,state:s==="success"||s==="skipped"?"green":s==="failed"?"red":s==="canceled"?"cancelled":"pending",detail:s||"unknown",url:typeof i.web_url=="string"?i.web_url:null}]}a(pj,"gitlabCheckStates");function mj(e,t,n){let r="required-checks",o=Ur(e,t);if(o===null)return{name:r,verdict:"note",detail:"not readable \u2014 promote waits for the pipeline itself"};if(!o.pipelineMustSucceed)return{name:r,verdict:"note",detail:"the project does not require a passing pipeline \u2014 the merge rests on the local gate"};let i=ks(or(e,t,n,"opened")??void 0),l=(i?ws(e,t,i.number):null)?.head_pipeline?.status,c=aj(l,o.allowSkipped);return c==="green"?{name:r,verdict:"ok",detail:"the pipeline of the head passed"}:c==="red"?{name:r,verdict:"fail",detail:`the pipeline of the head is ${String(l)}`}:{name:r,verdict:"note",detail:typeof l=="string"?`the pipeline of the head is ${l} \u2014 promote waits for it`:"no pipeline for the head yet \u2014 promote waits for it"}}a(mj,"gitlabChecksRow");import{execFileSync as g7}from"node:child_process";import{mkdtempSync as y7,rmSync as b7,unlinkSync as hj}from"node:fs";import{tmpdir as k7}from"node:os";import{join as Wf}from"node:path";var w7=a((e,t)=>e!==null&&t!==null&&e.mode===t.mode&&e.blob===t.blob,"same"),_w=10*6e4;function gj(e,t){let n={landed:[],differs:[],recent:[]};for(let r of e){if($o(r)==="landed"){n.landed.push(r.path);continue}n.differs.push(r.path),r.mtimeMs!==null&&t-r.mtimeMs<_w&&n.recent.push(r.path)}return n}a(gj,"planUnblock");function _7(e){return`refs/maind-backup/main-checkout-${e.toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z")}`}a(_7,"backupRefName");function mn(e,t,n){try{return g7("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024,...n?{env:n}:{}})}catch{return null}}a(mn,"git");var Hl={facts(e,t,n){return Mi(e,t,n,{timeoutMs:3e4})},backup(e,t,n,r){let o=y7(Wf(k7(),"maind-unblock-"));try{let i={...process.env,GIT_INDEX_FILE:Wf(o,"index")};if(mn(e,["read-tree","HEAD"],i)===null)return null;let s=n.filter(d=>d.exists).map(d=>d.path),l=n.filter(d=>!d.exists&&d.head!==null).map(d=>d.path);if(s.length>0&&mn(e,["add","-f","--",...s],i)===null||l.length>0&&mn(e,["rm","-q","--cached","--ignore-unmatch","--",...l],i)===null)return null;let c=mn(e,["write-tree"],i)?.trim();if(!c)return null;let u=mn(e,["commit-tree",c,"-p","HEAD","-m",r])?.trim();if(!u)return null;for(let d of n){if(d.work===null)continue;let f=mn(e,["--literal-pathspecs","ls-tree","-z",u,"--",d.path]),p=f===null?null:xa(f.split("\0").filter(m=>m.length>0)).get(d.path)??null;if(!w7(p,d.work))return null}return mn(e,["update-ref",t,u])===null?null:u}finally{b7(o,{recursive:!0,force:!0})}},clear(e,t){let n=t.filter(i=>i.head!==null).map(i=>i.path),r=t.filter(i=>i.head===null);if(n.length>0&&mn(e,["checkout","-q","HEAD","--",...n])===null)return!1;let o=r.filter(i=>i.index!==null).map(i=>i.path);if(o.length>0&&mn(e,["rm","-q","--cached","--",...o])===null)return!1;try{for(let i of r)i.exists&&hj(Wf(e,i.path))}catch{return!1}return!0},restore(e,t,n){let r=n.filter(o=>o.exists).map(o=>o.path);if(r.length>0&&(mn(e,["checkout","-q",t,"--",...r])===null||mn(e,["reset","-q","HEAD","--",...r])===null))return!1;try{for(let o of n)!o.exists&&o.head!==null&&hj(Wf(e,o.path))}catch{return!1}return!0}};function yj(e,t,n,r,o=Date.now()){let i=e.facts(t,n,r);if(i===null)return null;let s=gj(i,o);return s.differs.length>0||s.landed.length===0?{cleared:[],landed:s.landed.length}:e.clear(t,i)?{cleared:i,landed:s.landed.length}:null}a(yj,"clearLandedBlockers");function v7(e){let t=Math.round(e/6e4);if(t<1)return"seconds ago";if(t<120)return`${t} min ago`;let n=Math.round(t/60);return n<48?`${n} h ago`:`${Math.round(n/24)} d ago`}a(v7,"ago");function bj(e,t){let{mainRoot:n,remote:r,base:o}=t,i=`${r}/${o}`,s=[],l=a(w=>({exitCode:w,lines:s}),"end"),c=e.currentBranch(n);if(c!==o)return s.push(`the main checkout (${n}) is on ${c??"a detached HEAD"}, not on ${o} \u2014 nothing to pull here, and this command does not switch it.`),l(1);e.fetch(n,r)||s.push(`could not fetch ${r} \u2014 comparing with ${i} as of the last fetch.`);let u=e.behind(n,i);if(u===0)return s.push(`the main checkout is at ${i} \u2014 nothing to do.`),l(0);let d=e.blockers(n,i);if(d===null)return s.push("git did not answer \u2014 could not tell what stands in the way. Nothing was changed."),l(1);let f=u===null?"behind":`${u} commit(s) behind`;if(d.length===0)return t.yes?e.pullFastForward(n,r,o)?(s.push(`pulled \u2014 the main checkout is at ${i}.`),l(0)):(s.push(`git pull --ff-only refused, though no uncommitted file overlaps the incoming changes (git -C ${n} status shows why). Nothing was changed.`),l(1)):(s.push(`the main checkout is ${f} ${i}, and no uncommitted file stands in the way. With --yes this command pulls.`),l(0));let p=e.ops.facts(n,i,d);if(p===null)return s.push("git did not answer \u2014 could not compare the files with the incoming state. Nothing was changed."),l(1);let m=e.now(),h=gj(p,m.getTime()),g=new Set(h.landed);s.push(`the main checkout is ${f} ${i}; ${d.length} uncommitted file(s) stand in the way of the pull:`);for(let w of p){let x=w.mtimeMs===null?"":`, changed ${v7(m.getTime()-w.mtimeMs)}`;s.push(g.has(w.path)?` landed ${w.path} \u2014 holds exactly what ${i} brings${x}`:` differs ${w.path} \u2014 ${w.head===null?"untracked here":"modified here"}, not what ${i} brings${x}`)}if(!t.yes)return s.push(h.differs.length===0?"Every one of them already holds the incoming state \u2014 clearing them loses nothing.":`${h.differs.length} differ from the incoming state: with --yes they are saved in a backup ref first (a commit; nothing is deleted from git), then every file above is cleared and the checkout is pulled.`),h.recent.length>0&&s.push(`${h.recent.length} of the differing file(s) changed in the last ${_w/6e4} minutes \u2014 a session may be working on them; --yes stops there unless --even-recent is given.`),s.push("Nothing was changed. To do it: maind feature unblock-main --yes"),l(0);if(h.recent.length>0&&!t.evenRecent)return s.push(`stopped: ${h.recent.length} differing file(s) changed in the last ${_w/6e4} minutes \u2014 a session may be working on them right now. Nothing was changed. Ask that session, wait, or add --even-recent.`),l(1);let b=null,k=p.filter(w=>!g.has(w.path));if(k.length>0){b=_7(m);let w=e.ops.backup(n,b,k,`backup: ${k.length} uncommitted file(s) of the main checkout, parked by maind feature unblock-main before pulling ${i}`);if(w===null)return s.push("the backup could not be written or did not hold the files byte for byte \u2014 nothing was changed."),l(1);s.push(`saved ${k.length} differing file(s) in ${b} (${w.slice(0,9)}), byte for byte.`)}let _=a(()=>{let w=e.ops.restore(n,i,p.filter(S=>g.has(S.path))),x=b===null||e.ops.restore(n,b,k);s.push(w&&x?"the files are back where they were.":`some files could not be put back \u2014 they are in ${b??i}: git -C ${n} checkout ${b??i} -- <path>.`)},"putBack");return e.ops.clear(n,p)?e.pullFastForward(n,r,o)?(s.push(`pulled \u2014 the main checkout is at ${i}.`),b!==null&&(s.push(`the parked versions: git -C ${n} diff ${i} ${b} -- <path> (get one back: git -C ${n} checkout ${b} -- <path>)`),s.push(`once nothing in them is needed: git -C ${n} update-ref -d ${b}`)),l(0)):(s.push(`git pull --ff-only still refused (git -C ${n} status shows why).`),_(),l(1)):(s.push("could not clear the files (git checkout or a delete failed)."),_(),l(1))}a(bj,"unblockMain");var vw=null;function _s(e){vw=e}a(_s,"setActiveReport");function E(e){vw?vw.say(e):process.stderr.write(`maind feature: ${e}
|
|
582
582
|
`)}a(E,"note");function D(e,t,n,r=12e4){try{return Gl(e,t,{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:r}).trim()}catch{return null}}a(D,"sh");function Kl(e,t,n){try{return Gl("git",["show",`${t}:${n}`],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}a(Kl,"showAtRef");var Sj=30*6e4;function S7(e,t,n,r){try{return Gl(e,t,{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:r}),"ok"}catch(o){let i=o;return i.killed===!0||i.signal!=null&&i.status==null?"aborted":typeof i.status=="number"?"nonzero":"aborted"}}a(S7,"shOutcome");var Rj=/^(commit|cherry-pick|revert|am)\b/,Yf={defaultBranch(e){let t=D("git",["symbolic-ref","--quiet","refs/remotes/origin/HEAD"],e),n=t?/refs\/remotes\/origin\/(.+)$/.exec(t):null;if(n)return n[1];for(let r of["main","master"])if(D("git",["rev-parse","--verify","--quiet",`origin/${r}`],e)!==null)return r;return null},fetch(e,t){return D("git",["fetch","--quiet","--prune",t],e)!==null},exists(e){return x7(e)},worktreeAdd(e,t,n,r){return D("git",["worktree","add","--quiet","--no-track","-b",n,t,r],e)!==null},worktreeRemove(e,t){return D("git",["worktree","remove",t],e)!==null},worktreeAddExisting(e,t,n){return D("git",["worktree","add","--quiet",t,n],e)!==null},worktreeList(e){let t=D("git",["worktree","list","--porcelain"],e);if(!t)return[];let n=[],r=null,o=null,i=a(()=>{r!==null&&n.push({path:r,branch:o}),r=null,o=null},"flush");for(let s of t.split(`
|