@maind-dev/cli 0.162.0 → 0.162.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -267,7 +267,7 @@ maind: and re-run \`maind launch claude\`. (Or launch without routing: \`maind l
267
267
  `,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(`
268
268
  `);return{stdout:e.toml??`(using existing config: ${e.configPath})
269
269
  `,stderr:n+`
270
- `}}a(aA,"renderDryRun");import{createRequire as Aq}from"node:module";function $q(){return"0.162.0";try{return Aq(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a($q,"resolveVersion");var fe=$q();var Pq=5e3;function vt(e){process.stderr.write(`maind: ${e}
270
+ `}}a(aA,"renderDryRun");import{createRequire as Aq}from"node:module";function $q(){return"0.162.1";try{return Aq(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a($q,"resolveVersion");var fe=$q();var Pq=5e3;function vt(e){process.stderr.write(`maind: ${e}
271
271
  `)}a(vt,"err");function Lq(e){return e instanceof Error?e.message:String(e)}a(Lq,"msg");var Fq=new Set(["--config","--route","--mcp-url"]);function cA(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("-")){Fq.has(i)&&o++;continue}r=i;break}return{agent:r,dryRun:n("--dry-run"),config:t("--config")??null,route:t("--route")??Y0,direct:n("--direct"),noFallback:n("--no-fallback"),noInstall:n("--no-install"),json:n("--json"),mcpUrl:t("--mcp-url")??null}}a(cA,"parseLaunchArgs");var Bq={probe(e,t){let n=lA(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 lA("uv",[...e],{stdio:["ignore","inherit","inherit"]}).status},spawnInteractive(e){let t=Date.now();return new Promise(n=>{let r=!1,o=Tq(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=Ae()}catch(r){if(r instanceof De)return null;throw r}try{let r=new Me({apiKey:n.apiKey,deviceId:n.deviceId,clientVersion:fe,mcpUrl:e??void 0,projectKey:t}),o=new Promise(s=>{setTimeout(()=>s(null),Pq).unref()}),i=r.callTool("get_template",{template_id:z0}).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=jq(e);n&&n!=="."&&Iq(n,{recursive:!0}),Dq(e,t,"utf8")},readFile(e){try{return Nq(e,"utf8")}catch{return null}},fileExists(e){return Oq(e)},repoRoot(){try{let e=Cq("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 dt().projectKey},userConfigDir(){return jo()},homeDir(){return Mq()},env:process.env,platform:process.platform};function Uq(e,t){return e!==null?Rg(e,".maind",yg):Rg(t,yg)}a(Uq,"resolveRoutesPath");async function uA(e,t=Bq){let n=X0(e.agent);if(n.kind==="unknown")return vt(`usage: maind launch <agent> [--dry-run] [--config <path>] [--route <name>] [--direct] [--no-fallback] [--no-install] \u2014 supported: ${bg.join(", ")}`),2;if(n.kind==="planned")return vt(`agent '${n.agent}' is planned but not yet supported \u2014 v1 supports: ${bg.join(", ")}.`),2;if(e.json&&!e.dryRun)return vt("--json is only valid together with --dry-run (stdout belongs to the agent session)."),2;let r=n.agent;if(e.direct)return vt(sA()),dA(t,vg(r));let o=J0(t.env);o.warning!==null&&vt(o.warning);let i,s,l;if(e.config!==null){if(!t.fileExists(e.config))return vt(`config not found: ${e.config}`),2;let f=t.readFile(e.config);if(f===null||eA(f,e.route)===null)return vt(`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:Q0(f,e.route);if(s=Z0(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)`;vt(`using builtin routing policy (${m}).`)}i=Uq(t.repoRoot(),t.userConfigDir())}let c=pu,u=t.probe(pu,["--version"]).ok;if(e.dryRun){let f={agent:r,configPath:i,configSource:l,toml:s,argv:wg(c,r,e.route,i),backendKind:o.kind,switchyardDetected:u},p=aA(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 vt(`switchyard not found (--no-install). Install it with:
272
272
  maind: ${mu}`),1;if(!t.probe("uv",["--version"]).ok)return vt(rA()),1;if(vt(nA()),t.install(V0),t.probe(pu,["--version"]).ok)u=!0;else{let f=Rg(t.homeDir(),".local","bin",t.platform==="win32"?"switchyard.exe":"switchyard");t.probe(f,["--version"]).ok&&(c=f,u=!0)}if(!u)return Sg(t,e,r,oA())}if(l!=="flag"&&s!==null)try{t.writeConfig(i,s)}catch(f){return vt(`could not write ${i}: ${Lq(f)}`),1}let d=await t.spawnInteractive(wg(c,r,e.route,i));return d.spawnError!==null?Sg(t,e,r,`could not start switchyard (${d.spawnError})`):tA(d.code,d.signal,d.elapsedMs)==="fallback-eligible"?Sg(t,e,r,`switchyard exited with code ${d.code} after ${(d.elapsedMs/1e3).toFixed(1)}s`):xg(d.code,d.signal)}a(uA,"runLaunch");async function Sg(e,t,n,r){return t.noFallback?(vt(`${r} (--no-fallback set \u2014 not degrading to a direct spawn).`),1):(process.stderr.write(iA(r)+`
273
273
  `),dA(e,vg(n)))}a(Sg,"degradeOrFail");async function dA(e,t){let n=await e.spawnInteractive(t);return n.spawnError!==null?(vt(`'${t[0]}' not found on PATH \u2014 install the agent CLI first (${n.spawnError}).`),1):xg(n.code,n.signal)}a(dA,"spawnAndPropagate");var Eg="tests:";function hu(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(hu,"parseOverride");function Hq(e){return e==="open"||e==="warn"}a(Hq,"objectCarriesOverride");async function gu(e,t,n){let r=[];for(let i of e)!t.has(i.gate)&&!i.gate.startsWith(Eg)&&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`):Hq(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(gu,"checkOverrides");function fA(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(fA,"applyOverrides");function pA(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(pA,"unusedOverrideLines");var yu=["squash","merge","rebase"];function bu(e){return typeof e=="string"&&yu.includes(e)}a(bu,"isMergeMethod");function mA(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(mA,"githubMergeMethods");function hA(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(hA,"gitlabMergeMethods");function Ag(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?yu.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(Ag,"chooseMergeMethod");var Gq={squash:"squash",merge:"merge commit",rebase:"rebase"};function ai(e){return Gq[e]}a(ai,"methodLabel");function $g(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 ${ai(e.method)} (${t[e.source]})`}a($g,"methodLine");function Tg(e){let t=e.source==="flag"?"--merge-method":"mergeMethod in .maind/feature.json",n=e.allowed.length>0?e.allowed.map(ai).join(", "):"none";return[`${t} asks for ${ai(e.method)}, and this repository's forge does not allow it (allowed: ${n}).`,"Nothing ran and nothing was merged."]}a(Tg,"notAllowedLines");function ku(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(ku,"rebaseMergeCommitLines");import{readFileSync as FA}from"node:fs";import{join as BA}from"node:path";import{spawn as Kq,spawnSync as Wq}from"node:child_process";function Cg(e){return e==="work"||e==="always"||e==="off"}a(Cg,"isStayAwakeSetting");function qq(e,t){if(e.CI||e.NODE_TEST_CONTEXT)return"off";let n=e.MAIND_STAY_AWAKE?.trim().toLowerCase();return Cg(n)?n:t??"work"}a(qq,"resolveStayAwake");function Vq(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(Vq,"inhibitCommand");function Yq(e,t,n){let r=null,o=a(()=>{if(e==="off"||r!==null)return;let s=Vq(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(Yq,"makeAwake");function zq(e){try{return Wq("sh",["-c",`command -v ${e}`],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}a(zq,"hasBinary");var Xq={platform:process.platform,pid:process.pid,has:zq,start:a((e,t)=>{try{let n=Kq(e,[...t],{stdio:"ignore"});return n.on("error",()=>{}),n.unref(),typeof n.pid=="number"?()=>n.kill():null}catch{return null}},"start")},po=null;function _u(e,t,n={}){let r=po===null;return r&&(po=Yq(qq(n.env??process.env,e),t,n.deps??Xq)),po.work(),{end:a(()=>{r&&(po?.end(),po=null)},"end")}}a(_u,"beginAwake");function gA(){po?.work()}a(gA,"awakeWork");function yA(){po?.waiting()}a(yA,"awakeWaiting");import{execFileSync as rV}from"node:child_process";import{realpathSync as oV}from"node:fs";function wu(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(wu,"serverPlanAnswer");var na="MAIND_GATE_OBJECT_REASON",Jq=/^[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 Zq(e){if(e===null)return!1;let t=e.trim();return t.length<4?!1:!["1","true","yes","on","skip"].includes(t.toLowerCase())}a(Zq,"isReason");function vu(e){let t=Qq(e);return t.kind!=="linked"&&Zq(e.overrideReason)?{kind:"overridden",reason:e.overrideReason.trim()}:t}a(vu,"classifyWorkObject");function Qq(e){if(e.branch===null)return{kind:"detached"};let t=e.objectId?.trim()??"";return t.length===0?{kind:"missing",branch:e.branch}:Jq.test(t)?{kind:"linked",objectId:t,objectKey:e.objectKey?.trim()||null,planRevision:e.planRevision?.trim()||null}:{kind:"malformed",branch:e.branch,value:t}}a(Qq,"judge");function xu(e){return e.kind==="linked"||e.kind==="overridden"}a(xu,"workObjectPasses");function bA(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 (ADR-334) \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(bA,"workObjectLines");function Og(e){return`${e.dir}\0${e.check??""}`}a(Og,"checkKey");function kA(e){return`${e.replace(/[/\\]+$/,"")}-apply`}a(kA,"applyCheckoutPath");function _A(e){return[...new Set(e.filter(t=>t.command!==null).map(t=>t.trigger))].sort()}a(_A,"applyTriggers");function rt(e){return/^[A-Za-z0-9_./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}a(rt,"shellQuote");function eV(e,t){let n=t.replace(/^\/+|\/+$/g,"");return n.length===0?e:`${e.replace(/\/+$/,"")}/${n}`}a(eV,"joinAbs");function tV(e){return e.endsWith("/")?e:`${e}/`}a(tV,"withPrefix");function nV(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(nV,"defaultPostMergeSteps");function Ig(e,t,n){let r=e.map(s=>s.trim()).filter(s=>s.length>0),o=t??nV(r),i=[];for(let s of o){let l=tV(s.when),c=r.filter(h=>h.startsWith(l));if(c.length===0)continue;let u=eV(n,s.cwd??""),d=`cd ${rt(u)} && `,f=a((h,k)=>h===void 0?void 0:h.split("{name}").join(k),"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(k=>!k.startsWith("_"))){let k=f(s.note,h),y=f(s.run,h),b=f(s.check,h);i.push({reason:`${l}${h}/ changed`+(k?` \u2014 ${k}`:""),command:y?d+y:null,trigger:l,dir:u,check:y&&b?b: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(Ig,"postMergeActions");function wA(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 ${rt(i)} worktree remove ${rt(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(Og(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(wA,"postMergeLines");function ra(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(ra,"decideCompletion");function vA(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(vA,"missingCompletionLines");function Ng(e){if(!e.required)return null;let t=vu({branch:e.branch,objectId:e.boundObject,objectKey:null,overrideReason:e.overrideReason,planRevision:null});return xu(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: ${li}="<reason>" ${e.promoteCommand} --yes`,"Nothing was merged."]}a(Ng,"unboundObjectLines");var li=na;function Pn(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)}a(Pn,"cwdInside");function xt(e,t){return`cd ${rt(e)} && ${t}`}a(xt,"cleanupCommand");function xA(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(xA,"alreadyMergedLines");function SA(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(SA,"doneInsideLines");function RA(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(RA,"deferredCleanupLines");function EA(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:`,` ${xt(e.mainRoot,e.doneCommand)}`,` or, later, for every merged worktree at once: ${xt(e.mainRoot,"maind feature done --merged")}`]}a(EA,"keptWorktreeLines");async function Dg(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(Dg,"recoverBinding");async function oa(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(oa,"ensurePrLinked");function ci(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(ci,"linkMismatchLines");function AA(e,t){let n=t?.trim().toUpperCase()??null;return e.filter(r=>r.toUpperCase()!==n)}a(AA,"fanOutKeys");function $A(e,t){let n=rt(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 (${Tc(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:[` ${Tc(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($A,"fastForwardLines");function iV(e){let t=[],n=null,r="";for(let o of e.split(`
@@ -416,7 +416,7 @@ Fallback: run the MCP calls from an agent session (work_object_create/link_ref/r
416
416
  `)[0]?.trim()??null:null})();return s!==null&&s===jy(e.repo,t)?null:"is not exactly the revert of the release it names"}a(WY,"checkWithdraw");function oC(e,t){if(e.releaseVerdicts.has(t))return e.releaseVerdicts.get(t);let n=qY(e,t);return e.releaseVerdicts.set(t,n),n}a(oC,"checkRelease");function qY(e,t){let{repo:n,rules:r}=e,o=rC(n,t);if(o===null||o.length!==1)return"a release commit has exactly one parent";let i=o[0],s=Py(n,t,yr).map(Vu);if(s.length===0||s.some(f=>f===null))return"an unreadable release trailer";let l=cT(ze(n,["diff-tree","-r","-z","--raw","--no-renames",i,t])??"");if(l.length===0)return"an empty release commit";let c=lT(l);if(c!==null)return c;let u=new Set;for(let f of s){if("regenerate"in f)continue;let p=r.packages.find(h=>h.dir.replace(/\/+$/,"")===f.dir);if(!p)return`${f.dir} is not a package promote numbers on the base`;let m=VY(n,i,t,p,f.to,u);if(m!==null)return`${f.dir}: ${m}`}let d=l.map(f=>f.path).filter(f=>!u.has(f));return d.length===0?null:YY(e,i,t,d)}a(qY,"releaseVerdict");function VY(e,t,n,r,o,i){let s=r.dir.replace(/\/+$/,""),l=`${s}/package.json`,c=Un(e,t,l),u=iT(c,Un(e,n,l),o);if(u!==null)return u;i.add(l);let d=JSON.parse(c).version;if(r.mirror){let k=`${s}/${r.mirror}`,y=sT(Un(e,t,k),Un(e,n,k),d,o);if(y!==null)return y;i.add(k)}let f=(ze(e,["ls-tree","--name-only",t,`${s}/${r.fragments}/`])??"").split(`
417
417
  `).filter(k=>k&&ir(r,k)).sort(),p=[];for(let k of f){if(Un(e,n,k)!==null)return`the fragment ${k} was not consumed`;let y=Hu(Un(e,t,k)??"");if("problem"in y)return`${k}: ${y.problem}`;p.push(y.body),i.add(k)}let m=`${s}/CHANGELOG.md`,h=aT(Un(e,t,m),Un(e,n,m),o,p,r.changelog);return h!==null?h:(r.changelog&&i.add(m),null)}a(VY,"checkPackage");function YY(e,t,n,r){let{repo:o,baseRef:i,rules:s}=e,l=(ze(o,["-c","core.quotepath=off","diff","--name-only",`${i}...${t}`])??"").split(`
418
418
  `).filter(Boolean),c=s.regenerate.filter(f=>l.some(p=>p.startsWith(f.when)));if(c.length===0)return`changes ${r[0]} outside the release files, and no regenerate step applies`;let u=DY(My(PY(),"maind-carry-")),d=My(u,"wt");try{if(ze(o,["worktree","add","--detach","--quiet",d,t])===null)return"could not check out the parent to reproduce the derived files";let f=nC(d,c);if(f!==null&&s.postCreate.length>0){e.note(`installing a scratch tree to reproduce the derived files (${f} failed without it)`);for(let h of s.postCreate)if(Ly("sh",["-c",h],{cwd:d,encoding:"utf8",timeout:6e5}).status!==0)return`not reproducible here: the install it needs failed (${h})`;if(ze(d,["reset","--hard","--quiet"]),ze(d,["clean","-fd","--quiet"]),f=nC(d,c),f!==null)return`the regenerate step failed while reproducing it, also after the install: ${f}`}if(f!==null)return`the regenerate step failed while reproducing it: ${f}`;let p=(ze(d,["-c","core.quotepath=off","status","--porcelain=v1","-z","--untracked-files=all"])??"").split("\0").filter(h=>h.length>3).map(h=>h.slice(3)),m=new Set(r);if(p.length!==m.size||p.some(h=>!m.has(h)))return"the derived files differ from what the regenerate steps produce";for(let h of r){let k=Un(o,n,h),y;try{y=MY(My(d,h),"utf8")}catch{y=null}if(k!==y)return`${h} differs from what the regenerate steps produce`}return null}finally{ze(o,["worktree","remove","--force",d]),ze(o,["worktree","prune"]),jY(u,{recursive:!0,force:!0})}}a(YY,"reproduceRegenerate");function nC(e,t){for(let n of t)if(Ly("sh",["-c",n.run],{cwd:e,encoding:"utf8",timeout:3e5}).status!==0)return n.run;return null}a(nC,"runSteps");var Hy="maind-promote-hold.json";function nd(e,t){try{return zY("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:6e4}).trim()}catch{return null}}a(nd,"git");function rd(e,t){let n=nd(e,["rev-parse","--git-path",t]);return n?ez(n)?n:tz(e,n):null}a(rd,"gitPath");function Gy(e,t,n,r=Date.now()){let o=rd(e,Hy);if(!o||sC(e)!==null)return;let i={v:1,startHead:t,at:new Date(r).toISOString(),by:n};try{QY(o,`${JSON.stringify(i)}
419
- `)}catch{}}a(Gy,"beginHold");function Hn(e){let t=rd(e,Hy);if(t)try{ZY(t,{force:!0})}catch{}}a(Hn,"endHold");function sC(e){let t=rd(e,Hy);if(!t)return null;try{let n=JSON.parse(JY(t,"utf8")),r=typeof n.startHead=="string"&&/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(n.startHead)?n.startHead:null,o=typeof n.at=="string"?n.at:null,i=n.by==="check"||n.by==="promote"?n.by:null;return n.v!==1||!r||!o||!i?null:{v:1,startHead:r,at:o,by:i}}catch{return null}}a(sC,"readHold");function nz(e,t,n){if(!e||!t||e===t)return{kind:"none"};if(n.links.length===0||n.links[0].sha!==e)return{kind:"foreign"};if(n.stoppedAt.sha===t)return{kind:"own",count:n.links.length,to:t};let r=n.links.findIndex(o=>o.sha===t);return r>0?{kind:"own",count:r,to:t}:{kind:"foreign"}}a(nz,"classifyLeftover");function Oa(e,t,n){let r=sC(e);if(r===null)return{kind:"none"};let o=r.startHead,i=!1,s=rd(e,"MERGE_HEAD");s!==null&&XY(s)&&(i=iC("git",["merge","--abort"],{cwd:e,encoding:"utf8",timeout:6e4}).status===0);let l=nd(e,["rev-parse","HEAD"]);if(!l||l===o)return l===o&&(nd(e,["status","--porcelain"])??"")!==""?{kind:"uncommitted",by:r.by}:(Hn(e),i?{kind:"recovered",count:0,from:o,to:o,by:r.by,abortedMerge:i}:{kind:"cleared"});if(n!==null&&nd(e,["merge-base","--is-ancestor",l,n])!==null)return Hn(e),{kind:"cleared"};let c=nz(l,o,tn(e,l,t));if(c.kind!=="own")return Hn(e),{kind:"foreign",from:l,to:o};let u=iC("git",["reset","--keep",o],{cwd:e,encoding:"utf8",timeout:6e4});return u.status!==0?{kind:"failed",from:l,to:o,output:`${u.stdout??""}${u.stderr??""}`.trim()}:(Hn(e),{kind:"recovered",count:c.count,from:l,to:o,by:r.by,abortedMerge:i})}a(Oa,"recoverHold");function Ia(e,t,n){switch(e.kind){case"none":case"cleared":return[];case"recovered":return[`an earlier ${e.by==="check"?"promote --check":"promote"} run was interrupted while it held `+(e.count>0?`${e.count} local commit(s) of its own`:"a half-finished merge of the base")+` \u2014 they were never pushed. ${t} is back at ${e.to.slice(0,9)}.`];case"uncommitted":return[`an earlier ${e.by==="check"?"promote --check":"promote"} run ended while it was writing its own files (a release number, derived files) \u2014 they are in the worktree, not committed.`,`if you changed nothing here since, discard them and run it again: cd ${n} && ${xy}`];case"foreign":return[`an earlier promote run was interrupted at ${e.to.slice(0,9)}, but ${t} has moved on to ${e.from.slice(0,9)} with commits promote did not make \u2014 nothing was touched.`];case"failed":return[`an earlier promote run was interrupted and left local commits, and ${t} could not be moved back to ${e.to.slice(0,9)} (${e.output}).`,`undo them before the next run: cd ${n} && git reset --keep ${e.to}`]}}a(Ia,"holdRecoveryLines");function aC(e){let t=`${e.base} moved from ${e.from.slice(0,9)} to ${e.to.slice(0,9)}${e.commits?` (${e.commits} commit(s))`:""}`,n="the gate judged the merge result with the earlier base, so what would land now is unchecked",r=[e.when==="after-gate"?`${t} while the gate ran \u2014 ${n}. Nothing was pushed and nothing was merged.`:e.conflicting?`${t} before the merge, and the pull request now conflicts with it. Nothing was merged.`:`${t} before the merge \u2014 ${n}. Nothing was merged.`];return e.retriesSoFar>=e.maxRetries?(r.push(`${e.base} moved ${e.maxRetries+1} times in a row before the merge \u2014 run promote again when it is quieter.`),{retry:!1,lines:r}):(r.push(`promoting again against ${e.base} as it is now (attempt ${e.retriesSoFar+2} of ${e.maxRetries+1}) \u2014 the approval stands, only the base moved.`+(e.conflicting?" A conflict in promote's own release commit is solved there (the commit is withdrawn and the number assigned anew); a conflict in the branch's own content stops that attempt and names the files.":"")),{retry:!0,lines:r})}a(aC,"movedBasePlan");function lC(e,t,n){return[n?`${e} conflicts with ${t} \u2014 nothing was merged. GitHub reported the conflict only after the merge attempt (${t} moved since the checks ran).`:`${e} conflicts with ${t} \u2014 nothing was merged. GitHub builds no merge ref for a conflicting pull request, so the required checks never start.`,`run promote again: it rebuilds the merge result against ${t} and solves a conflict in its own release commit itself. If the branch's own content conflicts, it names the files \u2014 then merge ${t} into the branch, resolve, push (a pushed commit needs a new approval).`]}a(lC,"conflictLines");import{spawn as rz}from"node:child_process";var oz=a((e,t)=>{try{let n=rz(e,t,{stdio:"ignore"});return{kill:a(()=>void n.kill(),"kill"),unref:a(()=>n.unref(),"unref"),on:a((r,o)=>void n.on(r,o),"on")}}catch{return null}},"realSpawn");function iz(e,t){return e==="darwin"?{cmd:"caffeinate",args:["-i","-w",String(t)]}:e==="linux"?{cmd:"systemd-inhibit",args:["--what=idle:sleep","--who=maind","--why=a gate or merge run is in progress","tail",`--pid=${t}`,"-f","/dev/null"]}:null}a(iz,"awakeCommand");var od=0,id=null;function sd(e=process.platform,t=process.pid,n=oz){let r=!1;if(od===0){let o=iz(e,t),i=o?n(o.cmd,o.args):null;i&&(i.on("error",()=>{}),i.unref(),id=a(()=>i.kill(),"stop"))}return od+=1,()=>{r||(r=!0,od-=1,od===0&&id&&(id(),id=null))}}a(sd,"keepAwake");import{execFileSync as wI,spawnSync as u3}from"node:child_process";import{existsSync as d3,readFileSync as f3}from"node:fs";import{join as Sd}from"node:path";var sz={"migration-first":"push the migration before the code goes live","code-first":"release and deploy the code before you push the migration","any-order":"either order works"};function cC(e){return e.verdict==="declared"&&e.declared!==null?[`note rollout \u2014 ${e.declared.order}: ${sz[e.declared.order]} (${e.declared.reason})`]:e.verdict==="undeclared"?e.findings.map(t=>`note rollout \u2014 ${t.title}`):[]}a(cC,"rolloutRows");function az(e,t){return t===void 0||t.length===0?!0:e===void 0||e.length===0?!1:e.every(n=>t.some(r=>n===r||n.startsWith(r)))}a(az,"scopeCovers");function lz(e,t){if(t===null)return[{kind:"manifest-removed",subject:""}];let n=[],r=new Map(t.gates.map(i=>[i.id,i]));for(let i of e.gates){let s=r.get(i.id);if(s===void 0){n.push({kind:"gate-removed",subject:i.id});continue}i.blocking&&!s.blocking&&n.push({kind:"gate-non-blocking",subject:i.id}),az(i.paths,s.paths)||n.push({kind:"gate-narrowed",subject:i.id})}let o=new Set(t.versionedDirs);for(let i of e.versionedDirs)o.has(i)||n.push({kind:"versioned-removed",subject:i});return e.requireWorkObject&&!t.requireWorkObject&&n.push({kind:"work-object-off",subject:""}),e.review&&!t.review&&n.push({kind:"review-off",subject:""}),e.tests!==void 0&&t.tests!==void 0&&n.push(...uC(e.tests,t.tests)),n}a(lz,"weakenings");function uC(e,t){let n=[];if(e===null)return n;if(t===null)return[{kind:"tests-off",subject:""}];let r=new Set(e.skip);for(let o of t.skip)r.has(o)||n.push({kind:"tests-skipped",subject:o});for(let[o,i]of Object.entries(t.commands))e.commands[o]!==i&&n.push({kind:"tests-command",subject:o});for(let o of Object.keys(e.commands))t.commands[o]===void 0&&n.push({kind:"tests-command",subject:o});for(let[o,i]of Object.entries(e.inputs??{})){let s=t.inputs?.[o]??[];i.every(l=>s.some(c=>l===c||l.startsWith(c)))||n.push({kind:"tests-inputs",subject:o})}return n}a(uC,"testsWeakenings");function cz(e){if(e===null)return!1;let t=e.trim();return t.length<4?!1:!["1","true","yes","on","skip"].includes(t.toLowerCase())}a(cz,"isManifestReason");function dC(e){if(e.base===null||!e.baseRefResolvable)return{kind:"no-base"};if(e.baseUnparsable)return{kind:"base-unparsable"};let t=e.baseManifest===null?e.headManifest===null?[]:e.headManifest.tests===void 0?[]:uC(e.testsWithoutManifest??null,e.headManifest.tests):lz(e.baseManifest,e.headManifest);return e.baseManifest===null&&t.length===0?{kind:"base-absent"}:t.length===0?{kind:"intact"}:cz(e.overrideReason)?{kind:"overridden",weakenings:t,reason:e.overrideReason.trim()}:{kind:"weakened",weakenings:t}}a(dC,"classifyManifestDrift");var uz={"manifest-removed":a(()=>"the whole manifest is gone \u2014 every declared gate with it","manifest-removed"),"gate-removed":a(e=>`gate "${e}" is gone`,"gate-removed"),"gate-non-blocking":a(e=>`gate "${e}" no longer blocks`,"gate-non-blocking"),"gate-narrowed":a(e=>`gate "${e}" now applies to less than it did`,"gate-narrowed"),"versioned-removed":a(e=>`"${e}" no longer claims a hand-assigned version`,"versioned-removed"),"work-object-off":a(()=>"a branch no longer needs a work object","work-object-off"),"review-off":a(()=>"the review gate is switched off","review-off"),"tests-off":a(()=>"the built-in test gate is switched off","tests-off"),"tests-skipped":a(e=>`the test suite of "${e}" is skipped now`,"tests-skipped"),"tests-command":a(e=>`the test command of "${e}" changed`,"tests-command"),"tests-inputs":a(e=>`the test suite of "${e}" now runs for less than it did (tests.inputs)`,"tests-inputs")};function Ky(e){return uz[e.kind](e.subject)}a(Ky,"weakeningLine");function fC(e,t,n=null){if(e.branch===null)return{kind:"no-branch"};if(e.remoteSha===null)return{kind:"not-shipped",branch:e.branch};if(e.upstream!==null){let r=`${t}/${e.branch}`;if(e.upstream!==r)return{kind:"upstream-mismatch",branch:e.branch,upstream:e.upstream}}return e.localSha===null?{kind:"unknown",reason:"the local HEAD could not be resolved"}:e.localSha===e.remoteSha?{kind:"match",sha:e.localSha}:n!==null&&e.remoteSha===n&&e.behind===0?{kind:"push-pending",branch:e.branch,local:e.localSha,remote:e.remoteSha,ahead:e.ahead}:{kind:"diverged",branch:e.branch,local:e.localSha,remote:e.remoteSha,ahead:e.ahead,behind:e.behind}}a(fC,"classifyParity");function pC(e){return e.kind==="diverged"||e.kind==="upstream-mismatch"||e.kind==="unknown"}a(pC,"parityBlocks");function Wy(e,t,n=!1){let r=["the working tree has uncommitted changes \u2014 the gates below also judge files that are"," NOT in the commit that gets merged. Commit or discard them before relying on this verdict."];if(n&&e.kind==="match")return[`HEAD == ${t}/HEAD (${e.sha.slice(0,9)}), but ${r[0]}`,r[1]];if(n)return[...Wy(e,t,!1),...r];switch(e.kind){case"match":return[`checked state == ${t}/HEAD (${e.sha.slice(0,9)}).`];case"push-pending":return[`checked state == ${t}/${e.branch} (${e.remote.slice(0,9)}) + ${e.ahead??"?"} commit(s) of promote, not pushed yet (${e.local.slice(0,9)}).`," promote pushes exactly this state, and only if every gate below passes."];case"not-shipped":return[`branch ${e.branch}: no remote yet \u2014 the gate checks the local state.`];case"no-branch":return["detached HEAD \u2014 no remote counterpart to compare against."];case"upstream-mismatch":return[`branch ${e.branch} tracks ${e.upstream}, not ${t}/${e.branch}.`,` A merge takes ${t}/${e.branch}. Every verdict below would describe a different tree.`,` Fix: git branch --set-upstream-to=${t}/${e.branch} ${e.branch}`];case"diverged":{let o=["the gate would NOT check the state that gets merged:",` local HEAD ${e.local.slice(0,9)}${e.ahead!==null?` (${e.ahead} commit(s) ahead)`:""}`,` remote ${t}/${e.branch} ${e.remote.slice(0,9)}${e.behind!==null?` (${e.behind} commit(s) ahead)`:""}`," A merge takes the REMOTE state. Align first:"];return e.ahead!==0&&e.behind!==0?(o.push(" (history was rewritten \u2014 a plain push is rejected and a pull would bring the"," replaced commit back. On your OWN feature branch:)",` git push --force-with-lease ${t} ${e.branch}`),o):(e.ahead!==0&&o.push(` git push ${t} ${e.branch}`),e.behind!==0&&o.push(` git pull --ff-only ${t} ${e.branch}`),o)}case"unknown":return[`could not determine whether the checked state matches ${t}: ${e.reason}.`," This is not a pass \u2014 a verdict about the wrong tree is worse than none."]}}a(Wy,"parityLines");import{execFileSync as b9}from"node:child_process";import{readFileSync as k9}from"node:fs";import{join as EO}from"node:path";var Ri=".";function ad(e){let t=e.lastIndexOf("/");return t<0?Ri:e.slice(0,t)}a(ad,"dirOf");function qy(e,t){return e===Ri?t:`${e}/${t}`}a(qy,"joinDir");function Ei(e,t){return t===Ri||e===t||e.startsWith(`${t}/`)}a(Ei,"isUnder");function dz(e,t){return t===Ri?e:e===t?"":e.slice(t.length+1)}a(dz,"relativeTo");function Vy(e){if(typeof e!="string")return!1;let t=e.trim();return t.length===0?!1:!/no test specified/i.test(t)}a(Vy,"isRealTestScript");function fz(e){let t=e.split(`
419
+ `)}catch{}}a(Gy,"beginHold");function Hn(e){let t=rd(e,Hy);if(t)try{ZY(t,{force:!0})}catch{}}a(Hn,"endHold");function sC(e){let t=rd(e,Hy);if(!t)return null;try{let n=JSON.parse(JY(t,"utf8")),r=typeof n.startHead=="string"&&/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(n.startHead)?n.startHead:null,o=typeof n.at=="string"?n.at:null,i=n.by==="check"||n.by==="promote"?n.by:null;return n.v!==1||!r||!o||!i?null:{v:1,startHead:r,at:o,by:i}}catch{return null}}a(sC,"readHold");function nz(e,t,n){if(!e||!t||e===t)return{kind:"none"};if(n.links.length===0||n.links[0].sha!==e)return{kind:"foreign"};if(n.stoppedAt.sha===t)return{kind:"own",count:n.links.length,to:t};let r=n.links.findIndex(o=>o.sha===t);return r>0?{kind:"own",count:r,to:t}:{kind:"foreign"}}a(nz,"classifyLeftover");function Oa(e,t,n){let r=sC(e);if(r===null)return{kind:"none"};let o=r.startHead,i=!1,s=rd(e,"MERGE_HEAD");s!==null&&XY(s)&&(i=iC("git",["merge","--abort"],{cwd:e,encoding:"utf8",timeout:6e4}).status===0);let l=nd(e,["rev-parse","HEAD"]);if(!l||l===o)return l===o&&(nd(e,["status","--porcelain"])??"")!==""?{kind:"uncommitted",by:r.by}:(Hn(e),i?{kind:"recovered",count:0,from:o,to:o,by:r.by,abortedMerge:i}:{kind:"cleared"});if(n!==null&&nd(e,["merge-base","--is-ancestor",l,n])!==null)return Hn(e),{kind:"cleared"};let c=nz(l,o,tn(e,l,t));if(c.kind!=="own")return Hn(e),{kind:"foreign",from:l,to:o};let u=iC("git",["reset","--keep",o],{cwd:e,encoding:"utf8",timeout:6e4});return u.status!==0?{kind:"failed",from:l,to:o,output:`${u.stdout??""}${u.stderr??""}`.trim()}:(Hn(e),{kind:"recovered",count:c.count,from:l,to:o,by:r.by,abortedMerge:i})}a(Oa,"recoverHold");function Ia(e,t,n){switch(e.kind){case"none":case"cleared":return[];case"recovered":return[`an earlier ${e.by==="check"?"promote --check":"promote"} run was interrupted while it held `+(e.count>0?`${e.count} local commit(s) of its own`:"a half-finished merge of the base")+` \u2014 they were never pushed. ${t} is back at ${e.to.slice(0,9)}.`];case"uncommitted":return[`an earlier ${e.by==="check"?"promote --check":"promote"} run ended while it was writing its own files (a release number, derived files) \u2014 they are in the worktree, not committed.`,`if you changed nothing here since, discard them and run it again: cd ${n} && ${xy}`];case"foreign":return[`an earlier promote run was interrupted at ${e.to.slice(0,9)}, but ${t} has moved on to ${e.from.slice(0,9)} with commits promote did not make \u2014 nothing was touched.`];case"failed":return[`an earlier promote run was interrupted and left local commits, and ${t} could not be moved back to ${e.to.slice(0,9)} (${e.output}).`,`undo them before the next run: cd ${n} && git reset --keep ${e.to}`]}}a(Ia,"holdRecoveryLines");function aC(e){let t=`${e.base} moved from ${e.from.slice(0,9)} to ${e.to.slice(0,9)}${e.commits?` (${e.commits} commit(s))`:""}`,n="the gate judged the merge result with the earlier base, so what would land now is unchecked",r=[e.when==="after-red-gate"?`${t} while the gate ran, and the gate was red \u2014 its verdict was on a combination that would no longer land (a number the base took meanwhile reads as taken, for one). Nothing was pushed and nothing was merged.`:e.when==="after-gate"?`${t} while the gate ran \u2014 ${n}. Nothing was pushed and nothing was merged.`:e.conflicting?`${t} before the merge, and the pull request now conflicts with it. Nothing was merged.`:`${t} before the merge \u2014 ${n}. Nothing was merged.`];return e.retriesSoFar>=e.maxRetries?(r.push(`${e.base} moved ${e.maxRetries+1} times in a row before the merge \u2014 run promote again when it is quieter.`),{retry:!1,lines:r}):(r.push(`promoting again against ${e.base} as it is now (attempt ${e.retriesSoFar+2} of ${e.maxRetries+1}) \u2014 the approval stands, only the base moved.`+(e.conflicting?" A conflict in promote's own release commit is solved there (the commit is withdrawn and the number assigned anew); a conflict in the branch's own content stops that attempt and names the files.":"")),{retry:!0,lines:r})}a(aC,"movedBasePlan");function lC(e,t,n){return[n?`${e} conflicts with ${t} \u2014 nothing was merged. GitHub reported the conflict only after the merge attempt (${t} moved since the checks ran).`:`${e} conflicts with ${t} \u2014 nothing was merged. GitHub builds no merge ref for a conflicting pull request, so the required checks never start.`,`run promote again: it rebuilds the merge result against ${t} and solves a conflict in its own release commit itself. If the branch's own content conflicts, it names the files \u2014 then merge ${t} into the branch, resolve, push (a pushed commit needs a new approval).`]}a(lC,"conflictLines");import{spawn as rz}from"node:child_process";var oz=a((e,t)=>{try{let n=rz(e,t,{stdio:"ignore"});return{kill:a(()=>void n.kill(),"kill"),unref:a(()=>n.unref(),"unref"),on:a((r,o)=>void n.on(r,o),"on")}}catch{return null}},"realSpawn");function iz(e,t){return e==="darwin"?{cmd:"caffeinate",args:["-i","-w",String(t)]}:e==="linux"?{cmd:"systemd-inhibit",args:["--what=idle:sleep","--who=maind","--why=a gate or merge run is in progress","tail",`--pid=${t}`,"-f","/dev/null"]}:null}a(iz,"awakeCommand");var od=0,id=null;function sd(e=process.platform,t=process.pid,n=oz){let r=!1;if(od===0){let o=iz(e,t),i=o?n(o.cmd,o.args):null;i&&(i.on("error",()=>{}),i.unref(),id=a(()=>i.kill(),"stop"))}return od+=1,()=>{r||(r=!0,od-=1,od===0&&id&&(id(),id=null))}}a(sd,"keepAwake");import{execFileSync as wI,spawnSync as u3}from"node:child_process";import{existsSync as d3,readFileSync as f3}from"node:fs";import{join as Sd}from"node:path";var sz={"migration-first":"push the migration before the code goes live","code-first":"release and deploy the code before you push the migration","any-order":"either order works"};function cC(e){return e.verdict==="declared"&&e.declared!==null?[`note rollout \u2014 ${e.declared.order}: ${sz[e.declared.order]} (${e.declared.reason})`]:e.verdict==="undeclared"?e.findings.map(t=>`note rollout \u2014 ${t.title}`):[]}a(cC,"rolloutRows");function az(e,t){return t===void 0||t.length===0?!0:e===void 0||e.length===0?!1:e.every(n=>t.some(r=>n===r||n.startsWith(r)))}a(az,"scopeCovers");function lz(e,t){if(t===null)return[{kind:"manifest-removed",subject:""}];let n=[],r=new Map(t.gates.map(i=>[i.id,i]));for(let i of e.gates){let s=r.get(i.id);if(s===void 0){n.push({kind:"gate-removed",subject:i.id});continue}i.blocking&&!s.blocking&&n.push({kind:"gate-non-blocking",subject:i.id}),az(i.paths,s.paths)||n.push({kind:"gate-narrowed",subject:i.id})}let o=new Set(t.versionedDirs);for(let i of e.versionedDirs)o.has(i)||n.push({kind:"versioned-removed",subject:i});return e.requireWorkObject&&!t.requireWorkObject&&n.push({kind:"work-object-off",subject:""}),e.review&&!t.review&&n.push({kind:"review-off",subject:""}),e.tests!==void 0&&t.tests!==void 0&&n.push(...uC(e.tests,t.tests)),n}a(lz,"weakenings");function uC(e,t){let n=[];if(e===null)return n;if(t===null)return[{kind:"tests-off",subject:""}];let r=new Set(e.skip);for(let o of t.skip)r.has(o)||n.push({kind:"tests-skipped",subject:o});for(let[o,i]of Object.entries(t.commands))e.commands[o]!==i&&n.push({kind:"tests-command",subject:o});for(let o of Object.keys(e.commands))t.commands[o]===void 0&&n.push({kind:"tests-command",subject:o});for(let[o,i]of Object.entries(e.inputs??{})){let s=t.inputs?.[o]??[];i.every(l=>s.some(c=>l===c||l.startsWith(c)))||n.push({kind:"tests-inputs",subject:o})}return n}a(uC,"testsWeakenings");function cz(e){if(e===null)return!1;let t=e.trim();return t.length<4?!1:!["1","true","yes","on","skip"].includes(t.toLowerCase())}a(cz,"isManifestReason");function dC(e){if(e.base===null||!e.baseRefResolvable)return{kind:"no-base"};if(e.baseUnparsable)return{kind:"base-unparsable"};let t=e.baseManifest===null?e.headManifest===null?[]:e.headManifest.tests===void 0?[]:uC(e.testsWithoutManifest??null,e.headManifest.tests):lz(e.baseManifest,e.headManifest);return e.baseManifest===null&&t.length===0?{kind:"base-absent"}:t.length===0?{kind:"intact"}:cz(e.overrideReason)?{kind:"overridden",weakenings:t,reason:e.overrideReason.trim()}:{kind:"weakened",weakenings:t}}a(dC,"classifyManifestDrift");var uz={"manifest-removed":a(()=>"the whole manifest is gone \u2014 every declared gate with it","manifest-removed"),"gate-removed":a(e=>`gate "${e}" is gone`,"gate-removed"),"gate-non-blocking":a(e=>`gate "${e}" no longer blocks`,"gate-non-blocking"),"gate-narrowed":a(e=>`gate "${e}" now applies to less than it did`,"gate-narrowed"),"versioned-removed":a(e=>`"${e}" no longer claims a hand-assigned version`,"versioned-removed"),"work-object-off":a(()=>"a branch no longer needs a work object","work-object-off"),"review-off":a(()=>"the review gate is switched off","review-off"),"tests-off":a(()=>"the built-in test gate is switched off","tests-off"),"tests-skipped":a(e=>`the test suite of "${e}" is skipped now`,"tests-skipped"),"tests-command":a(e=>`the test command of "${e}" changed`,"tests-command"),"tests-inputs":a(e=>`the test suite of "${e}" now runs for less than it did (tests.inputs)`,"tests-inputs")};function Ky(e){return uz[e.kind](e.subject)}a(Ky,"weakeningLine");function fC(e,t,n=null){if(e.branch===null)return{kind:"no-branch"};if(e.remoteSha===null)return{kind:"not-shipped",branch:e.branch};if(e.upstream!==null){let r=`${t}/${e.branch}`;if(e.upstream!==r)return{kind:"upstream-mismatch",branch:e.branch,upstream:e.upstream}}return e.localSha===null?{kind:"unknown",reason:"the local HEAD could not be resolved"}:e.localSha===e.remoteSha?{kind:"match",sha:e.localSha}:n!==null&&e.remoteSha===n&&e.behind===0?{kind:"push-pending",branch:e.branch,local:e.localSha,remote:e.remoteSha,ahead:e.ahead}:{kind:"diverged",branch:e.branch,local:e.localSha,remote:e.remoteSha,ahead:e.ahead,behind:e.behind}}a(fC,"classifyParity");function pC(e){return e.kind==="diverged"||e.kind==="upstream-mismatch"||e.kind==="unknown"}a(pC,"parityBlocks");function Wy(e,t,n=!1){let r=["the working tree has uncommitted changes \u2014 the gates below also judge files that are"," NOT in the commit that gets merged. Commit or discard them before relying on this verdict."];if(n&&e.kind==="match")return[`HEAD == ${t}/HEAD (${e.sha.slice(0,9)}), but ${r[0]}`,r[1]];if(n)return[...Wy(e,t,!1),...r];switch(e.kind){case"match":return[`checked state == ${t}/HEAD (${e.sha.slice(0,9)}).`];case"push-pending":return[`checked state == ${t}/${e.branch} (${e.remote.slice(0,9)}) + ${e.ahead??"?"} commit(s) of promote, not pushed yet (${e.local.slice(0,9)}).`," promote pushes exactly this state, and only if every gate below passes."];case"not-shipped":return[`branch ${e.branch}: no remote yet \u2014 the gate checks the local state.`];case"no-branch":return["detached HEAD \u2014 no remote counterpart to compare against."];case"upstream-mismatch":return[`branch ${e.branch} tracks ${e.upstream}, not ${t}/${e.branch}.`,` A merge takes ${t}/${e.branch}. Every verdict below would describe a different tree.`,` Fix: git branch --set-upstream-to=${t}/${e.branch} ${e.branch}`];case"diverged":{let o=["the gate would NOT check the state that gets merged:",` local HEAD ${e.local.slice(0,9)}${e.ahead!==null?` (${e.ahead} commit(s) ahead)`:""}`,` remote ${t}/${e.branch} ${e.remote.slice(0,9)}${e.behind!==null?` (${e.behind} commit(s) ahead)`:""}`," A merge takes the REMOTE state. Align first:"];return e.ahead!==0&&e.behind!==0?(o.push(" (history was rewritten \u2014 a plain push is rejected and a pull would bring the"," replaced commit back. On your OWN feature branch:)",` git push --force-with-lease ${t} ${e.branch}`),o):(e.ahead!==0&&o.push(` git push ${t} ${e.branch}`),e.behind!==0&&o.push(` git pull --ff-only ${t} ${e.branch}`),o)}case"unknown":return[`could not determine whether the checked state matches ${t}: ${e.reason}.`," This is not a pass \u2014 a verdict about the wrong tree is worse than none."]}}a(Wy,"parityLines");import{execFileSync as b9}from"node:child_process";import{readFileSync as k9}from"node:fs";import{join as EO}from"node:path";var Ri=".";function ad(e){let t=e.lastIndexOf("/");return t<0?Ri:e.slice(0,t)}a(ad,"dirOf");function qy(e,t){return e===Ri?t:`${e}/${t}`}a(qy,"joinDir");function Ei(e,t){return t===Ri||e===t||e.startsWith(`${t}/`)}a(Ei,"isUnder");function dz(e,t){return t===Ri?e:e===t?"":e.slice(t.length+1)}a(dz,"relativeTo");function Vy(e){if(typeof e!="string")return!1;let t=e.trim();return t.length===0?!1:!/no test specified/i.test(t)}a(Vy,"isRealTestScript");function fz(e){let t=e.split(`
420
420
  `),n=a(r=>r.trim().replace(/^(['"])(.*)\1$/,"$2"),"unquote");for(let r=0;r<t.length;r+=1){let o=/^packages\s*:\s*(.*)$/.exec(t[r]);if(!o)continue;let i=o[1].replace(/\s+#.*$/,"").trim();if(i.startsWith("["))return i.replace(/^\[/,"").replace(/\]\s*$/,"").split(",").map(n).filter(c=>c.length>0);if(i.length>0)return null;let s=[];for(let l=r+1;l<t.length;l+=1){let c=t[l];if(c.trim().length===0||/^\s*#/.test(c))continue;let u=/^\s*-\s+(.*)$/.exec(c);if(!u){if(/^\S/.test(c))break;continue}let d=n(u[1].replace(/\s+#.*$/,""));d.length>0&&s.push(d)}return s}return null}a(fz,"parsePnpmWorkspace");function pz(e){let t=e.workspaces,n=Array.isArray(t)?t:t!==null&&typeof t=="object"&&Array.isArray(t.packages)?t.packages:null;return n===null?null:n.filter(r=>typeof r=="string"&&r.trim().length>0)}a(pz,"workspacesField");function mC(e,t){let n=e.trim().replace(/^\.\//,"").replace(/\/+$/,"");if(n.length===0)return!1;let r="";for(let o=0;o<n.length;o+=1){let i=n[o];if(i==="*")n[o+1]==="*"?n[o+2]==="/"?(r+="(?:.*/)?",o+=2):(r+=".*",o+=1):r+="[^/]*";else if(i==="?")r+="[^/]";else if(i==="{"){let s=n.indexOf("}",o);if(s<0)r+="\\{";else{let l=n.slice(o+1,s).split(",").map(c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));r+=`(?:${l.join("|")})`,o=s}}else r+=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${r}$`).test(t)}a(mC,"matchesWorkspacePattern");function mz(e,t){let n=!1;for(let r of e)r.startsWith("!")?mC(r.slice(1),t)&&(n=!1):mC(r,t)&&(n=!0);return n}a(mz,"isMember");var gC=[["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["bun.lockb","bun"],["bun.lock","bun"],["package-lock.json","npm"],["npm-shrinkwrap.json","npm"]];function hz(e){let t=e.packageManager;if(typeof t!="string")return null;let n=/^(pnpm|npm|yarn|bun)@/.exec(t.trim());return n?n[1]:null}a(hz,"managerField");function ld(e){return e==="package.json"||e==="pnpm-workspace.yaml"||gC.some(([t])=>t===e)||[".npmrc",".pnpmfile.cjs",".yarnrc",".yarnrc.yml","bunfig.toml"].includes(e)?!0:/^tsconfig(\..+)?\.json$/.test(e)}a(ld,"isWorkspaceGlobalFile");function gz(e){if(e===null)return null;try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}a(gz,"parseJsonObject");function hC(e){return e===Ri?0:e.split("/").length}a(hC,"depth");function yC(e){let t=new Set(e.tracked),n=[];for(let m of e.tracked){if(m!=="package.json"&&!m.endsWith("/package.json")||m.split("/").includes("node_modules"))continue;let h=gz(e.read(m));h!==null&&n.push({dir:ad(m),pkg:h})}let r=new Map;for(let m of n){let h=qy(m.dir,"pnpm-workspace.yaml"),y=(t.has(h)?fz(e.read(h)??""):null)??pz(m.pkg);y!==null&&y.length>0&&r.set(m.dir,y)}let o=[...r.keys()].sort((m,h)=>hC(h)-hC(m)),i=new Map;for(let m of n){let h=m.dir;for(let k of o)if(!(k===m.dir||!Ei(m.dir,k))&&mz(r.get(k),dz(m.dir,k))){h=k;break}i.set(m.dir,h)}let s=new Set;for(let[m,h]of i)h!==m&&s.add(h);let l=new Map(n.map(m=>[m.dir,m])),c=new Map,u=a(m=>{let h=c.get(m);if(h)return h;let k=null,y=m;for(;y!==null&&k===null;){let _=l.get(y);if(k=_?hz(_.pkg):null,k===null){let w=gC.find(([v])=>t.has(qy(y,v)));w?k=w[1]:t.has(qy(y,"pnpm-workspace.yaml"))&&(k="pnpm")}y=y===Ri?null:ad(y)}let b=k??"npm";return c.set(m,b),b},"managerOf"),d=new Map;for(let m of n){let h=typeof m.pkg.name=="string"&&m.pkg.name.trim().length>0?m.pkg.name.trim():null;if(h===null)continue;let k=i.get(m.dir),y=d.get(k)??new Map;y.has(h)||y.set(h,m.dir),d.set(k,y)}let f=["dependencies","devDependencies","peerDependencies","optionalDependencies"],p=n.map(m=>{let h=i.get(m.dir),k=d.get(h)??new Map,y=new Set;for(let w of f){let v=m.pkg[w];if(!(v===null||typeof v!="object"||Array.isArray(v)))for(let E of Object.keys(v)){let x=k.get(E);x!==void 0&&x!==m.dir&&y.add(x)}}let b=m.pkg.scripts,_=b!==null&&typeof b=="object"&&!Array.isArray(b)?b.test:void 0;return{dir:m.dir,name:typeof m.pkg.name=="string"&&m.pkg.name.trim().length>0?m.pkg.name.trim():null,root:h,manager:u(h),testScript:Vy(_)?_.trim():null,deps:[...y].sort(),isWorkspaceRoot:s.has(m.dir)}});return p.sort((m,h)=>m.dir<h.dir?-1:m.dir>h.dir?1:0),{packages:p}}a(yC,"discoverWorkspace");function bC(e){return`${e} run test`}a(bC,"testCommandFor");function cd(e){return e.packages.filter(t=>t.testScript===null?!1:t.isWorkspaceRoot?!e.packages.some(n=>n.root===t.dir&&n.dir!==t.dir&&n.testScript!==null):!0)}a(cd,"suiteUnits");function yz(e,t){let n=null;for(let r of t)Ei(e,r.dir)&&(n===null||r.dir.length>n.dir.length||n.dir===".")&&(n=r);return n}a(yz,"ownerOf");function kC(e,t){let n=new Set([e.dir]),r=[e];for(;r.length>0;){let o=r.pop();for(let i of o.deps){if(n.has(i))continue;n.add(i);let s=t.get(i);s&&r.push(s)}}return[...n].sort()}a(kC,"closureOf");function _C(e,t){return!t||t.length===0?e:[...new Set([...e,...t.map(n=>n.replace(/\/+$/,"")).filter(n=>n.length>0)])].sort()}a(_C,"withInputs");function wC(e,t,n){let r=new Map(e.packages.map(m=>[m.dir,m])),o=new Map;for(let m of t){let h=ad(m),k=r.get(h);if(k?.isWorkspaceRoot&&ld(m.slice(m.lastIndexOf("/")+1)))for(let b of e.packages)b.root===k.dir&&!o.has(b.dir)&&o.set(b.dir,`${m} changed`);let y=yz(m,e.packages);y&&o.set(y.dir,"changed in this diff")}let i=[...o.keys()];for(;i.length>0;){let m=i.pop();for(let h of e.packages)o.has(h.dir)||!h.deps.includes(m)||(o.set(h.dir,`depends on ${m}`),i.push(h.dir))}for(let[m,h]of Object.entries(n.inputs??{})){if(o.has(m))continue;let k=t.find(y=>h.some(b=>y===b||y.startsWith(b)));k!==void 0&&o.set(m,`${k} changed (a declared input)`)}let s=cd(e),l=new Set(s.map(m=>m.dir)),c=[],u=[],d=new Set(n.skip),f=a(m=>{d.has(m.dir)?u.push(m.dir):c.push(m)},"take");for(let m of s){let h=o.get(m.dir);if(h===void 0&&m.isWorkspaceRoot){let k=e.packages.find(y=>y.root===m.dir&&y.dir!==m.dir&&o.has(y.dir));k&&(h=`${k.dir} changed`)}h!==void 0&&f({dir:m.dir,name:m.name,command:n.commands[m.dir]??bC(m.manager),why:h,closure:_C(m.isWorkspaceRoot?[m.dir]:kC(m,r),n.inputs?.[m.dir]),root:m.root,manager:m.manager,custom:n.commands[m.dir]!==void 0})}for(let[m,h]of Object.entries(n.commands)){if(l.has(m))continue;let k=r.get(m),y=k?o.get(m):t.some(b=>Ei(b,m))?"changed in this diff":void 0;y!==void 0&&f({dir:m,name:k?.name??null,command:h,why:y,closure:_C(k?kC(k,r):[m],n.inputs?.[m]),root:k?.root??null,manager:k?.manager??null,custom:!0})}c.sort((m,h)=>m.dir<h.dir?-1:m.dir>h.dir?1:0);let p=new Set([...l,...Object.keys(n.commands)]).size;return{suites:c,skipped:u.sort(),known:p}}a(wC,"affectedSuites");import{execFileSync as bz}from"node:child_process";import{createHash as kz}from"node:crypto";import{cpSync as _z,existsSync as Ma,mkdirSync as EC,readFileSync as wz,writeFileSync as vz}from"node:fs";import{dirname as AC,isAbsolute as xz,join as wo,resolve as Yy}from"node:path";function Ai(e){return`tests:${e}`}a(Ai,"testsId");function Na(e,t){return e.timedOut?Ea(t):e.exit===null?"ended without an exit code":`exit ${e.exit}`}a(Na,"runDetail");async function vC(e,t,n,r=null){let o=new Map,i=[],s=0;for(let l of e){if(r!==null&&s>=r){o.set(l.dir,{kind:"not-run"});continue}n.progress(Ai(l.dir));let c=await n.run(l,t);if(s+=c.ms,c.ok){o.set(l.dir,{kind:"green",ms:c.ms});continue}if(c.timedOut){i.push({suite:l,run:c,ms:c.ms});continue}let u=await n.run(l,t);if(u.ok){o.set(l.dir,{kind:"flaky",ms:c.ms+u.ms,run:c});continue}i.push({suite:l,run:u,ms:c.ms+u.ms})}if(i.length>0){let l=await n.compareWithBase(i.map(c=>c.suite));for(let c of i)o.set(c.suite.dir,{kind:"red",ms:c.ms,run:c.run,base:l.get(c.suite.dir)??{kind:"unavailable",reason:"the base run gave no answer"}})}return o}a(vC,"runSuites");function xC(e,t,n,r,o=null){let i=Ai(e.dir),s=`\`${e.command}\` in ${e.dir}`;if(t.kind==="not-run")return{id:i,verdict:"not-checked",blocking:!1,note:`not run \u2014 the suites before it used the ${o??"?"} minutes the built-in test gate takes by default. Set "tests": true in .maind/gates.json to run every affected suite, or name what to skip under "tests.skip"`};if(t.kind==="green")return{id:i,verdict:"pass",blocking:!0,durationMs:t.ms};if(t.kind==="flaky")return{id:i,verdict:"fail",blocking:!1,durationMs:t.ms,note:`flaky: ${s} failed once (${Na(t.run,r)}) and passed on the second run`};let l=Na(t.run,r),c=t.run.timedOut?{timedOut:!0}:{},u=t.base;return u.kind==="green"?{id:i,verdict:"fail",blocking:!0,durationMs:t.ms,...c,note:`${s} is red on this branch (${l}) and green on ${n} \u2014 this branch broke it`}:u.kind==="new"?{id:i,verdict:"fail",blocking:!0,durationMs:t.ms,...c,note:`${s} is red (${l}); the suite does not exist on ${n}, so it is this branch's own`}:u.kind==="red"?{id:i,verdict:"fail",blocking:!1,durationMs:t.ms,...c,note:`${s} is red here (${l}) and on ${n} as well`+(u.seen?` (seen ${u.seen.slice(0,16).replace("T"," ")} UTC)`:"")+" \u2014 not caused by this branch"}:{id:i,verdict:"fail",blocking:!1,durationMs:t.ms,...c,note:`${s} is red (${l}), and it could not be compared with ${n}: ${u.reason}`}}a(xC,"suiteResult");function SC(e){return e.kind==="green"||e.kind==="not-run"?!1:e.kind==="flaky"?!0:e.base.kind!=="red"}a(SC,"showsOutput");function Da(e){return{id:"tests",verdict:"not-checked",blocking:!1,note:e}}a(Da,"noSuitesResult");var Sz=24*60*6e4,ud=10*6e4,Rz="maind/tests-base.json";function kn(e,t){try{return bz("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:12e4,maxBuffer:64*1024*1024}).trim()}catch{return null}}a(kn,"git");function Ez(e,t){return t==="."?`${e}^{tree}`:`${e}:${t}`}a(Ez,"treeish");function Az(e,t){return e==="pnpm"?"pnpm install --frozen-lockfile":e==="yarn"?t?"yarn install --immutable":"yarn install --frozen-lockfile":e==="bun"?"bun install --frozen-lockfile":"npm ci"}a(Az,"frozenInstall");function $z(e,t,n){if(!n(e.dir))return!1;if(e.custom)return!0;let r=t(e.dir==="."?"package.json":`${e.dir}/package.json`);if(r===null)return!1;try{let o=JSON.parse(r);return Vy(o.scripts?.test)}catch{return!1}}a($z,"existsOnBase");function Tz(e,t,n){let r=[n.dir,n.command];for(let o of n.closure){let i=kn(e,["rev-parse","--verify","--quiet",Ez(t,o)]);if(i===null)return null;r.push(`${o}=${i}`)}if(n.root!==null){let o=kn(e,n.root==="."?["ls-tree",t]:["ls-tree",t,`${n.root}/`]);if(o===null)return null;for(let i of o.split(`
421
421
  `)){let s=/^\d+ blob ([0-9a-f]+)\t(.+)$/.exec(i);if(!s)continue;let l=s[2].slice(s[2].lastIndexOf("/")+1);ld(l)&&r.push(`${l}=${s[1]}`)}}return kz("sha256").update(r.join(`
422
422
  `)).digest("hex")}a(Tz,"baseKey");function $C(e){let t=kn(e,["rev-parse","--git-common-dir"]);return t?wo(xz(t)?t:Yy(e,t),Rz):null}a($C,"redLogPath");function Cz(e,t){let n={v:1,red:{}},r=$C(e);if(!r)return n;try{let o=JSON.parse(wz(r,"utf8"));if(o.v!==1||o.red===null||typeof o.red!="object")return n;let i={};for(let[s,l]of Object.entries(o.red)){let c=Date.parse(l?.at??"");Number.isFinite(c)&&t-c<=Sz&&t>=c&&(i[s]=l)}return{v:1,red:i}}catch{return n}}a(Cz,"readRedLog");function Oz(e,t){let n=$C(e);if(n)try{EC(AC(n),{recursive:!0}),vz(n,`${JSON.stringify(t,null,2)}
@@ -535,7 +535,7 @@ ${i.stderr??""}`.split(`
535
535
  `).filter(Boolean),l=Ht(t);return!(l.kind==="loaded"&&l.versioned.some(u=>u.numbering==="promote"&&Yt(u,s)))&&Sy($a(e,n,o.regenerate).steps,s).length===0?null:{name:"rebase",verdict:"fail",detail:`${n} moved since ${r} forked, and promote would bring it in with a merge commit before assigning a number \u2014 a rebase merge gets none. Rebase ${r} onto ${n} and push, or merge with --merge-method squash or merge.`}}a(ZN,"rebaseCheckRow");function PN(e,t,n,r,o){let i=e.mergeCommit(t,r);if(!i)return{kind:"unreadable"};let s=bi(t,i),l="versioned"in s?s.versioned:[];if(l.length===0)return{kind:"none"};let c=JN(t,i,o),u=(P("git",["-c","core.quotepath=off","diff","--name-only",c,i],t)??"").split(`
536
536
  `).filter(Boolean),d=kT({packages:l,mergedFiles:u,versionAt:a((f,p)=>br(el(t,f==="before"?c:i,`${p}/package.json`)),"versionAt"),tagExists:a(f=>(P("git",["ls-remote","--tags",n,`refs/tags/${f}`],t)??"")!=="","tagExists")});return{kind:"found",sha:i,found:d}}a(PN,"mergedReleases");async function X6(e){let{args:t,deps:n,root:r,target:o,cfg:i,base:s,fx:l,pr:c}=e,u=o.branch,d=l.ops,f=c.mergedAt?.slice(0,10)??null,p=n.worktreeList(r),m=p[0]?.path??r;for(let x of _T({prNumber:c.number,mergedOn:f,branch:u}))R(x);let h=t.closesObject===!0?"closes":t.progressOnly===!0?"progress":void 0;if(t.check===!0||t.yes!==!0){let x=d.remoteSlugFor(r),O=P("git",["config","--get",`branch.${u}.maindObject`],r),T=P("git",["config","--get",`branch.${u}.maindObjectKey`],r),S=O===null&&x?await Ln(l.ref(x,c.number)).catch(()=>null):null,A=O??S?.id??null;if(ra(A,h).kind==="missing"){for(let B of Ry({prNumber:c.number,branch:u,object:T??S?.key??A??"?"}))R(B);return 1}let C=wi(Ie("promote",o),{...t.closesObject?{closesObject:!0}:{},...t.progressOnly?{progressOnly:!0}:{}},{cwd:m,cliVersion:fe});n.fetch(r,i.remote);let N=PN(l,r,i.remote,c.number,u);if(N.kind==="found"){for(let B of N.found.releases)R(`promote tags ${B.tag} on ${N.sha.slice(0,9)} (${B.name} ${B.from} -> ${B.to}).`);for(let B of N.found.tagged)R(`${B} is already tagged.`);for(let B of Ey(N.found.unnumbered,c.number))R(B)}for(let B of wT(C,N.kind==="found"&&N.found.releases.length>0))R(B);return t.check===!0?0:1}let k=await Dg(P("git",["config","--get",`branch.${u}.maindObject`],r),{prNumber:a(()=>c.number,"prNumber"),slug:a(()=>d.remoteSlugFor(r),"slug"),ref:l.ref,lookup:Ln,write:a((x,O)=>{P("git",["config",`branch.${u}.maindObject`,x],r),O&&P("git",["config",`branch.${u}.maindObjectKey`,O],r)},"write")});k.kind==="recovered"&&R(`${u} had no local binding, but ${k.ref} is linked to ${k.key??k.objectId} \u2014 binding restored.`);let y=P("git",["config","--get",`branch.${u}.maindObjectKey`],r)??(k.kind==="recovered"?k.key:null),b=ra(k.kind==="unbound"?null:k.objectId,h);if(b.kind==="missing"){for(let x of Ry({prNumber:c.number,branch:u,object:y??b.objectId}))R(x);return 1}if(k.kind==="bound"){let x=await oa(k.objectId,{prNumber:a(()=>c.number,"prNumber"),slug:a(()=>d.remoteSlugFor(r),"slug"),ref:l.ref,lookup:Ln,link:a(async(O,T)=>{await Et(Rt(["link","--object",O,"--ref",T]))},"link")});if(x.kind==="mismatch"){for(let O of ci({branch:u,phase:"promote",prNumber:c.number,ref:x.ref,bound:{id:k.objectId,key:y},other:x.other}))R(O);return 1}}n.fetch(r,i.remote);let _=VN({root:r,fx:l,remote:i.remote,base:s,branch:u,objectKey:y}),w=d.remoteSlugFor(r),v=!1;w?f?(v=await YN(l.ref(w,c.number),f,b.completes,_),v&&P("git",["config",`branch.${u}.${Xu}`,String(c.number)],r)):R(`the forge did not say when PR #${c.number} merged \u2014 the merge was not reported (a report needs its date).`):R("the repository path could not be read from the forge \u2014 the merge was not reported.");let E=PN(l,r,i.remote,c.number,u);if(E.kind==="found"){for(let x of E.found.tagged)R(`${x} is already tagged.`);E.found.releases.length>0&&zN(n,r,i.remote,E.sha,E.found.releases,c.number);for(let x of Ey(E.found.unnumbered,c.number))R(x)}else E.kind==="unreadable"&&R(`the merge commit of PR #${c.number} could not be read \u2014 no release tag was checked.`);return R(`finished PR #${c.number}${f?` (merged ${f})`:""}`+(v?b.completes?" \u2014 reported as completion":" \u2014 reported as progress, the object stays open":" \u2014 the merge is NOT reported (see above)")),XN({deps:n,root:r,target:o,cfg:i,base:s,wt:o.worktree,mergedFiles:_.mergedFiles,trees:p,mainRoot:m}),process.stdout.write(`${c.number}
537
537
  `),0}a(X6,"finishMergedElsewhere");async function J6(e,t,n,r,o){if(n.length===0)return;let i=await Ut(n.map(s=>s.key));if(!i.ok){o(`could not resolve ${n.map(s=>s.key).join(", ")} (${i.reason}) \u2014 their merge was not reported.`);return}for(let s of n){let l=i.refs.find(f=>f.ident===s.key);if(!l?.id){o(`${s.key} is named after a closing word but resolves to no visible object \u2014 nothing was reported for it.`);continue}let c=["report","--event","merge","--ref",e,"--object",l.id,"--occurred-on",t,"--completes"],u=LN(Ar(BN(),"maind-fanout-"));if(s.documents.length>0){let f=Ar(u,"documents.json");qd(f,JSON.stringify(s.documents)),c.push("--documents-json",f)}if(r.kind==="ok"){let f=Ar(u,"doc-decision.json");qd(f,JSON.stringify(r.decision)),c.push("--doc-decision-json",f)}let d=await Et(Rt(c));FN(u,{recursive:!0,force:!0}),d!==0&&(o(`the merge report for ${s.key} failed. Report it manually:`),o(` work_object_report_event { event: "merge", ref: "${e}", object_id: "${l.id}", occurred_on: "${t}", completes_object: true }`))}}a(J6,"reportFanOut");async function QN({args:e,root:t,cfg:n,deps:r,target:o,branch:i,base:s,fx:l,out:c}){let u=$d(),d=new Li($=>process.stderr.write($),u.style,u.width,u.live);Hi(d),Cu($=>d.objectOutput($,"unknown"));let f=a(($,z="Not merged")=>(d.callout("fail",z,Rb($)),1),"halt");d.header(i,`${n.remote}/${s}`,e.check===!0?"maind feature promote --check":"maind feature promote");let p=c.prFor(t,i);if(p?.state==="MERGED"&&bT({branchExists:r.branchExists(t,i),reportedPr:P("git",["config","--get",`branch.${i}.${Xu}`],t),prNumber:p.number}))return X6({args:e,deps:r,root:t,target:o,cfg:n,base:s,fx:l,pr:p});if(p?.state==="MERGED"){let $=r.exists(o.worktree)||r.branchExists(t,i),z=r.worktreeList(t)[0]?.path??t;for(let ae of xA({prNumber:p.number,mergedOn:p.mergedAt?.slice(0,10)??null,leftover:$,cleanup:xt(z,Ie("done",o))}))R(ae);return process.stdout.write(`${p.number}
538
- `),0}if(e.check===!0){let $=[],z={...e.closesObject?{closesObject:!0}:{},...e.progressOnly?{progressOnly:!0}:{},...e.mergeMethod?{mergeMethod:e.mergeMethod}:{}},ae={cwd:r.exists(o.worktree)?o.worktree:t,cliVersion:fe},he=wi(Ie("promote",o),{...z,...e.wait?{wait:!0}:{}},ae),Re;p?p.state!=="OPEN"?$.push({name:"pull-request",verdict:"fail",detail:`PR #${p.number} is ${p.state.toLowerCase()}`}):$.push({name:"pull-request",verdict:"ok",detail:`PR #${p.number}`}):$.push({name:"pull-request",verdict:"fail",detail:`no pull request for ${i} \u2014 ship first: ${Ie("ship",o)}`});let Qe=c.remoteSlugFor(t),Se=p&&Qe?l.ref(Qe,p.number):null,D=P("git",["config","--get",`branch.${i}.maindObject`],t),U=P("git",["config","--get",`branch.${i}.maindObjectKey`],t),Q=Se?await Ln(Se).catch(()=>null):null,ue=D??Q?.id??null;!D&&Q&&$.push({name:"binding",verdict:"note",detail:`no local binding \u2014 promote restores it from the PR link (${Q.key??Q.id})`}),ra(ue,e.closesObject===!0?"closes":e.progressOnly===!0?"progress":void 0).kind==="missing"?$.push({name:"completion",verdict:"fail",detail:"the branch is bound to a work object \u2014 say --closes-object or --progress-only"}):ue&&$.push({name:"completion",verdict:"ok",detail:e.closesObject?"closes the object":"progress only"});let He=Ag({flag:e.mergeMethod??null,configured:n.mergeMethod??null,forge:c.mergeMethods(t)});if(He.kind==="not-allowed")$.push({name:"merge-method",verdict:"fail",detail:Tg(He)[0]});else if($.push({name:"merge-method",verdict:"ok",detail:$g(He)}),He.method==="rebase"){let ee=ZN(t,r.exists(o.worktree)?o.worktree:t,`${n.remote}/${s}`,i,n);ee&&$.push(ee)}let ge=Ng({required:nl(r.exists(o.worktree)?o.worktree:t),branch:i,boundObject:ue,overrideReason:process.env[li]??null,promoteCommand:Ie("promote",o)});ge&&$.push({name:"work-object",verdict:"fail",detail:ge[0]??"a work object is required"}),D&&Se&&(Q===null?$.push({name:"pr-link",verdict:"note",detail:`${Se} is not linked yet \u2014 promote links it to ${U??D}`}):Q.id!==D?$.push({name:"pr-link",verdict:"fail",detail:ci({branch:i,phase:"promote",prNumber:p?.number??null,ref:Se,bound:{id:D,key:U},other:Q})[0].replace(/ — the merge would be reported against the wrong object\.$/,"")}):$.push({name:"pr-link",verdict:"ok",detail:`${Se} \u2192 ${Q.key??Q.id}`}));let q=o.worktree;if(r.exists(q)){let ee=Oa(q,`${n.remote}/${s}`,`${n.remote}/${i}`);for(let _e of Ia(ee,i,rt(q)))$.push({name:"interrupted-run",verdict:ee.kind==="failed"?"fail":"note",detail:_e})}r.exists(q)?r.isDirty(q)!==!1?$.push({name:"worktree",verdict:"fail",detail:`${q} has uncommitted changes \u2014 the gate would judge files that are not in the commit`}):$.push({name:"worktree",verdict:"ok",detail:"clean"}):$.push({name:"worktree",verdict:o.byBranch?"note":"fail",detail:o.byBranch?`promote checks ${i} out into ${q} for the gate`:`no worktree at ${q}`});let Pe=p?.headSha??null,Ye=P("git",["rev-parse","HEAD"],r.exists(q)?q:t);Pe&&Ye&&Ye!==Pe?$.push({name:"pushed",verdict:"fail",detail:`local ${Ye.slice(0,9)}, pull request ${Pe.slice(0,9)} \u2014 push first: ${Ie("ship",o)}`}):Pe&&$.push({name:"pushed",verdict:"ok",detail:Pe.slice(0,9)}),r.fetch(t,n.remote);let be=`${n.remote}/${s}`;for(let ee of lr(r.exists(q)?q:t,{baseRef:be}).findings)$.push({name:"sql-base-overlap",verdict:"note",detail:ee.title});if(ue&&Se&&Pe&&p){let ee=Qt(ho,{sleep:a(Ee=>new Promise(Be=>setTimeout(Be,Ee)),"sleep"),note:R}),_e=await ee("work_object_merge_approval_state",{objectId:ue,ref:Se,headSha:Pe}),K=_e.kind==="ok"?Fn(_e.body):null,re=yo(To(),K?.objectKey??null),ie=null;if(K&&(K.state==="none"||K.state==="pending")){let Ee=tn(r.exists(q)?q:t,Pe,be,{note:R});ie=await ju(ee,{objectId:ue,ref:Se,headSha:Pe,base:s},{links:Ee.links,stopLine:Ta(Ee)})}$.push(RT(K??{failure:_e.kind==="unknown_tool"?"the server cannot read merge approvals yet":_e.kind==="failed"||_e.kind==="invalid_params"?_e.reason:String(_e.body.error??"unreadable answer")},{prNumber:p.number,url:re,wait:Pb(e,process.stdin.isTTY===!0&&process.stdout.isTTY===!0),carry:ie})),K?.state==="approved"||ie?.kind==="carries"?Re={kind:"given"}:K&&(K.state==="none"||K.state==="pending")&&ie?.kind!=="declined"&&(Re={kind:"asks",url:re,asked:K.state==="pending",waitCommand:wi(Ie("promote",o),{...z,wait:!0},ae)})}let Z=Ca(r.exists(q)?q:t,be,i),$e=Z.verdict;if(r.exists(q)){let ee=Ht(q),_e=ee.kind==="loaded"?ee.versioned.filter(re=>re.numbering==="promote"):[],K=GN(Yu(q,be,_e,$o()),$e.kind==="conflict"||Z.ownOnly.length>0);K&&$.push(K)}if($.push(HN(i,Z,be)),p){let ee=_i(p.title??"",xa(c.baseSubjects(t,be)),c.branchCommits(t,be,i));$.push(ee.kind==="ok"?{name:"title",verdict:"ok",detail:p.title??""}:{name:"title",verdict:"fail",detail:`"${ee.title}" is not a conventional commit${ee.suggestion?` \u2014 suggestion: "${ee.suggestion}"`:""}`})}if(r.exists(q)&&$e.kind!=="conflict"&&r.isDirty(q)===!1){let ee=$a(t,`${n.remote}/${s}`,n.regenerate);ee.differs&&$.push({name:"regenerate",verdict:"note",detail:Uy(`${n.remote}/${s}`,t)});let _e=Ht(q),K=P("git",["rev-parse","HEAD"],q);K&&Gy(q,K,"check");let re=Dy({wt:q,root:t,branch:i,baseRef:be,packages:_e.kind==="loaded"?_e.versioned.filter(ie=>ie.numbering==="promote"):[],regenerate:ee.steps,method:He.kind==="not-allowed"?"squash":He.method,utcTodayIso:$o(),phase:"check",note:a(ie=>d.say(ie),"note")});if(re.kind==="stop")$.push({name:"merge-result",verdict:"fail",detail:re.lines.join(" ")});else{if(n.postCreate.length>0){let Be=ko(q);Be.stale&&($.push({name:"install",verdict:"note",detail:`${Be.reason} \u2014 ran postCreate for the merge result`}),Er(n,q)||$.push({name:"install",verdict:"note",detail:"postCreate failed \u2014 a red check below may come from a stale install"}))}d.open("Gate");let ie=e.overrides?null:Ty(q,be,{postCreate:n.postCreate.length>0,cli:fe,branchHead:K});d.progress("running the gate on the merge result (as promote would)");let Ee=await KN(q,ie,{json:!1,overrides:e.overrides,...K?{pushPendingFrom:K}:{},prChecks:jb(l,t,i,()=>Si(t,be,n.ignoreChecks??[]))},d,"check");Ee!==0?Zu(q):ie!==null&&Oy(q,ie,"check",Date.now()),$.push(Ee===0?{name:"gate",verdict:"ok",detail:`every declared gate passed on the merge result with ${be}`}:{name:"gate",verdict:"fail",detail:`red on the merge result with ${be} \u2014 see the gate output above`})}if(K&&P("git",["rev-parse","HEAD"],q)!==K){let ie=zu(q,K);ie.ok||$.push({name:"merge-result",verdict:"fail",detail:`could not move ${i} back to ${K.slice(0,9)} (${ie.output}) \u2014 run: cd ${rt(q)} && git reset --keep ${K}`})}K&&P("git",["rev-parse","HEAD"],q)===K&&Hn(q)}if(p){$.push(l.checksRow(t,i,s));let ee=new Set((e.checkOverrides??[]).map(K=>K.gate)),_e=HI((l.checkStates(t,i)??null)?.filter(K=>!ee.has(K.name)&&!ee.has(K.job??K.name))??null,l.requiredNames(t,i,s),Si(t,`${n.remote}/${s}`,n.ignoreChecks??[]));_e&&$.push(_e),ee.size>0&&$.push({name:"other-checks",verdict:"note",detail:`--override names ${[...ee].join(", ")} \u2014 promote verifies that the object is open before it accepts a red check`})}if(r.exists(q)){let ee=await ka(q,`${n.remote}/${s}`,ue??null);if(ee.kind==="skipped")$.push({name:"landed-since",verdict:"note",detail:`not checked: ${ee.reason}`});else for(let K of ee.lines)$.push({name:"landed-since",verdict:"note",detail:K});let _e=U??Q?.key??null;if(ue&&_e){for(let K of await ga(q,`${n.remote}/${s}`,{id:ue,key:_e}))$.push({name:"lesson-check",verdict:"note",detail:K});for(let K of await ya(q,`${n.remote}/${s}`,{id:ue,key:_e}))$.push({name:"documentation",verdict:"note",detail:K});for(let K of await Fu(q,i,{id:ue,key:_e}))$.push({name:"plan",verdict:"note",detail:K})}}d.open("Checks");for(let ee of $)d.row(ee.verdict,ee.name,ee.detail);let tt=ST($,he,Re);return d.callout(tt.tone,tt.title,tt.parts),tt.exitCode}if(e.yes!==!0)return f([`promote merges ${i} into ${s}. Re-run with --yes when you mean it.`],"Not started");let m=await Dg(P("git",["config","--get",`branch.${i}.maindObject`],t),{prNumber:a(()=>c.prFor(t,i)?.number??null,"prNumber"),slug:a(()=>c.remoteSlugFor(t),"slug"),ref:l.ref,lookup:Ln,write:a(($,z)=>{P("git",["config",`branch.${i}.maindObject`,$],t),z&&P("git",["config",`branch.${i}.maindObjectKey`,z],t)},"write")});m.kind==="recovered"&&R(`${i} had no local binding, but ${m.ref} is linked to ${m.key??m.objectId} \u2014 binding restored.`);let h=ra(m.kind==="unbound"?null:m.objectId,e.closesObject===!0?"closes":e.progressOnly===!0?"progress":void 0);if(h.kind==="missing"){let $=P("git",["config","--get",`branch.${i}.maindObjectKey`],t);return f(vA(i,$??h.objectId),"Not started")}let k=a(async $=>{if(m.kind==="unbound")return;let z=c.prFor(t,i),ae=c.remoteSlugFor(t);if(!z?.headSha||!ae||z.state!=="OPEN")return;let he=$==="gate"?FT(rl):[];await Et(Rt(["report","--event","gate","--ref",l.ref(ae,z.number),"--sha",z.headSha,"--stopped-at",$,...he]))},"reportStop"),y=a(async($,z,ae="Not merged")=>(f(z,ae),await k($),1),"haltAt"),b=Ag({flag:e.mergeMethod??null,configured:n.mergeMethod??null,forge:c.mergeMethods(t)});if(b.kind==="not-allowed")return y("method_not_allowed",Tg(b),"Not started");b.source!=="default"&&R($g(b));let _=Ng({required:nl(r.exists(o.worktree)?o.worktree:t),branch:i,boundObject:m.kind==="unbound"?null:m.objectId,overrideReason:process.env[li]??null,promoteCommand:Ie("promote",o)});if(_)return f(_,"Not started");if(m.kind==="bound"){let $=await oa(m.objectId,{prNumber:a(()=>c.prFor(t,i)?.number??null,"prNumber"),slug:a(()=>c.remoteSlugFor(t),"slug"),ref:l.ref,lookup:Ln,link:a(async(z,ae)=>{await Et(Rt(["link","--object",z,"--ref",ae]))},"link")});if($.kind==="mismatch")return f(ci({branch:i,phase:"promote",prNumber:c.prFor(t,i)?.number??null,ref:$.ref,bound:{id:m.objectId,key:P("git",["config","--get",`branch.${i}.maindObjectKey`],t)},other:$.other}),"Not started")}let w=o.worktree;if(!r.exists(w)&&o.byBranch){let $=NA(r,{repoRoot:t,branch:i,path:w,remote:n.remote});switch($.kind){case"ok":{R(`checked ${i} out into ${w} for the gate.`);let z=tl(t,w,fi(t,w));z.length>0&&R(`provisioned ${z.length} declared path(s) from the main checkout.`),Er(n,w);break}case"no-branch":return f([`${i} exists neither locally nor as ${$.remote}/${i} \u2014 nothing to promote.`],"Not started");case"path-exists":return f([`${$.path} exists but does not hold ${i} \u2014 move it aside, or check ${i} out there yourself.`],"Not started");case"worktree-failed":return f([`git refused to check ${i} out into ${$.path}.`],"Not started");case"unsupported":break}}if(r.exists(o.worktree)){let $=Oa(o.worktree,`${n.remote}/${s}`,`${n.remote}/${i}`),z=Ia($,i,rt(o.worktree));if($.kind==="failed"||$.kind==="uncommitted")return f([...z,"nothing ran and nothing was merged."],"Not started");for(let ae of z)R(ae)}if(r.exists(o.worktree)&&r.isDirty(o.worktree)!==!1)return f([`${o.worktree} has uncommitted changes \u2014 commit or discard them first. The gate would judge files that are not in the commit being merged.`,"nothing ran and nothing was merged."],"Not started");let v=await z6(e.checkOverrides);if(v.kind==="refused")return f([...v.lines,"nothing ran \u2014 fix or drop the override."],"Not started");let E=v.accepted;if(r.fetch(t,n.remote),r.exists(w)){let $=await ka(w,`${n.remote}/${s}`,m.kind==="unbound"?null:m.objectId);if($.kind==="skipped")R(`could not check what landed since the branch forked: ${$.reason}`);else for(let z of $.lines)R(z)}let x=`${n.remote}/${s}`;for(let $ of q$(lr(r.exists(w)?w:t,{baseRef:x})))R($);if(r.exists(w)&&m.kind!=="unbound"){let $=P("git",["config","--get",`branch.${i}.maindObjectKey`],t)??(m.kind==="recovered"?m.key:null);if($){for(let z of await ga(w,x,{id:m.objectId,key:$}))R(z);for(let z of await ya(w,x,{id:m.objectId,key:$}))R(z)}}let O=Ht(r.exists(w)?w:t),T=O.kind==="loaded"?O.versioned.filter($=>$.numbering==="promote"):[],S=$a(t,x,n.regenerate);S.differs&&R(Uy(x,t));let A=r.exists(w)?P("git",["rev-parse","HEAD"],w):null,C=a(($=!1)=>{if(A===null)return;if(P("git",["rev-parse","HEAD"],w)===A){Hn(w);return}let z=zu(w,A);z.ok&&Hn(w),!(z.ok&&$)&&R(z.ok?`${i} is back at ${A.slice(0,9)} \u2014 promote's local commits are undone, the pull request was not touched.`:`could not move ${i} back to ${A.slice(0,9)} (${z.output}). promote's commits are local only \u2014 undo them before the next run: cd ${rt(w)} && git reset --keep ${A}`)},"undoLocal"),N=a(($,z,ae,he)=>{let Re=aC({base:x,from:$,to:z,commits:P("git",["rev-list","--count",`${$}..${z}`],t),when:ae,conflicting:he,retriesSoFar:DN,maxRetries:q6});if(!Re.retry)return f(Re.lines);for(let Qe of Re.lines)R(Qe);return DN+=1,ol(e)},"againForMovedBase"),B=a($=>(A!==null&&r.exists(w)&&Gy(w,A,"promote"),Dy({wt:w,root:t,branch:i,baseRef:x,packages:r.exists(w)?T:[],regenerate:r.exists(w)?($==="merge"?$a(t,x,n.regenerate):S).steps:[],method:b.method,utcTodayIso:$o(),phase:$,note:R})),"mergeResult"),I=c.prFor(t,i),j=I?.headSha??null;if(m.kind!=="unbound"&&I&&j){let $=P("git",["rev-parse","HEAD"],r.exists(w)?w:t);if($!==j)return y("not_pushed",[`${i} is at ${$?.slice(0,9)??"?"} locally, the pull request at ${j.slice(0,9)} \u2014 push first (${Ie("ship",o)}). Nothing was merged.`]);let z=c.remoteSlugFor(t);if(!z)return f(["the repository slug could not be read \u2014 the merge approval cannot be checked. Nothing was merged."]);let ae=tn(r.exists(w)?w:t,j,x,{note:R}),he=_o(ae,j),Re=Qt(ho,{sleep:a(Z=>new Promise($e=>setTimeout($e,Z)),"sleep"),note:R}),Qe=Eb(r.exists(w)?w:t,n.remote,s),Se=Pu(r.exists(w)?w:t,x,j,he);if(Se.kind==="conflict"){let Z=await Re("work_object_merge_approval_state",{objectId:m.objectId,ref:l.ref(z,I.number),headSha:j}),$e=jT(Z.kind==="ok"?Fn(Z.body):null,j.slice(0,7));return y("base_conflict",[`${i} ${en(Se,x)}`,...$e.lines],$e.title)}let D=await Re("work_object_merge_approval_state",{objectId:m.objectId,ref:l.ref(z,I.number),headSha:j}),U=D.kind==="ok"?Fn(D.body):null;if(r.exists(w)&&OT(U,ae.links.length>0)){let Z=B("before-approval");if(Z.kind==="stop"){C(!0);let tt=PT(U);return y(Z.reason,[...Z.lines,...tt.lines],tt.title)}if(n.postCreate.length>0){let tt=ko(w);tt.stale&&(R(`${tt.reason} \u2014 running postCreate before the gate.`),Er(n,w)||R("postCreate failed \u2014 a red check below may come from a stale install."))}d.open("Gate");let $e=await NN(w,{remote:n.remote,base:s,postCreate:n.postCreate.length>0,overrides:e.overrides,prChecks:jb(l,t,i,()=>Si(t,x,n.ignoreChecks??[])),pushPendingFrom:A,branchHead:A,record:"promote",progress:"running the gate on the merge result before the merge approval is asked"},d);if(C(!0),$e!==0){let tt=MT(U),ee=tt.lines.map(_e=>({text:_e}));for(let _e of Ay(rl,!!e.overrides))ee.push({text:_e});return d.callout("fail",tt.title,ee),await k("gate"),1}R(U?.state==="pending"?`the gate is green on the merge result of ${j.slice(0,9)} with ${x} \u2014 the open question is for exactly this head.`:`the gate is green on the merge result of ${j.slice(0,9)} with ${x} \u2014 the merge approval is asked for exactly this head.`)}let Q=process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ue=Pb(e,Q)&&IT({tty:Q,before:U}),Ne=a(Z=>new Promise($e=>setTimeout($e,Z)),"pause"),He=ue?gi():null,ge={pid:process.pid,head:j};ue&&r.exists(w)&&Ui(w,{...ge,by:"promote"}),d.open("Approval");let q=LT(Z=>{$$(Z)?d.text(Z,"ok"):R(Z)}),Pe=q.flush,Ye=q.push,be=await O$({objectId:m.objectId,ref:l.ref(z,I.number),prNumber:I.number,headSha:j,base:s,dashboardUrl:To(),carry:{links:ae.links,stopLine:Ta(ae)}},{call:my(Re,{sleep:a(Z=>new Promise($e=>setTimeout($e,Z)),"sleep"),note:R,maxQuotaWaitMs:ue?e.waitTimeoutMs??gr.timeoutMs:0}),isTty:a(()=>Q,"isTty"),prompt:a(Z=>(Pe(),Bd(Z)),"prompt"),note:Ye,onWait:a(Z=>{Pe(),yA(),d.approval({url:Z.url,prNumber:Z.prNumber,shortSha:Z.shortSha,lines:[`PR #${Z.prNumber} at ${Z.shortSha} waits for a person's approval.`,`Approve it in a browser session \u2014 promote merges as soon as you do (waiting up to ${A$(Z.timeoutMs)}, checking ${Z.cadence}).`]})},"onWait"),...ue?{wait:{options:{...gr,timeoutMs:e.waitTimeoutMs??gr.timeoutMs},...He?{call:my(Qt(He.call,{sleep:Ne,note:R}),{sleep:Ne,note:R,maxQuotaWaitMs:e.waitTimeoutMs??gr.timeoutMs})}:{},currentHead:a(()=>c.prFor(t,i)?.headSha??null,"currentHead"),baseConflict:Fi(Bi(r.exists(w)?w:t,n.remote,s,j,he),{checkedBase:Qe}),sleep:a(Z=>new Promise($e=>setTimeout($e,Z)),"sleep"),now:a(()=>Date.now(),"now"),tick:a(Z=>{Pe(),r.exists(w)&&Ui(w,{...ge,by:"promote"}),d.progress(`waiting for the approval \u2014 ${Math.max(1,Math.ceil(Z/6e4))} min left`)},"tick")}}:{},tellObject:a(async Z=>{await Iu(m.objectId,Z)},"tellObject")}).finally(async()=>{await He?.close()});if(be.kind==="pending"){let Z=wi(Ie("promote",o),{...e.closesObject?{closesObject:!0}:{},...e.progressOnly?{progressOnly:!0}:{},...e.mergeMethod?{mergeMethod:e.mergeMethod}:{},wait:!0},{cwd:r.exists(w)?w:t,cliVersion:fe}),$e=!Q&&U?.state!=="pending",tt=$e?[]:q.take();if(Pe(),r.exists(w)){Va(w,ge);let ee=xr(rn(w),j,{alive:vr,now:a(()=>Date.now(),"now")});if(Td({questionOpen:!0,setting:n.approvalWatch??"on",ci:!!process.env.CI,alreadyWatched:ee})){let _e=r.worktreeList(t)[0]?.path??t,K=Cd(_e,o);K&&R(`watching ${x} until the answer \u2014 a conflict with this head is reported to the work object (log: ${K}).`)}}if(d.approval({url:be.url,prNumber:I.number,shortSha:j.slice(0,7)}),$e){let ee=NT({url:be.url,waitRequested:e.wait===!0,rerun:Z});d.callout("warn","Asked \u2014 tell your user",[...ee.lines.map(_e=>({text:_e})),{command:ee.command}])}else{let ee=DT(tt,Z);d.callout("warn",ee.title,[...Rb(ee.lines),{command:ee.command}])}return 3}if(r.exists(w)&&Va(w,ge),be.kind==="stop"){let Z=q.take();return y(C$[be.reason],Z.length>0?Z:["the merge approval did not lead to a merge \u2014 nothing was merged."])}Pe(),gA(),r.fetch(t,n.remote)}else m.kind==="unbound"&&R("no work object is bound \u2014 promote checks merge approvals only for a bound branch, so none was checked here.");let F={kind:"none"},Y=null,ne=null,ke=P("git",["rev-parse","--verify","--quiet",`${x}^{commit}`],t);if(r.exists(w)){d.open("Release"),sd();let $=B("merge");if($.kind==="stop")return C(),y($.reason,[...$.lines,$.reason==="base_conflict"?"nothing ran and nothing was merged.":"nothing was merged."]);F=$.release,Y=$.trialFrom}if(r.exists(w)){let $=!1;if(n.postCreate.length>0){let he=ko(w);he.stale&&(R(`${he.reason} \u2014 running postCreate again before the gate.`),$=!Er(n,w))}d.open("Gate","the state that lands");let z=await NN(w,{remote:n.remote,base:s,postCreate:n.postCreate.length>0,overrides:e.overrides,prChecks:jb(l,t,i,()=>Si(t,x,n.ignoreChecks??[])),pushPendingFrom:A,branchHead:A,record:"promote",progress:"running the gate on the merge result"},d);if(z===0&&d.open("Merge"),z!==0){C();let he=[{text:"the gate is red \u2014 nothing was pushed and nothing was merged."}];$&&he.push({text:`postCreate failed just before the gate, so a red check may come from a stale install rather than this branch. Fix it, then promote again: cd ${rt(w)} && ${n.postCreate.join(" && ")}`});for(let Re of Ay(rl,!!e.overrides))he.push({text:Re});return d.callout("fail","Not merged",he),await k("gate"),1}if(ke){r.fetch(t,n.remote);let he=P("git",["rev-parse","--verify","--quiet",`${x}^{commit}`],t);if(he!==null&&he!==ke)return C(!0),A!==null&&P("git",["rev-parse","HEAD"],w)!==A?f([`${x} moved while the gate ran, and promote's local commits could not be undone \u2014 no new attempt on top of them.`,"nothing was pushed and nothing was merged."]):N(ke,he,"after-gate",!1)}if(Y!==null){let he=zu(w,Y);if(!he.ok)return C(),y("release_failed",[`could not undo the trial merge of ${x} (${he.output}) \u2014 nothing was pushed and nothing was merged.`])}let ae=P("git",["rev-parse","HEAD"],w);if(ae&&ae!==A){let he=l.requiredNames(t,i,s);ne=l.checkStates(t,i);let Re=hT(w,n.remote,i);if(!Re.ok)return C(),y("release_failed",[`pushing promote's commits failed: ${Re.output}`,"nothing was merged."]);R(`pushed ${ae.slice(0,9)} \u2014 the state the gate just checked.`),l.awaitHead(t,i,ae,he)}Hn(w)}else return f([`no worktree at ${w} \u2014 the gate cannot run, so nothing is merged.`]);let Fe=P("git",["config","--get",`branch.${i}.maindObjectKey`],t)??(m.kind==="recovered"?m.key:null),{mergedFiles:ce,documents:We,docDecision:Xe,fanOut:Ue}=VN({root:t,fx:l,remote:n.remote,base:s,branch:i,objectKey:Fe}),le=j?P("git",["rev-parse","HEAD"],w):null,G=AI(c,{repoRoot:t,branch:i,base:s,cfg:n,method:b.method,closesObject:h.completes,utcTodayIso:$o(),expectedHead:le,otherChecks:a(()=>{let $=jI({read:a(()=>l.checkStates(t,i),"read"),pause:a(z=>c.pause?c.pause(z):void Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,z),"pause"),now:a(()=>Date.now(),"now"),note:R},{before:ne,ignore:Si(t,x,n.ignoreChecks??[]),accepted:new Set(E.keys()),timeoutMs:MN,intervalMs:V6,graceMs:Y6});if($.kind==="green"){for(let ae of UI($.judgement))R(ae);let z=new Set($.judgement.accepted.map(ae=>ae.name));for(let ae of $.judgement.accepted){let he=E.get(ae.name),Re=he.key??he.id,Qe=ji(Mi(`check:${ae.name}`,`red accepted, tracked by ${Re} (${he.id})`,i,t),nn());R(`${ae.name} did not pass (${ae.detail}) and was accepted \u2014 tracked by ${Re}. `+(Qe?`Recorded as a gate_override in ${nn()}.`:`WARNING: the override could NOT be recorded (${nn()} unwritable).`))}for(let ae of E.keys())z.has(ae)||R(`--override check:${ae}: that check is not red \u2014 the override is dropped, nothing was recorded.`)}return $},"otherChecks"),...ke?{baseMoved:a(()=>{r.fetch(t,n.remote);let $=P("git",["rev-parse","--verify","--quiet",`${x}^{commit}`],t);return $!==null&&$!==ke?{from:ke,to:$}:null},"baseMoved")}:{},...F.kind==="released"&&F.releases.length>0?{takenClaims:a(()=>(r.fetch(t,n.remote),mT(t,x,F.kind==="released"?F.releases:[])),"takenClaims")}:{}}),je={"wrong-base":"wrong_base","head-moved":"head_moved","title-not-conventional":"title_not_conventional","commits-not-conventional":"commits_not_conventional","checks-red":"checks_red",conflicting:"base_conflict","checks-unknown":"checks_unknown","merge-failed":"merge_failed"},it=G.kind==="claim-taken"?Kd>=Gd?"number_taken":void 0:je[G.kind];switch(it&&await k(it),G.kind){case"no-pr":return f([`no pull request found for ${G.branch} \u2014 ship it first.`]);case"not-open":return f([`the pull request for ${G.branch} is ${G.state}, not OPEN.`]);case"wrong-base":return f([`the pull request targets ${G.actual}, expected ${G.expected}.`]);case"claim-taken":{let $=[...G.reasons.map(z=>`${z} \u2014 ${x} moved while promote waited for the checks.`),"nothing was merged."];if(Kd<Gd){for(let z of $)R(z);return Kd+=1,R(`promoting again \u2014 the number is assigned anew (attempt ${Kd+1} of ${Gd+1}).`),ol(e)}return f([...$,`${x} took a number ${Gd+1} times in a row \u2014 run promote again when it is quieter.`])}case"base-moved":return N(G.from,G.to,"before-merge",G.conflicting===!0);case"head-moved":return f([`the pull request moved to ${G.actual?.slice(0,9)??"?"} while promote prepared ${G.expected.slice(0,9)} \u2014 someone pushed in between. Nothing was merged; run promote again (a pushed commit needs a new approval \u2014 only promote's own commits carry the earlier one).`]);case"title-not-conventional":return f([`PR #${G.pr.number} is titled "${G.title}" \u2014 not a conventional commit, and this repository's history is.`,`the title becomes the squash commit on ${s}; after the merge it cannot be fixed without rewriting ${s}. Nothing was merged.`,l.titleFix(G.pr.number,c.remoteSlugFor(t),G.suggestion??"<type>(<scope>): <subject>")]);case"commits-not-conventional":return f([`with a ${G.method==="merge"?"merge commit":"rebase"}, every commit of ${G.branch} lands on ${s}, and this repository's history is conventional. Not conventional: ${G.subjects.map($=>`"${$}"`).join(", ")}. Nothing was merged.`,"reword them and push (the new head needs a new approval), or merge with --merge-method squash \u2014 then only the title lands."]);case"checks-red":if(G.judgement){let $=wi(Ie("promote",o),{...e.closesObject?{closesObject:!0}:{},...e.progressOnly?{progressOnly:!0}:{},...e.mergeMethod?{mergeMethod:e.mergeMethod}:{}});return f(FI(G.judgement,x,$))}return f([`required checks are RED for ${G.branch} \u2014 nothing was merged.`]);case"conflicting":return f(lC(G.branch,G.base,G.late===!0));case"checks-unknown":return G.judgement?f(BI(G.judgement,x,Math.round(MN/6e4))):G.reason?f([`${G.reason} \u2014 nothing was merged. This is not a red verdict; run promote again.`]):f([`could not determine the required checks for ${G.branch} \u2014 nothing was merged. They may still be running; this is not a red verdict.`]);case"merge-failed":return f([`the merge (${ai(b.method)}) failed for ${G.branch}.`,...F.kind==="released"?["the release commit was pushed moments ago \u2014 if its required checks are still running, wait until they are green and re-run promote (it withdraws and re-assigns the number)."]:[]]);case"ok":{let $=c.remoteSlugFor(t);$?await YN(l.ref($,G.pr.number),G.mergedOn,G.completes,{documents:We,docDecision:Xe,fanOut:Ue})&&P("git",["config",`branch.${i}.${Xu}`,String(G.pr.number)],t):R("the repository path could not be read from the forge \u2014 the merge was not reported."),F.kind==="released"&&F.releases.some(Re=>Re.tag)&&zN(r,t,n.remote,l.mergeCommit(t,G.pr.number),F.releases,G.pr.number);let z=r.worktreeList(t),ae=z[0]?.path??t,he=$A(G.ff,{base:s,mainRoot:ae,ref:`${n.remote}/${s}`});d.callout("ok",`Merged PR #${G.pr.number}`,[{text:`merged PR #${G.pr.number} (${G.mergedOn}, ${ai(G.method)})`+(G.completes?" \u2014 reported as completion":" \u2014 reported as progress, the object stays open")+he.suffix},...he.extra.map(Re=>({text:Re.trim()}))]),d.open("Afterwards");for(let Re of CA(G.stacked,{branch:i,base:s,remote:n.remote,mergedPr:G.pr.number,mergedHead:G.pr.headSha,mainRoot:ae,slug:$,worktreeFor:a(Qe=>z.find(Se=>Se.branch===Qe)?.path??null,"worktreeFor"),method:G.method}))R(Re);return XN({deps:r,root:t,target:o,cfg:n,base:s,wt:w,mergedFiles:ce,trees:z,mainRoot:ae}),process.stdout.write(`${G.pr.number}
538
+ `),0}if(e.check===!0){let $=[],z={...e.closesObject?{closesObject:!0}:{},...e.progressOnly?{progressOnly:!0}:{},...e.mergeMethod?{mergeMethod:e.mergeMethod}:{}},ae={cwd:r.exists(o.worktree)?o.worktree:t,cliVersion:fe},he=wi(Ie("promote",o),{...z,...e.wait?{wait:!0}:{}},ae),Re;p?p.state!=="OPEN"?$.push({name:"pull-request",verdict:"fail",detail:`PR #${p.number} is ${p.state.toLowerCase()}`}):$.push({name:"pull-request",verdict:"ok",detail:`PR #${p.number}`}):$.push({name:"pull-request",verdict:"fail",detail:`no pull request for ${i} \u2014 ship first: ${Ie("ship",o)}`});let Qe=c.remoteSlugFor(t),Se=p&&Qe?l.ref(Qe,p.number):null,D=P("git",["config","--get",`branch.${i}.maindObject`],t),U=P("git",["config","--get",`branch.${i}.maindObjectKey`],t),Q=Se?await Ln(Se).catch(()=>null):null,ue=D??Q?.id??null;!D&&Q&&$.push({name:"binding",verdict:"note",detail:`no local binding \u2014 promote restores it from the PR link (${Q.key??Q.id})`}),ra(ue,e.closesObject===!0?"closes":e.progressOnly===!0?"progress":void 0).kind==="missing"?$.push({name:"completion",verdict:"fail",detail:"the branch is bound to a work object \u2014 say --closes-object or --progress-only"}):ue&&$.push({name:"completion",verdict:"ok",detail:e.closesObject?"closes the object":"progress only"});let He=Ag({flag:e.mergeMethod??null,configured:n.mergeMethod??null,forge:c.mergeMethods(t)});if(He.kind==="not-allowed")$.push({name:"merge-method",verdict:"fail",detail:Tg(He)[0]});else if($.push({name:"merge-method",verdict:"ok",detail:$g(He)}),He.method==="rebase"){let ee=ZN(t,r.exists(o.worktree)?o.worktree:t,`${n.remote}/${s}`,i,n);ee&&$.push(ee)}let ge=Ng({required:nl(r.exists(o.worktree)?o.worktree:t),branch:i,boundObject:ue,overrideReason:process.env[li]??null,promoteCommand:Ie("promote",o)});ge&&$.push({name:"work-object",verdict:"fail",detail:ge[0]??"a work object is required"}),D&&Se&&(Q===null?$.push({name:"pr-link",verdict:"note",detail:`${Se} is not linked yet \u2014 promote links it to ${U??D}`}):Q.id!==D?$.push({name:"pr-link",verdict:"fail",detail:ci({branch:i,phase:"promote",prNumber:p?.number??null,ref:Se,bound:{id:D,key:U},other:Q})[0].replace(/ — the merge would be reported against the wrong object\.$/,"")}):$.push({name:"pr-link",verdict:"ok",detail:`${Se} \u2192 ${Q.key??Q.id}`}));let q=o.worktree;if(r.exists(q)){let ee=Oa(q,`${n.remote}/${s}`,`${n.remote}/${i}`);for(let _e of Ia(ee,i,rt(q)))$.push({name:"interrupted-run",verdict:ee.kind==="failed"?"fail":"note",detail:_e})}r.exists(q)?r.isDirty(q)!==!1?$.push({name:"worktree",verdict:"fail",detail:`${q} has uncommitted changes \u2014 the gate would judge files that are not in the commit`}):$.push({name:"worktree",verdict:"ok",detail:"clean"}):$.push({name:"worktree",verdict:o.byBranch?"note":"fail",detail:o.byBranch?`promote checks ${i} out into ${q} for the gate`:`no worktree at ${q}`});let Pe=p?.headSha??null,Ye=P("git",["rev-parse","HEAD"],r.exists(q)?q:t);Pe&&Ye&&Ye!==Pe?$.push({name:"pushed",verdict:"fail",detail:`local ${Ye.slice(0,9)}, pull request ${Pe.slice(0,9)} \u2014 push first: ${Ie("ship",o)}`}):Pe&&$.push({name:"pushed",verdict:"ok",detail:Pe.slice(0,9)}),r.fetch(t,n.remote);let be=`${n.remote}/${s}`;for(let ee of lr(r.exists(q)?q:t,{baseRef:be}).findings)$.push({name:"sql-base-overlap",verdict:"note",detail:ee.title});if(ue&&Se&&Pe&&p){let ee=Qt(ho,{sleep:a(Ee=>new Promise(Be=>setTimeout(Be,Ee)),"sleep"),note:R}),_e=await ee("work_object_merge_approval_state",{objectId:ue,ref:Se,headSha:Pe}),K=_e.kind==="ok"?Fn(_e.body):null,re=yo(To(),K?.objectKey??null),ie=null;if(K&&(K.state==="none"||K.state==="pending")){let Ee=tn(r.exists(q)?q:t,Pe,be,{note:R});ie=await ju(ee,{objectId:ue,ref:Se,headSha:Pe,base:s},{links:Ee.links,stopLine:Ta(Ee)})}$.push(RT(K??{failure:_e.kind==="unknown_tool"?"the server cannot read merge approvals yet":_e.kind==="failed"||_e.kind==="invalid_params"?_e.reason:String(_e.body.error??"unreadable answer")},{prNumber:p.number,url:re,wait:Pb(e,process.stdin.isTTY===!0&&process.stdout.isTTY===!0),carry:ie})),K?.state==="approved"||ie?.kind==="carries"?Re={kind:"given"}:K&&(K.state==="none"||K.state==="pending")&&ie?.kind!=="declined"&&(Re={kind:"asks",url:re,asked:K.state==="pending",waitCommand:wi(Ie("promote",o),{...z,wait:!0},ae)})}let Z=Ca(r.exists(q)?q:t,be,i),$e=Z.verdict;if(r.exists(q)){let ee=Ht(q),_e=ee.kind==="loaded"?ee.versioned.filter(re=>re.numbering==="promote"):[],K=GN(Yu(q,be,_e,$o()),$e.kind==="conflict"||Z.ownOnly.length>0);K&&$.push(K)}if($.push(HN(i,Z,be)),p){let ee=_i(p.title??"",xa(c.baseSubjects(t,be)),c.branchCommits(t,be,i));$.push(ee.kind==="ok"?{name:"title",verdict:"ok",detail:p.title??""}:{name:"title",verdict:"fail",detail:`"${ee.title}" is not a conventional commit${ee.suggestion?` \u2014 suggestion: "${ee.suggestion}"`:""}`})}if(r.exists(q)&&$e.kind!=="conflict"&&r.isDirty(q)===!1){let ee=$a(t,`${n.remote}/${s}`,n.regenerate);ee.differs&&$.push({name:"regenerate",verdict:"note",detail:Uy(`${n.remote}/${s}`,t)});let _e=Ht(q),K=P("git",["rev-parse","HEAD"],q);K&&Gy(q,K,"check");let re=Dy({wt:q,root:t,branch:i,baseRef:be,packages:_e.kind==="loaded"?_e.versioned.filter(ie=>ie.numbering==="promote"):[],regenerate:ee.steps,method:He.kind==="not-allowed"?"squash":He.method,utcTodayIso:$o(),phase:"check",note:a(ie=>d.say(ie),"note")});if(re.kind==="stop")$.push({name:"merge-result",verdict:"fail",detail:re.lines.join(" ")});else{if(n.postCreate.length>0){let Be=ko(q);Be.stale&&($.push({name:"install",verdict:"note",detail:`${Be.reason} \u2014 ran postCreate for the merge result`}),Er(n,q)||$.push({name:"install",verdict:"note",detail:"postCreate failed \u2014 a red check below may come from a stale install"}))}d.open("Gate");let ie=e.overrides?null:Ty(q,be,{postCreate:n.postCreate.length>0,cli:fe,branchHead:K});d.progress("running the gate on the merge result (as promote would)");let Ee=await KN(q,ie,{json:!1,overrides:e.overrides,...K?{pushPendingFrom:K}:{},prChecks:jb(l,t,i,()=>Si(t,be,n.ignoreChecks??[]))},d,"check");Ee!==0?Zu(q):ie!==null&&Oy(q,ie,"check",Date.now()),$.push(Ee===0?{name:"gate",verdict:"ok",detail:`every declared gate passed on the merge result with ${be}`}:{name:"gate",verdict:"fail",detail:`red on the merge result with ${be} \u2014 see the gate output above`})}if(K&&P("git",["rev-parse","HEAD"],q)!==K){let ie=zu(q,K);ie.ok||$.push({name:"merge-result",verdict:"fail",detail:`could not move ${i} back to ${K.slice(0,9)} (${ie.output}) \u2014 run: cd ${rt(q)} && git reset --keep ${K}`})}K&&P("git",["rev-parse","HEAD"],q)===K&&Hn(q)}if(p){$.push(l.checksRow(t,i,s));let ee=new Set((e.checkOverrides??[]).map(K=>K.gate)),_e=HI((l.checkStates(t,i)??null)?.filter(K=>!ee.has(K.name)&&!ee.has(K.job??K.name))??null,l.requiredNames(t,i,s),Si(t,`${n.remote}/${s}`,n.ignoreChecks??[]));_e&&$.push(_e),ee.size>0&&$.push({name:"other-checks",verdict:"note",detail:`--override names ${[...ee].join(", ")} \u2014 promote verifies that the object is open before it accepts a red check`})}if(r.exists(q)){let ee=await ka(q,`${n.remote}/${s}`,ue??null);if(ee.kind==="skipped")$.push({name:"landed-since",verdict:"note",detail:`not checked: ${ee.reason}`});else for(let K of ee.lines)$.push({name:"landed-since",verdict:"note",detail:K});let _e=U??Q?.key??null;if(ue&&_e){for(let K of await ga(q,`${n.remote}/${s}`,{id:ue,key:_e}))$.push({name:"lesson-check",verdict:"note",detail:K});for(let K of await ya(q,`${n.remote}/${s}`,{id:ue,key:_e}))$.push({name:"documentation",verdict:"note",detail:K});for(let K of await Fu(q,i,{id:ue,key:_e}))$.push({name:"plan",verdict:"note",detail:K})}}d.open("Checks");for(let ee of $)d.row(ee.verdict,ee.name,ee.detail);let tt=ST($,he,Re);return d.callout(tt.tone,tt.title,tt.parts),tt.exitCode}if(e.yes!==!0)return f([`promote merges ${i} into ${s}. Re-run with --yes when you mean it.`],"Not started");let m=await Dg(P("git",["config","--get",`branch.${i}.maindObject`],t),{prNumber:a(()=>c.prFor(t,i)?.number??null,"prNumber"),slug:a(()=>c.remoteSlugFor(t),"slug"),ref:l.ref,lookup:Ln,write:a(($,z)=>{P("git",["config",`branch.${i}.maindObject`,$],t),z&&P("git",["config",`branch.${i}.maindObjectKey`,z],t)},"write")});m.kind==="recovered"&&R(`${i} had no local binding, but ${m.ref} is linked to ${m.key??m.objectId} \u2014 binding restored.`);let h=ra(m.kind==="unbound"?null:m.objectId,e.closesObject===!0?"closes":e.progressOnly===!0?"progress":void 0);if(h.kind==="missing"){let $=P("git",["config","--get",`branch.${i}.maindObjectKey`],t);return f(vA(i,$??h.objectId),"Not started")}let k=a(async $=>{if(m.kind==="unbound")return;let z=c.prFor(t,i),ae=c.remoteSlugFor(t);if(!z?.headSha||!ae||z.state!=="OPEN")return;let he=$==="gate"?FT(rl):[];await Et(Rt(["report","--event","gate","--ref",l.ref(ae,z.number),"--sha",z.headSha,"--stopped-at",$,...he]))},"reportStop"),y=a(async($,z,ae="Not merged")=>(f(z,ae),await k($),1),"haltAt"),b=Ag({flag:e.mergeMethod??null,configured:n.mergeMethod??null,forge:c.mergeMethods(t)});if(b.kind==="not-allowed")return y("method_not_allowed",Tg(b),"Not started");b.source!=="default"&&R($g(b));let _=Ng({required:nl(r.exists(o.worktree)?o.worktree:t),branch:i,boundObject:m.kind==="unbound"?null:m.objectId,overrideReason:process.env[li]??null,promoteCommand:Ie("promote",o)});if(_)return f(_,"Not started");if(m.kind==="bound"){let $=await oa(m.objectId,{prNumber:a(()=>c.prFor(t,i)?.number??null,"prNumber"),slug:a(()=>c.remoteSlugFor(t),"slug"),ref:l.ref,lookup:Ln,link:a(async(z,ae)=>{await Et(Rt(["link","--object",z,"--ref",ae]))},"link")});if($.kind==="mismatch")return f(ci({branch:i,phase:"promote",prNumber:c.prFor(t,i)?.number??null,ref:$.ref,bound:{id:m.objectId,key:P("git",["config","--get",`branch.${i}.maindObjectKey`],t)},other:$.other}),"Not started")}let w=o.worktree;if(!r.exists(w)&&o.byBranch){let $=NA(r,{repoRoot:t,branch:i,path:w,remote:n.remote});switch($.kind){case"ok":{R(`checked ${i} out into ${w} for the gate.`);let z=tl(t,w,fi(t,w));z.length>0&&R(`provisioned ${z.length} declared path(s) from the main checkout.`),Er(n,w);break}case"no-branch":return f([`${i} exists neither locally nor as ${$.remote}/${i} \u2014 nothing to promote.`],"Not started");case"path-exists":return f([`${$.path} exists but does not hold ${i} \u2014 move it aside, or check ${i} out there yourself.`],"Not started");case"worktree-failed":return f([`git refused to check ${i} out into ${$.path}.`],"Not started");case"unsupported":break}}if(r.exists(o.worktree)){let $=Oa(o.worktree,`${n.remote}/${s}`,`${n.remote}/${i}`),z=Ia($,i,rt(o.worktree));if($.kind==="failed"||$.kind==="uncommitted")return f([...z,"nothing ran and nothing was merged."],"Not started");for(let ae of z)R(ae)}if(r.exists(o.worktree)&&r.isDirty(o.worktree)!==!1)return f([`${o.worktree} has uncommitted changes \u2014 commit or discard them first. The gate would judge files that are not in the commit being merged.`,"nothing ran and nothing was merged."],"Not started");let v=await z6(e.checkOverrides);if(v.kind==="refused")return f([...v.lines,"nothing ran \u2014 fix or drop the override."],"Not started");let E=v.accepted;if(r.fetch(t,n.remote),r.exists(w)){let $=await ka(w,`${n.remote}/${s}`,m.kind==="unbound"?null:m.objectId);if($.kind==="skipped")R(`could not check what landed since the branch forked: ${$.reason}`);else for(let z of $.lines)R(z)}let x=`${n.remote}/${s}`;for(let $ of q$(lr(r.exists(w)?w:t,{baseRef:x})))R($);if(r.exists(w)&&m.kind!=="unbound"){let $=P("git",["config","--get",`branch.${i}.maindObjectKey`],t)??(m.kind==="recovered"?m.key:null);if($){for(let z of await ga(w,x,{id:m.objectId,key:$}))R(z);for(let z of await ya(w,x,{id:m.objectId,key:$}))R(z)}}let O=Ht(r.exists(w)?w:t),T=O.kind==="loaded"?O.versioned.filter($=>$.numbering==="promote"):[],S=$a(t,x,n.regenerate);S.differs&&R(Uy(x,t));let A=r.exists(w)?P("git",["rev-parse","HEAD"],w):null,C=a(($=!1)=>{if(A===null)return;if(P("git",["rev-parse","HEAD"],w)===A){Hn(w);return}let z=zu(w,A);z.ok&&Hn(w),!(z.ok&&$)&&R(z.ok?`${i} is back at ${A.slice(0,9)} \u2014 promote's local commits are undone, the pull request was not touched.`:`could not move ${i} back to ${A.slice(0,9)} (${z.output}). promote's commits are local only \u2014 undo them before the next run: cd ${rt(w)} && git reset --keep ${A}`)},"undoLocal"),N=a(($,z,ae,he)=>{let Re=aC({base:x,from:$,to:z,commits:P("git",["rev-list","--count",`${$}..${z}`],t),when:ae,conflicting:he,retriesSoFar:DN,maxRetries:q6});if(!Re.retry)return f(Re.lines);for(let Qe of Re.lines)R(Qe);return DN+=1,ol(e)},"againForMovedBase"),B=a($=>(A!==null&&r.exists(w)&&Gy(w,A,"promote"),Dy({wt:w,root:t,branch:i,baseRef:x,packages:r.exists(w)?T:[],regenerate:r.exists(w)?($==="merge"?$a(t,x,n.regenerate):S).steps:[],method:b.method,utcTodayIso:$o(),phase:$,note:R})),"mergeResult"),I=c.prFor(t,i),j=I?.headSha??null;if(m.kind!=="unbound"&&I&&j){let $=P("git",["rev-parse","HEAD"],r.exists(w)?w:t);if($!==j)return y("not_pushed",[`${i} is at ${$?.slice(0,9)??"?"} locally, the pull request at ${j.slice(0,9)} \u2014 push first (${Ie("ship",o)}). Nothing was merged.`]);let z=c.remoteSlugFor(t);if(!z)return f(["the repository slug could not be read \u2014 the merge approval cannot be checked. Nothing was merged."]);let ae=tn(r.exists(w)?w:t,j,x,{note:R}),he=_o(ae,j),Re=Qt(ho,{sleep:a(Z=>new Promise($e=>setTimeout($e,Z)),"sleep"),note:R}),Qe=Eb(r.exists(w)?w:t,n.remote,s),Se=Pu(r.exists(w)?w:t,x,j,he);if(Se.kind==="conflict"){let Z=await Re("work_object_merge_approval_state",{objectId:m.objectId,ref:l.ref(z,I.number),headSha:j}),$e=jT(Z.kind==="ok"?Fn(Z.body):null,j.slice(0,7));return y("base_conflict",[`${i} ${en(Se,x)}`,...$e.lines],$e.title)}let D=await Re("work_object_merge_approval_state",{objectId:m.objectId,ref:l.ref(z,I.number),headSha:j}),U=D.kind==="ok"?Fn(D.body):null;if(r.exists(w)&&OT(U,ae.links.length>0)){let Z=B("before-approval");if(Z.kind==="stop"){C(!0);let tt=PT(U);return y(Z.reason,[...Z.lines,...tt.lines],tt.title)}if(n.postCreate.length>0){let tt=ko(w);tt.stale&&(R(`${tt.reason} \u2014 running postCreate before the gate.`),Er(n,w)||R("postCreate failed \u2014 a red check below may come from a stale install."))}d.open("Gate");let $e=await NN(w,{remote:n.remote,base:s,postCreate:n.postCreate.length>0,overrides:e.overrides,prChecks:jb(l,t,i,()=>Si(t,x,n.ignoreChecks??[])),pushPendingFrom:A,branchHead:A,record:"promote",progress:"running the gate on the merge result before the merge approval is asked"},d);if(C(!0),$e!==0){let tt=MT(U),ee=tt.lines.map(_e=>({text:_e}));for(let _e of Ay(rl,!!e.overrides))ee.push({text:_e});return d.callout("fail",tt.title,ee),await k("gate"),1}R(U?.state==="pending"?`the gate is green on the merge result of ${j.slice(0,9)} with ${x} \u2014 the open question is for exactly this head.`:`the gate is green on the merge result of ${j.slice(0,9)} with ${x} \u2014 the merge approval is asked for exactly this head.`)}let Q=process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ue=Pb(e,Q)&&IT({tty:Q,before:U}),Ne=a(Z=>new Promise($e=>setTimeout($e,Z)),"pause"),He=ue?gi():null,ge={pid:process.pid,head:j};ue&&r.exists(w)&&Ui(w,{...ge,by:"promote"}),d.open("Approval");let q=LT(Z=>{$$(Z)?d.text(Z,"ok"):R(Z)}),Pe=q.flush,Ye=q.push,be=await O$({objectId:m.objectId,ref:l.ref(z,I.number),prNumber:I.number,headSha:j,base:s,dashboardUrl:To(),carry:{links:ae.links,stopLine:Ta(ae)}},{call:my(Re,{sleep:a(Z=>new Promise($e=>setTimeout($e,Z)),"sleep"),note:R,maxQuotaWaitMs:ue?e.waitTimeoutMs??gr.timeoutMs:0}),isTty:a(()=>Q,"isTty"),prompt:a(Z=>(Pe(),Bd(Z)),"prompt"),note:Ye,onWait:a(Z=>{Pe(),yA(),d.approval({url:Z.url,prNumber:Z.prNumber,shortSha:Z.shortSha,lines:[`PR #${Z.prNumber} at ${Z.shortSha} waits for a person's approval.`,`Approve it in a browser session \u2014 promote merges as soon as you do (waiting up to ${A$(Z.timeoutMs)}, checking ${Z.cadence}).`]})},"onWait"),...ue?{wait:{options:{...gr,timeoutMs:e.waitTimeoutMs??gr.timeoutMs},...He?{call:my(Qt(He.call,{sleep:Ne,note:R}),{sleep:Ne,note:R,maxQuotaWaitMs:e.waitTimeoutMs??gr.timeoutMs})}:{},currentHead:a(()=>c.prFor(t,i)?.headSha??null,"currentHead"),baseConflict:Fi(Bi(r.exists(w)?w:t,n.remote,s,j,he),{checkedBase:Qe}),sleep:a(Z=>new Promise($e=>setTimeout($e,Z)),"sleep"),now:a(()=>Date.now(),"now"),tick:a(Z=>{Pe(),r.exists(w)&&Ui(w,{...ge,by:"promote"}),d.progress(`waiting for the approval \u2014 ${Math.max(1,Math.ceil(Z/6e4))} min left`)},"tick")}}:{},tellObject:a(async Z=>{await Iu(m.objectId,Z)},"tellObject")}).finally(async()=>{await He?.close()});if(be.kind==="pending"){let Z=wi(Ie("promote",o),{...e.closesObject?{closesObject:!0}:{},...e.progressOnly?{progressOnly:!0}:{},...e.mergeMethod?{mergeMethod:e.mergeMethod}:{},wait:!0},{cwd:r.exists(w)?w:t,cliVersion:fe}),$e=!Q&&U?.state!=="pending",tt=$e?[]:q.take();if(Pe(),r.exists(w)){Va(w,ge);let ee=xr(rn(w),j,{alive:vr,now:a(()=>Date.now(),"now")});if(Td({questionOpen:!0,setting:n.approvalWatch??"on",ci:!!process.env.CI,alreadyWatched:ee})){let _e=r.worktreeList(t)[0]?.path??t,K=Cd(_e,o);K&&R(`watching ${x} until the answer \u2014 a conflict with this head is reported to the work object (log: ${K}).`)}}if(d.approval({url:be.url,prNumber:I.number,shortSha:j.slice(0,7)}),$e){let ee=NT({url:be.url,waitRequested:e.wait===!0,rerun:Z});d.callout("warn","Asked \u2014 tell your user",[...ee.lines.map(_e=>({text:_e})),{command:ee.command}])}else{let ee=DT(tt,Z);d.callout("warn",ee.title,[...Rb(ee.lines),{command:ee.command}])}return 3}if(r.exists(w)&&Va(w,ge),be.kind==="stop"){let Z=q.take();return y(C$[be.reason],Z.length>0?Z:["the merge approval did not lead to a merge \u2014 nothing was merged."])}Pe(),gA(),r.fetch(t,n.remote)}else m.kind==="unbound"&&R("no work object is bound \u2014 promote checks merge approvals only for a bound branch, so none was checked here.");let F={kind:"none"},Y=null,ne=null,ke=P("git",["rev-parse","--verify","--quiet",`${x}^{commit}`],t);if(r.exists(w)){d.open("Release"),sd();let $=B("merge");if($.kind==="stop")return C(),y($.reason,[...$.lines,$.reason==="base_conflict"?"nothing ran and nothing was merged.":"nothing was merged."]);F=$.release,Y=$.trialFrom}if(r.exists(w)){let $=!1;if(n.postCreate.length>0){let he=ko(w);he.stale&&(R(`${he.reason} \u2014 running postCreate again before the gate.`),$=!Er(n,w))}d.open("Gate","the state that lands");let z=await NN(w,{remote:n.remote,base:s,postCreate:n.postCreate.length>0,overrides:e.overrides,prChecks:jb(l,t,i,()=>Si(t,x,n.ignoreChecks??[])),pushPendingFrom:A,branchHead:A,record:"promote",progress:"running the gate on the merge result"},d);if(ke){r.fetch(t,n.remote);let he=P("git",["rev-parse","--verify","--quiet",`${x}^{commit}`],t);if(he!==null&&he!==ke)return C(!0),A!==null&&P("git",["rev-parse","HEAD"],w)!==A?f([`${x} moved while the gate ran, and promote's local commits could not be undone \u2014 no new attempt on top of them.`,"nothing was pushed and nothing was merged."]):N(ke,he,z===0?"after-gate":"after-red-gate",!1)}if(z===0&&d.open("Merge"),z!==0){C();let he=[{text:"the gate is red \u2014 nothing was pushed and nothing was merged."}];$&&he.push({text:`postCreate failed just before the gate, so a red check may come from a stale install rather than this branch. Fix it, then promote again: cd ${rt(w)} && ${n.postCreate.join(" && ")}`});for(let Re of Ay(rl,!!e.overrides))he.push({text:Re});return d.callout("fail","Not merged",he),await k("gate"),1}if(Y!==null){let he=zu(w,Y);if(!he.ok)return C(),y("release_failed",[`could not undo the trial merge of ${x} (${he.output}) \u2014 nothing was pushed and nothing was merged.`])}let ae=P("git",["rev-parse","HEAD"],w);if(ae&&ae!==A){let he=l.requiredNames(t,i,s);ne=l.checkStates(t,i);let Re=hT(w,n.remote,i);if(!Re.ok)return C(),y("release_failed",[`pushing promote's commits failed: ${Re.output}`,"nothing was merged."]);R(`pushed ${ae.slice(0,9)} \u2014 the state the gate just checked.`),l.awaitHead(t,i,ae,he)}Hn(w)}else return f([`no worktree at ${w} \u2014 the gate cannot run, so nothing is merged.`]);let Fe=P("git",["config","--get",`branch.${i}.maindObjectKey`],t)??(m.kind==="recovered"?m.key:null),{mergedFiles:ce,documents:We,docDecision:Xe,fanOut:Ue}=VN({root:t,fx:l,remote:n.remote,base:s,branch:i,objectKey:Fe}),le=j?P("git",["rev-parse","HEAD"],w):null,G=AI(c,{repoRoot:t,branch:i,base:s,cfg:n,method:b.method,closesObject:h.completes,utcTodayIso:$o(),expectedHead:le,otherChecks:a(()=>{let $=jI({read:a(()=>l.checkStates(t,i),"read"),pause:a(z=>c.pause?c.pause(z):void Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,z),"pause"),now:a(()=>Date.now(),"now"),note:R},{before:ne,ignore:Si(t,x,n.ignoreChecks??[]),accepted:new Set(E.keys()),timeoutMs:MN,intervalMs:V6,graceMs:Y6});if($.kind==="green"){for(let ae of UI($.judgement))R(ae);let z=new Set($.judgement.accepted.map(ae=>ae.name));for(let ae of $.judgement.accepted){let he=E.get(ae.name),Re=he.key??he.id,Qe=ji(Mi(`check:${ae.name}`,`red accepted, tracked by ${Re} (${he.id})`,i,t),nn());R(`${ae.name} did not pass (${ae.detail}) and was accepted \u2014 tracked by ${Re}. `+(Qe?`Recorded as a gate_override in ${nn()}.`:`WARNING: the override could NOT be recorded (${nn()} unwritable).`))}for(let ae of E.keys())z.has(ae)||R(`--override check:${ae}: that check is not red \u2014 the override is dropped, nothing was recorded.`)}return $},"otherChecks"),...ke?{baseMoved:a(()=>{r.fetch(t,n.remote);let $=P("git",["rev-parse","--verify","--quiet",`${x}^{commit}`],t);return $!==null&&$!==ke?{from:ke,to:$}:null},"baseMoved")}:{},...F.kind==="released"&&F.releases.length>0?{takenClaims:a(()=>(r.fetch(t,n.remote),mT(t,x,F.kind==="released"?F.releases:[])),"takenClaims")}:{}}),je={"wrong-base":"wrong_base","head-moved":"head_moved","title-not-conventional":"title_not_conventional","commits-not-conventional":"commits_not_conventional","checks-red":"checks_red",conflicting:"base_conflict","checks-unknown":"checks_unknown","merge-failed":"merge_failed"},it=G.kind==="claim-taken"?Kd>=Gd?"number_taken":void 0:je[G.kind];switch(it&&await k(it),G.kind){case"no-pr":return f([`no pull request found for ${G.branch} \u2014 ship it first.`]);case"not-open":return f([`the pull request for ${G.branch} is ${G.state}, not OPEN.`]);case"wrong-base":return f([`the pull request targets ${G.actual}, expected ${G.expected}.`]);case"claim-taken":{let $=[...G.reasons.map(z=>`${z} \u2014 ${x} moved while promote waited for the checks.`),"nothing was merged."];if(Kd<Gd){for(let z of $)R(z);return Kd+=1,R(`promoting again \u2014 the number is assigned anew (attempt ${Kd+1} of ${Gd+1}).`),ol(e)}return f([...$,`${x} took a number ${Gd+1} times in a row \u2014 run promote again when it is quieter.`])}case"base-moved":return N(G.from,G.to,"before-merge",G.conflicting===!0);case"head-moved":return f([`the pull request moved to ${G.actual?.slice(0,9)??"?"} while promote prepared ${G.expected.slice(0,9)} \u2014 someone pushed in between. Nothing was merged; run promote again (a pushed commit needs a new approval \u2014 only promote's own commits carry the earlier one).`]);case"title-not-conventional":return f([`PR #${G.pr.number} is titled "${G.title}" \u2014 not a conventional commit, and this repository's history is.`,`the title becomes the squash commit on ${s}; after the merge it cannot be fixed without rewriting ${s}. Nothing was merged.`,l.titleFix(G.pr.number,c.remoteSlugFor(t),G.suggestion??"<type>(<scope>): <subject>")]);case"commits-not-conventional":return f([`with a ${G.method==="merge"?"merge commit":"rebase"}, every commit of ${G.branch} lands on ${s}, and this repository's history is conventional. Not conventional: ${G.subjects.map($=>`"${$}"`).join(", ")}. Nothing was merged.`,"reword them and push (the new head needs a new approval), or merge with --merge-method squash \u2014 then only the title lands."]);case"checks-red":if(G.judgement){let $=wi(Ie("promote",o),{...e.closesObject?{closesObject:!0}:{},...e.progressOnly?{progressOnly:!0}:{},...e.mergeMethod?{mergeMethod:e.mergeMethod}:{}});return f(FI(G.judgement,x,$))}return f([`required checks are RED for ${G.branch} \u2014 nothing was merged.`]);case"conflicting":return f(lC(G.branch,G.base,G.late===!0));case"checks-unknown":return G.judgement?f(BI(G.judgement,x,Math.round(MN/6e4))):G.reason?f([`${G.reason} \u2014 nothing was merged. This is not a red verdict; run promote again.`]):f([`could not determine the required checks for ${G.branch} \u2014 nothing was merged. They may still be running; this is not a red verdict.`]);case"merge-failed":return f([`the merge (${ai(b.method)}) failed for ${G.branch}.`,...F.kind==="released"?["the release commit was pushed moments ago \u2014 if its required checks are still running, wait until they are green and re-run promote (it withdraws and re-assigns the number)."]:[]]);case"ok":{let $=c.remoteSlugFor(t);$?await YN(l.ref($,G.pr.number),G.mergedOn,G.completes,{documents:We,docDecision:Xe,fanOut:Ue})&&P("git",["config",`branch.${i}.${Xu}`,String(G.pr.number)],t):R("the repository path could not be read from the forge \u2014 the merge was not reported."),F.kind==="released"&&F.releases.some(Re=>Re.tag)&&zN(r,t,n.remote,l.mergeCommit(t,G.pr.number),F.releases,G.pr.number);let z=r.worktreeList(t),ae=z[0]?.path??t,he=$A(G.ff,{base:s,mainRoot:ae,ref:`${n.remote}/${s}`});d.callout("ok",`Merged PR #${G.pr.number}`,[{text:`merged PR #${G.pr.number} (${G.mergedOn}, ${ai(G.method)})`+(G.completes?" \u2014 reported as completion":" \u2014 reported as progress, the object stays open")+he.suffix},...he.extra.map(Re=>({text:Re.trim()}))]),d.open("Afterwards");for(let Re of CA(G.stacked,{branch:i,base:s,remote:n.remote,mergedPr:G.pr.number,mergedHead:G.pr.headSha,mainRoot:ae,slug:$,worktreeFor:a(Qe=>z.find(Se=>Se.branch===Qe)?.path??null,"worktreeFor"),method:G.method}))R(Re);return XN({deps:r,root:t,target:o,cfg:n,base:s,wt:w,mergedFiles:ce,trees:z,mainRoot:ae}),process.stdout.write(`${G.pr.number}
539
539
  `),0}}}a(QN,"runPromote");import{readFileSync as Z6}from"node:fs";import{resolve as Q6}from"node:path";function eD(e){return[`${e.gone} worktree(s) next to this checkout hold a branch that is gone on the remote. This removes the proven-merged, clean ones (add --dry-run to see which first):`,` ${xt(e.mainRoot,"maind feature done --merged")}`]}a(eD,"startSweepHintLines");function tD(e){return e.proven.length===0?[`${e.gone} worktree(s) hold a branch that is gone on the remote, none of them proven merged and free (open PR, local changes, or someone stands in it) \u2014 \`maind feature done --merged --dry-run\` says why.`]:[`${e.proven.length} of ${e.gone} worktree(s) whose branch is gone on the remote are proven merged and clean:`,...e.proven.map(t=>` ${t}`)]}a(tD,"startSweepOfferLines");function nD(e){return`Remove ${e===1?"it":`these ${e}`} now? [y/N] `}a(nD,"startSweepQuestion");function rD(e){return e!==null&&/^\s*y(es)?\s*$/i.test(e)}a(rD,"isYes");async function eJ(e,t,n,r){if(!(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){for(let c of eD({gone:r.length,mainRoot:t}))R(c);return}let o={repoRoot:t,cfg:n,cwd:mt(process.cwd()),liveAgentCwds:Ud(),real:mt,onlyWorktrees:new Set(r.map(c=>mt(c)))};R(`checking the ${r.length} worktree(s) whose branch is gone on the remote \u2026`);let s=sa(e,{...o,dryRun:!0}).entries.filter(c=>c.outcome==="would-remove").map(c=>c.path);for(let c of tD({gone:r.length,proven:s}))R(c);if(s.length===0)return;if(!rD(await Bd(nD(s.length)))){R(`kept. Later: ${xt(t,"maind feature done --merged")}`);return}let l=sa(e,{...o,dryRun:!1});for(let c of Hd(l,!1))R(c)}a(eJ,"offerStartSweep");function Lb(e){return/^[A-Za-z0-9_./~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}a(Lb,"shellPath");var Fb="ACTION:";function oD(e,t){return[`${Fb} the accepted plan is not attached yet \u2014 create the work object WITH it, inside the worktree (ADR-334):`,` cd ${Lb(e)} && maind object create --title "<title>" --anchor <repo-rel-path> --plan ${Lb(t)} --bind-branch`]}a(oD,"startPlanHintLines");function iD(e){let t=e.planPath?["--plan",e.planPath]:[],n=e.parentId?["--parent",e.parentId]:[];return e.title!==void 0?["create","--title",e.title,...n,"--bind-branch",...t]:e.objectId?["bind","--object",e.objectId,...t]:null}a(iD,"startObjectArgv");function Vd(e,t=[]){let n=`cd ${Lb(e)} &&`,r=t.flatMap(o=>[` this session is bound to ${`${o.key??o.id} "${o.title.length>60?`${o.title.slice(0,59)}\u2026`:o.title}"`}:`,` the same work (a note, a doc, one more fix): ${n} maind object bind --object ${o.id}`,` follow-up work of it: ${n} maind object create --title "<title>" --parent ${o.id} --bind-branch`]);return r.length>0?[`${Fb} this branch has no work object yet \u2014 place it before the first commit:`,...r,` independent work: ${n} maind object create --title "<title>" --anchor <repo-rel-path> --bind-branch`,' next time: maind feature start <name> --object <KEY> (or --title "<title>" --parent <KEY>)']:[`${Fb} this branch has no work object yet \u2014 create one now; without it the plan cannot show the work as in progress:`,` ${n} maind object create --title "<title>" --anchor <repo-rel-path> --bind-branch`,` or bind an existing one: ${n} maind object bind --object <uuid> (uuid of a key: maind object resolve <KEY> --json)`,' next time: maind feature start <name> --title "<title>" (or --object <KEY>)']}a(Vd,"startNoObjectLines");async function sD({args:e,root:t,cfg:n,deps:r}){let o=e.planFile?Q6(e.planFile):null;if(o!==null){let l=ny(o,c=>Z6(c,"utf8"));if(!l.ok)return R(l.reason),2}let i=ui(t),s=DA(r,{repoRoot:t,name:e.name,cfg:n,requirements:i});switch(s.kind){case"invalid-name":return R(s.reason),2;case"path-exists":return R(`${s.path} already exists \u2014 pick another name or remove it first.`),1;case"branch-exists":return R(`branch ${s.branch} already exists.`),1;case"start-point-missing":return R(`${s.startPoint} does not exist \u2014 this repository has no '${s.remote}' remote (or it was never fetched). maind feature needs one: ship opens a pull request against it.`),1;case"no-base-branch":return R(`could not determine the default branch of '${n.remote}'. Set "baseBranch" in ${Zt}.`),1;case"worktree-failed":return R(`git refused to create the worktree at ${s.path}.`),1;case"ok":{let l=tl(t,s.path,fi(t,s.path));l.length>0&&R(`provisioned ${l.length} declared path(s) from the main checkout.`),Er(n,s.path),R(`${s.branch} from ${s.startPoint}`);let c=mh(t);c&&c.length>0&&await eJ(r,t,n,c.map(h=>h.path));let u=null,d=null,f=!1,p=[];if(e.object!==void 0){let h=await bn(e.object);h===null?(R(`could not resolve ${e.object} to a work object you can see \u2014 the branch is not bound.`),p.push(...Vd(s.path,await Ou())),f=!0):(u=h.id,h.status==="passed"&&R(`${h.key??e.object} is already passed \u2014 this branch adds to finished work: promote it with --progress-only.`))}if(e.parent!==void 0){let h=await bn(e.parent);h===null?(R(`could not resolve --parent ${e.parent} to a work object you can see \u2014 no object was created.`),p.push(...Vd(s.path,await Ou())),f=!0):d=h.id}let m=f?null:iD({objectId:u,...e.title!==void 0?{title:e.title}:{},parentId:d,planPath:o});m!==null?await Et(Rt(m),_$(s.path,{quietStdout:!0}))!==0&&(f=!0):f||(o!==null?p.push(...oD(s.path,o)):p.push(...Vd(s.path,await Ou()))),process.stdout.write(`${s.path}
540
540
  `);for(let h of p)R(h);return f?1:0}}}a(sD,"runStart");import{readdirSync as aJ,statSync as lJ}from"node:fs";import{basename as cJ,dirname as uJ,join as mD}from"node:path";import{lstatSync as tJ,readdirSync as nJ}from"node:fs";import{join as rJ}from"node:path";var oJ={readdir:a(e=>nJ(e),"readdir"),lstat:a(e=>tJ(e),"lstat")},iJ=new Set(["node_modules",".git"]);function aD(e,t=oJ){let n=0;try{t.lstat(e)}catch{return null}let r=[e];for(;r.length>0;){let o=r.pop(),i;try{i=t.readdir(o)}catch{continue}for(let s of i){if(iJ.has(s))continue;let l=rJ(o,s),c;try{c=t.lstat(l)}catch{continue}c.isDirectory()?r.push(l):c.isFile()&&c.nlink===1&&(n+=typeof c.blocks=="number"?c.blocks*512:c.size)}}return n}a(aD,"ownBytes");var sJ="ownBytes counts allocated bytes of files outside node_modules; node_modules is left out because pnpm links or clones it from its store, so removing it frees little";function lD(e,t,n){let r=0,o=e.entries.map(i=>{if(i.outcome==="kept")return{path:i.path,branch:i.branch,outcome:"kept",reason:i.reason};if(i.outcome==="removed")return{path:i.path,branch:i.branch,outcome:"removed",via:i.via,...i.branchKept?{branchKept:i.branchKept}:{}};let s=n(i.path);return typeof s=="number"&&(r+=s),{path:i.path,branch:i.branch,outcome:"would-remove",via:i.via,ownBytes:s}});return{version:1,dryRun:t,worktrees:o,orphans:e.orphans,branches:e.branches,...e.remoteBranches?{remoteBranches:e.remoteBranches}:{},reclaimableOwnBytes:r,sizeNote:sJ}}a(lD,"sweepJson");function uD(e){return e==="github"?"delete_branch_on_merge":"remove_source_branch_after_merge"}a(uD,"settingName");var dD={github:"GitHub",gitlab:"GitLab"},cD={github:"admin",gitlab:"maintainer"};function fD(e,t){let n=uD(e.kind),r=dD[e.kind],o=e.read();if(o===null)return{lines:[`${r} did not say whether it deletes merged branches (${n}) \u2014 not readable with your login.`],exitCode:1};if(o)return{lines:[`${r} deletes the source branch after every merge (${n} is on) \u2014 merges outside promote leave nothing behind.`],exitCode:0};if(!t)return{lines:[`${r} keeps the source branch after a merge (${n} is off): every merge outside promote leaves one behind.`,`maind feature branch-cleanup --enable turns it on (needs ${cD[e.kind]} rights on the repository); until then, maind feature done --merged --remote sweeps them.`],exitCode:0};let i=e.enable();if(!i.ok)return{lines:[`${r} refused to turn on ${n}${i.err?`: ${i.err}`:""}.`,`It needs ${cD[e.kind]} rights on the repository \u2014 someone who has them can run maind feature branch-cleanup --enable.`],exitCode:1};let s=e.read();return s!==!0?{lines:[`${r} accepted the change, but ${n} reads ${s===null?"unreadable":"off"} afterwards \u2014 check the repository settings.`],exitCode:1}:{lines:[`${n} is on: ${r} now deletes the source branch after every merge.`],exitCode:0}}a(fD,"branchCleanup");function pD(e){return`${dD[e]} does not delete source branches on merge (${uD(e)} is off), so every merge outside promote leaves one behind \u2014 maind feature branch-cleanup --enable turns it on.`}a(pD,"sweepSettingHint");function dJ(e,t){let n=uJ(e),r=`${cJ(e)}-`,o=new Set(t.map(l=>mt(l))),i;try{i=aJ(n)}catch{return[]}let s=[];for(let l of i){if(!l.startsWith(r))continue;let c=mD(n,l);if(!o.has(mt(c)))try{lJ(mD(c,".git")).isFile()&&s.push(c)}catch{}}return s.sort()}a(dJ,"orphanDirs");async function hD({args:e,root:t,cfg:n,deps:r}){let o=e.dryRun===!0;if(o||P("git",["worktree","prune"],t),e.remote===!0&&!r.fetch(t,n.remote))return R(`could not fetch ${n.remote} \u2014 nothing on the remote was touched.`),1;let i=sa(r,{repoRoot:t,cfg:n,cwd:mt(process.cwd()),liveAgentCwds:Ud(),dryRun:o,real:mt,orphanDirs:dJ,...e.remote===!0?{remote:!0}:{}});if(e.json===!0)return process.stdout.write(`${JSON.stringify(lD(i,o,c=>aD(c)))}
541
541
  `),0;for(let c of Hd(i,o))R(c);let l=(i.remoteBranches??[]).filter(c=>c.outcome!=="kept").length>0?Gi(t):null;return l!==null&&l!=="none"&&Pd(l.kind,t).read()===!1&&R(pD(l.kind)),0}a(hD,"runDoneMerged");async function gD({args:e,root:t,cfg:n,deps:r,target:o}){if(e.whenFree===!0){R(`[${new Date().toISOString()}] waiting until nothing stands in ${o.worktree} any more, then: ${Ie("done",o)}`);let s=B$({exists:a(l=>r.exists(l),"exists"),occupants:a(l=>Su(l,{excludeParent:!1}),"occupants"),sleep:a(l=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,l),"sleep"),now:a(()=>Date.now(),"now")},o.worktree);if(s.kind==="gone")return R(`[${new Date().toISOString()}] ${o.worktree} is already gone \u2014 nothing to do.`),0;if(s.kind==="timeout")return R(`[${new Date().toISOString()}] gave up waiting \u2014 ${s.occupants===null?"who stands in it could not be determined":`still the working directory of ${mo(s.occupants)}`}. The worktree stays; \`maind feature done --merged\` picks it up later.`),1;R(`[${new Date().toISOString()}] ${o.worktree} is free (after ${Math.round(s.waitedMs/1e3)} s) \u2014 cleaning up.`)}if(r.exists(o.worktree)&&Pn(mt(process.cwd()),mt(o.worktree))){let s=r.worktreeList(t)[0]?.path??t;for(let l of SA({worktree:o.worktree,cleanup:xt(s,Ie("done",o))}))R(l);return 1}let i=ia(r,{repoRoot:t,name:o.label,cfg:n,target:o});switch(i.kind){case"invalid-name":return R(i.reason),2;case"dirty":return R(`${i.path} has uncommitted changes \u2014 commit or discard them first.`),1;case"occupied":{let s=r.worktreeList(t)[0]?.path??t;return R(`${i.path} is still the working directory of ${mo(i.occupants)} \u2014 removing it would leave that shell in a deleted directory. Nothing was removed.`),R(` in that terminal: cd ${rt(s)} \u2014 then run again: ${xt(s,Ie("done",o))}`),1}case"remove-failed":return R(`git refused to remove the worktree at ${i.path}.`),1;case"pr-open":return R(`PR #${i.prNumber} for ${i.branch} is still open \u2014 nothing was removed.${i.url?` ${i.url}`:""}`),R(` merge it first (${Ie("promote",o)}), or close it and run done again.`),1;case"not-landed":return R(`${i.reason} \u2014 nothing was removed.`),i.path&&R(` if the work is abandoned, remove only the worktree (the branch stays): git worktree remove ${i.path}`),1;case"would-remove":return R(`${o.branch} is proven merged and would be removed.`),0;case"branch-unverified":return R(`worktree removed, but ${i.branch} was kept: ${i.reason}.`),R(` delete it yourself once you are sure: git branch -D ${i.branch}`),1;case"ok":return R(`${i.removedWorktree?"worktree removed":"no worktree to remove"}, ${i.deletedBranch?`branch deleted (${i.via==="squash-proof"?"via the squash-merge proof":`it is contained in ${n.remote}/${n.baseBranch??r.defaultBranch(t)??"the default branch"}`})`:"no branch to delete"}.`),0}}a(gD,"runDone");async function yD({root:e,cfg:t,deps:n}){for(let r of jA(n,{repoRoot:e,cfg:t}))process.stdout.write(`${r.name} ${r.branch} ${r.path}