@maind-dev/cli 0.167.0 → 0.168.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -268,7 +268,7 @@ maind: and re-run \`maind launch claude\`. (Or launch without routing: \`maind l
268
268
  `,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(`
269
269
  `);return{stdout:e.toml??`(using existing config: ${e.configPath})
270
270
  `,stderr:n+`
271
- `}}a(OA,"renderDryRun");import{createRequire as $2}from"node:module";function T2(){return"0.167.0";try{return $2(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a(T2,"resolveVersion");var fe=T2();var L2=5e3;function wt(e){process.stderr.write(`maind: ${e}
271
+ `}}a(OA,"renderDryRun");import{createRequire as $2}from"node:module";function T2(){return"0.168.0";try{return $2(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a(T2,"resolveVersion");var fe=T2();var L2=5e3;function wt(e){process.stderr.write(`maind: ${e}
272
272
  `)}a(wt,"err");function F2(e){return e instanceof Error?e.message:String(e)}a(F2,"msg");var B2=new Set(["--config","--route","--mcp-url"]);function NA(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("-")){B2.has(i)&&o++;continue}r=i;break}return{agent:r,dryRun:n("--dry-run"),config:t("--config")??null,route:t("--route")??bA,direct:n("--direct"),noFallback:n("--no-fallback"),noInstall:n("--no-install"),json:n("--json"),mcpUrl:t("--mcp-url")??null}}a(NA,"parseLaunchArgs");var U2={probe(e,t){let n=IA(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 IA("uv",[...e],{stdio:["ignore","inherit","inherit"]}).status},spawnInteractive(e){let t=Date.now();return new Promise(n=>{let r=!1,o=C2(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),L2).unref()}),i=r.callTool("get_template",{template_id:kA}).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=P2(e);n&&n!=="."&&N2(n,{recursive:!0}),M2(e,t,"utf8")},readFile(e){try{return D2(e,"utf8")}catch{return null}},fileExists(e){return I2(e)},repoRoot(){try{let e=O2("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 Lo()},homeDir(){return j2()},env:process.env,platform:process.platform};function H2(e,t){return e!==null?Dg(e,".maind",Eg):Dg(t,Eg)}a(H2,"resolveRoutesPath");async function DA(e,t=U2){let n=_A(e.agent);if(n.kind==="unknown")return wt(`usage: maind launch <agent> [--dry-run] [--config <path>] [--route <name>] [--direct] [--no-fallback] [--no-install] \u2014 supported: ${Ag.join(", ")}`),2;if(n.kind==="planned")return wt(`agent '${n.agent}' is planned but not yet supported \u2014 v1 supports: ${Ag.join(", ")}.`),2;if(e.json&&!e.dryRun)return wt("--json is only valid together with --dry-run (stdout belongs to the agent session)."),2;let r=n.agent;if(e.direct)return wt(CA()),MA(t,Og(r));let o=wA(t.env);o.warning!==null&&wt(o.warning);let i,s,l;if(e.config!==null){if(!t.fileExists(e.config))return wt(`config not found: ${e.config}`),2;let f=t.readFile(e.config);if(f===null||SA(f,e.route)===null)return wt(`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:xA(f,e.route);if(s=vA(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)`;wt(`using builtin routing policy (${m}).`)}i=H2(t.repoRoot(),t.userConfigDir())}let c=wu,u=t.probe(wu,["--version"]).ok;if(e.dryRun){let f={agent:r,configPath:i,configSource:l,toml:s,argv:Cg(c,r,e.route,i),backendKind:o.kind,switchyardDetected:u},p=OA(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 wt(`switchyard not found (--no-install). Install it with:
273
273
  maind: ${vu}`),1;if(!t.probe("uv",["--version"]).ok)return wt(AA()),1;if(wt(EA()),t.install(yA),t.probe(wu,["--version"]).ok)u=!0;else{let f=Dg(t.homeDir(),".local","bin",t.platform==="win32"?"switchyard.exe":"switchyard");t.probe(f,["--version"]).ok&&(c=f,u=!0)}if(!u)return Ng(t,e,r,$A())}if(l!=="flag"&&s!==null)try{t.writeConfig(i,s)}catch(f){return wt(`could not write ${i}: ${F2(f)}`),1}let d=await t.spawnInteractive(Cg(c,r,e.route,i));return d.spawnError!==null?Ng(t,e,r,`could not start switchyard (${d.spawnError})`):RA(d.code,d.signal,d.elapsedMs)==="fallback-eligible"?Ng(t,e,r,`switchyard exited with code ${d.code} after ${(d.elapsedMs/1e3).toFixed(1)}s`):Ig(d.code,d.signal)}a(DA,"runLaunch");async function Ng(e,t,n,r){return t.noFallback?(wt(`${r} (--no-fallback set \u2014 not degrading to a direct spawn).`),1):(process.stderr.write(TA(r)+`
274
274
  `),MA(e,Og(n)))}a(Ng,"degradeOrFail");async function MA(e,t){let n=await e.spawnInteractive(t);return n.spawnError!==null?(wt(`'${t[0]}' not found on PATH \u2014 install the agent CLI first (${n.spawnError}).`),1):Ig(n.code,n.signal)}a(MA,"spawnAndPropagate");var Mg="tests:";function xu(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(xu,"parseOverride");function G2(e){return e==="open"||e==="warn"}a(G2,"objectCarriesOverride");async function Su(e,t,n){let r=[];for(let i of e)!t.has(i.gate)&&!i.gate.startsWith(Mg)&&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`):G2(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(Su,"checkOverrides");function jA(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(jA,"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 Ru=["squash","merge","rebase"];function Eu(e){return typeof e=="string"&&Ru.includes(e)}a(Eu,"isMergeMethod");function LA(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(LA,"githubMergeMethods");function FA(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(FA,"gitlabMergeMethods");function jg(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?Ru.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(jg,"chooseMergeMethod");var K2={squash:"squash",merge:"merge commit",rebase:"rebase"};function mi(e){return K2[e]}a(mi,"methodLabel");function Pg(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 ${mi(e.method)} (${t[e.source]})`}a(Pg,"methodLine");function Lg(e){let t=e.source==="flag"?"--merge-method":"mergeMethod in .maind/feature.json",n=e.allowed.length>0?e.allowed.map(mi).join(", "):"none";return[`${t} asks for ${mi(e.method)}, and this repository's forge does not allow it (allowed: ${n}).`,"Nothing ran and nothing was merged."]}a(Lg,"notAllowedLines");function Au(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(Au,"rebaseMergeCommitLines");import{readFileSync as c$}from"node:fs";import{join as u$}from"node:path";import{spawn as W2,spawnSync as q2}from"node:child_process";function Fg(e){return e==="work"||e==="always"||e==="off"}a(Fg,"isStayAwakeSetting");function V2(e,t){if(e.CI||e.NODE_TEST_CONTEXT)return"off";let n=e.MAIND_STAY_AWAKE?.trim().toLowerCase();return Fg(n)?n:t??"work"}a(V2,"resolveStayAwake");function Y2(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(Y2,"inhibitCommand");function z2(e,t,n){let r=null,o=a(()=>{if(e==="off"||r!==null)return;let s=Y2(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(z2,"makeAwake");function X2(e){try{return q2("sh",["-c",`command -v ${e}`],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}a(X2,"hasBinary");var J2={platform:process.platform,pid:process.pid,has:X2,start:a((e,t)=>{try{let n=W2(e,[...t],{stdio:"ignore"});return n.on("error",()=>{}),n.unref(),typeof n.pid=="number"?()=>n.kill():null}catch{return null}},"start")},ho=null;function $u(e,t,n={}){let r=ho===null;return r&&(ho=z2(V2(n.env??process.env,e),t,n.deps??J2)),ho.work(),{end:a(()=>{r&&(ho?.end(),ho=null)},"end")}}a($u,"beginAwake");function BA(){ho?.work()}a(BA,"awakeWork");function UA(){ho?.waiting()}a(UA,"awakeWaiting");import{execFileSync as oV}from"node:child_process";import{realpathSync as iV}from"node:fs";function Tu(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(Tu,"serverPlanAnswer");var ua="MAIND_GATE_OBJECT_REASON",Z2=/^[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 Q2(e){if(e===null)return!1;let t=e.trim();return t.length<4?!1:!["1","true","yes","on","skip"].includes(t.toLowerCase())}a(Q2,"isReason");function Cu(e){let t=eV(e);return t.kind!=="linked"&&Q2(e.overrideReason)?{kind:"overridden",reason:e.overrideReason.trim()}:t}a(Cu,"classifyWorkObject");function eV(e){if(e.branch===null)return{kind:"detached"};let t=e.objectId?.trim()??"";return t.length===0?{kind:"missing",branch:e.branch}:Z2.test(t)?{kind:"linked",objectId:t,objectKey:e.objectKey?.trim()||null,planRevision:e.planRevision?.trim()||null}:{kind:"malformed",branch:e.branch,value:t}}a(eV,"judge");function Ou(e){return e.kind==="linked"||e.kind==="overridden"}a(Ou,"workObjectPasses");function HA(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(HA,"workObjectLines");function Bg(e){return`${e.dir}\0${e.check??""}`}a(Bg,"checkKey");function GA(e){return`${e.replace(/[/\\]+$/,"")}-apply`}a(GA,"applyCheckoutPath");function KA(e){return[...new Set(e.filter(t=>t.command!==null).map(t=>t.trigger))].sort()}a(KA,"applyTriggers");function ot(e){return/^[A-Za-z0-9_./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}a(ot,"shellQuote");function tV(e,t){let n=t.replace(/^\/+|\/+$/g,"");return n.length===0?e:`${e.replace(/\/+$/,"")}/${n}`}a(tV,"joinAbs");function nV(e){return e.endsWith("/")?e:`${e}/`}a(nV,"withPrefix");function rV(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(rV,"defaultPostMergeSteps");function Ug(e,t,n){let r=e.map(s=>s.trim()).filter(s=>s.length>0),o=t??rV(r),i=[];for(let s of o){let l=nV(s.when),c=r.filter(h=>h.startsWith(l));if(c.length===0)continue;let u=tV(n,s.cwd??""),d=`cd ${ot(u)} && `,f=a((h,b)=>h===void 0?void 0:h.split("{name}").join(b),"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(b=>!b.startsWith("_"))){let b=f(s.note,h),y=f(s.run,h),k=f(s.check,h);i.push({reason:`${l}${h}/ changed`+(b?` \u2014 ${b}`:""),command:y?d+y:null,trigger:l,dir:u,check:y&&k?k:null})}let m=p.filter(h=>h.startsWith("_"));m.length>0&&i.push({reason:`${m.map(h=>`${l}${h}/`).join(", ")} changed \u2014 shared code, no target of its own: redeploy what imports it`,command:null,trigger:l,dir:u,check:null})}return i}a(Ug,"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 ${ot(i)} worktree remove ${ot(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(Bg(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 da(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(da,"decideCompletion");function qA(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(qA,"missingCompletionLines");function Hg(e){if(!e.required)return null;let t=Cu({branch:e.branch,objectId:e.boundObject,objectKey:null,overrideReason:e.overrideReason,planRevision:null});return Ou(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: ${hi}="<reason>" ${e.promoteCommand} --yes`,"Nothing was merged."]}a(Hg,"unboundObjectLines");var hi=ua;function Ln(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)}a(Ln,"cwdInside");function vt(e,t){return`cd ${ot(e)} && ${t}`}a(vt,"cleanupCommand");function VA(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(VA,"alreadyMergedLines");function YA(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(YA,"doneInsideLines");function zA(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(zA,"deferredCleanupLines");function XA(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:`,` ${vt(e.mainRoot,e.doneCommand)}`,` or, later, for every merged worktree at once: ${vt(e.mainRoot,"maind feature done --merged")}`]}a(XA,"keptWorktreeLines");async function Gg(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(Gg,"recoverBinding");async function fa(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(fa,"ensurePrLinked");function gi(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(gi,"linkMismatchLines");function JA(e,t){let n=t?.trim().toUpperCase()??null;return e.filter(r=>r.toUpperCase()!==n)}a(JA,"fanOutKeys");function ZA(e,t){let n=ot(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 (${Pc(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:[` ${Pc(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(ZA,"fastForwardLines");function sV(e){let t=[],n=null,r="";for(let o of e.split(`
@@ -371,11 +371,11 @@ Fallback: run the MCP calls from an agent session (work_object_create/link_ref/r
371
371
  `),S.doc_missing===!0&&t.err(`maind: documentation missing (doc_duty=${String(S.doc_duty)}) \u2014 the object has no linked document and no Doc-Decision exception. Name the object key in a Markdown document of the change, or add a trailer \`Doc-Decision: none - <reason>\` to a commit.
372
372
  `);let I=S.fan_out_of,F=I?` to ${S.object?.key??e.object} (ref of ${I.key??"another object"})`:"";return t.err(e.event==="merge"&&e.completes!==!0?`maind: merge reported for ${e.ref}${F} as progress \u2014 the object was NOT closed.
373
373
  `:`maind: ${e.event} reported for ${e.ref}${F}.
374
- `),0}catch(w){return r(w instanceof Error?w.message:String(w))}finally{y.session?.source==="announced"&&await vi(b,m,y.session.sessionId)}}a(Rt,"runObject");function WV(e,t,n){let r=typeof n.linked_object_id=="string"?n.linked_object_id:null,o=typeof n.linked_object_key=="string"?n.linked_object_key:null,i=o??r;return[i?`maind: object link: ${e} is already linked to ${i}${o&&r?` (${r})`:""}, not to ${t??"this object"} \u2014 refs are never re-pointed.`:`maind: object link: ${e} is already linked to another object you cannot see, not to ${t??"this object"} \u2014 refs are never re-pointed.`,` if the work belongs there, bind the branch to it: maind object bind --object ${r??"<uuid>"}`,` if the link is wrong, a person removes it on ${i??"that object"}'s page (or propose it: work_object_update refs_remove).`]}a(WV,"refAlreadyLinkedLines");async function Fn(e){let t=await kn(e);return t===null?null:{id:t.id,key:t.key}}a(Fn,"lookupObjectByRef");async function kn(e){let t,n;try{let s=Ae();if(n=dt().projectKey,!n)return null;t=new Me({apiKey:s.apiKey,deviceId:s.deviceId,clientVersion:fe,projectKey:n})}catch{return null}let r=null,o={session:null},i=wa(t,n,xt,o);try{if(r=o.session=await _a(t,n,void 0,xt),r===null)return null;let s=await i.callTool("get_my_work_objects",{project_key:n,session_id:r.sessionId,keys:[e]});if(s.ok!==!0||!Array.isArray(s.resolved)||s.resolved.length!==1)return null;let l=s.resolved[0];return typeof l.id!="string"?null:{id:l.id,key:typeof l.key=="string"?l.key:null,status:typeof l.status=="string"?l.status:"unknown"}}catch{return null}finally{o.session?.source==="announced"&&await vi(t,n,o.session.sessionId)}}a(kn,"resolveWorkObject");async function Fu(e=xt){try{let t=e.projectKey();if(!t)return[];let n=py(t,void 0,e);if(n===null)return[];let r=e.resolveAuth(),i=await e.createClient({apiKey:r.apiKey,deviceId:r.deviceId,clientVersion:fe,projectKey:t}).callTool("list_active_sessions",{project_key:t,session_id:n.sessionId});if(i.ok!==!0||!Array.isArray(i.sessions))return[];let s=i.sessions.find(l=>l.is_self===!0);return!s||!Array.isArray(s.bound_objects)?[]:s.bound_objects.map(l=>l).filter(l=>typeof l.id=="string"&&wi.test(l.id)&&typeof l.title=="string").map(l=>({id:l.id,key:typeof l.key=="string"?l.key:null,title:l.title})).slice(0,3)}catch{return[]}}a(Fu,"sessionBoundObjects");async function yo(e,t){let n,r;try{let s=Ae();if(r=dt().projectKey,!r)return{kind:"failed",reason:"no project key (no git remote)"};n=new Me({apiKey:s.apiKey,deviceId:s.deviceId,clientVersion:fe,projectKey:r})}catch(s){return{kind:"failed",reason:s instanceof Error?s.message:String(s)}}let o={session:null},i=wa(n,r,xt,o);try{return o.session=await _a(n,r,void 0,xt),o.session===null?{kind:"failed",reason:"no session could be announced"}:{kind:"ok",body:await i.callTool(e,sy(r,o.session.sessionId,t))}}catch(s){return W$(s)}finally{o.session?.source==="announced"&&await vi(n,r,o.session.sessionId)}}a(yo,"callMergeApprovalTool");function sy(e,t,n){return{project_key:e,session_id:t,...n.objectId!==null?{object_id:n.objectId}:{},ref:n.ref,head_sha:n.headSha,...n.base!==void 0?{base:n.base}:{},...n.chain!==void 0?{chain:n.chain}:{}}}a(sy,"mergeApprovalToolArgs");function W$(e){return e instanceof ut&&e.kind==="unknown_tool"?{kind:"unknown_tool"}:e instanceof ut&&e.kind==="invalid_params"?{kind:"invalid_params",reason:`the server refused the arguments \u2014 ${e.issues.map(n=>`${(n.path??[]).join(".")||"(input)"}: ${n.message??n.code??"invalid"}`).join("; ")||e.message}`}:e instanceof Ws?{kind:"failed",reason:e.message,quota:e.quota}:e instanceof gn?{kind:"failed",reason:e.message,status:e.status}:e instanceof ur?{kind:"failed",reason:e.message,network:!0}:{kind:"failed",reason:e instanceof Error?e.message:String(e)}}a(W$,"mergeApprovalFailure");var qV=uy*6e4/2;function VV(e){if(e===null||typeof e!="object")return!1;let t=e;return t.ok===!1&&t.error==="session_not_announced"}a(VV,"isSessionNotAnnounced");function xi(e=xt,t=Date.now){let n=null,r=null,o=0,i=a(()=>{if(n!==null)return n;try{let u=e.resolveAuth(),d=e.projectKey();return d?(n={client:e.createClient({apiKey:u.apiKey,deviceId:u.deviceId,clientVersion:fe,projectKey:d}),projectKey:d},n):{kind:"failed",reason:"no project key (no git remote)"}}catch(u){return{kind:"failed",reason:u instanceof Error?u.message:String(u)}}},"connect"),s=a(async u=>(r=await my(u.client,u.projectKey,e),o=t(),r!==null),"announceOwn"),l=a(async u=>r===null?(r=py(u.projectKey,void 0,e),r!==null||await s(u)):r.source!=="announced"||t()-o<qV?!0:(await u.client.callTool("announce_session",{project_key:u.projectKey,session_id:r.sessionId,focus:"cli:object",ttl_minutes:uy})).ok===!0?(o=t(),!0):s(u),"ensureSession"),c=a(async(u,d)=>{let f=i();if("kind"in f)return f;if(!await l(f)||r===null)return{kind:"failed",reason:"no session could be announced"};let p=await f.client.callTool(u,sy(f.projectKey,r.sessionId,d));if(VV(p)&&r.source!=="flag"&&r.source!=="env"){if(!await s(f)||r===null)return{kind:"ok",body:p};p=await f.client.callTool(u,sy(f.projectKey,r.sessionId,d))}return{kind:"ok",body:p}},"attempt");return{async call(u,d){for(let f=!1;;f=!0)try{return await c(u,d)}catch(p){if((p instanceof gn||p instanceof ur)&&(n=null),p instanceof gn&&p.status===404&&!f)continue;return W$(p)}},async close(){let u=r;if(r=null,u?.source!=="announced")return;let d=i();"kind"in d||await vi(d.client,d.projectKey,u.sessionId)}}}a(xi,"openMergeApprovalCaller");async function Bu(e,t){let n,r;try{let s=Ae();if(r=dt().projectKey,!r)return!1;n=new Me({apiKey:s.apiKey,deviceId:s.deviceId,clientVersion:fe,projectKey:r})}catch{return!1}let o={session:null},i=wa(n,r,xt,o);try{return o.session=await _a(n,r,void 0,xt),o.session===null?!1:(await i.callTool("work_object_post_comment",{project_key:r,session_id:o.session.sessionId,object_id:e,body:t})).ok===!0}catch{return!1}finally{o.session?.source==="announced"&&await vi(n,r,o.session.sessionId)}}a(Bu,"postObjectComment");var ka=a(e=>typeof e=="string"&&e.length>0?e:null,"str"),q$=a(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num"),V$=a(e=>typeof e=="boolean"?e:null,"bool");function YV(e){if(e===null||typeof e!="object")return null;let t=e,n=ka(t.state);return n===null?null:{state:n,isOwnUser:V$(t.is_own_user),expiresInSeconds:q$(t.expires_in_seconds),sessionIdShort:ka(t.session_id_short)}}a(YV,"takeOf");function zV(e){return Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"&&t.is_self!==!0).map(t=>({sessionIdShort:ka(t.session_id_short),isOwnUser:V$(t.is_own_user),title:ka(t.title),focus:ka(t.focus),lastSeenSeconds:q$(t.last_seen_seconds)})):[]}a(zV,"bindingsOf");function F$(e){let t=Math.round(e/60);return t<60?`${t}m`:`${Math.floor(t/60)}h ${t%60}m`}a(F$,"duration");function XV(e){if(e.unresolved)return[`${e.ident} UNRESOLVED`];let t=[`${e.key??e.id} ${e.status} ${e.availability??"-"} ${e.title}`],n=a((r,o)=>`${r===!0?"your":r===!1?"a teammate's":"a"} session${o?` ${o}`:""}`,"who");e.take&&e.take.state==="held"&&t.push(` taken by ${n(e.take.isOwnUser,e.take.sessionIdShort)}`+(e.take.expiresInSeconds!==null?` \u2014 lease ${F$(e.take.expiresInSeconds)} left`:""));for(let r of e.bindings??[]){let o=r.title??r.focus;t.push(` bound: ${n(r.isOwnUser,r.sessionIdShort)}`+(o?` \u2014 ${o}`:"")+(r.lastSeenSeconds!==null?` (seen ${F$(r.lastSeenSeconds)} ago)`:""))}return e.availabilityFact&&e.availability!=="free"&&t.push(` ${e.availabilityFact}`),t}a(XV,"resolveLines");function ay(e){return/^[a-z][a-z0-9_-]{0,31}:/.test(e.trim())}a(ay,"isRefIdent");function B$(e,t,n){let r=e.trim(),o=r.toLowerCase(),i=t.find(s=>s.id?.toLowerCase()===o||s.key?.toLowerCase()===o||(s.former_keys??[]).some(l=>l.toLowerCase()===o));if(i)return i;if(ay(r)){let s=t.find(l=>l.source_ref===r||(l.refs??[]).includes(r));if(s)return s;if(n&&t.length===1)return t[0]}return null}a(B$,"matchResolvedRow");async function JV(e,t){let n=await Ht(e);if(!n.ok)return process.stderr.write(`maind: object resolve: ${n.reason}
374
+ `),0}catch(w){return r(w instanceof Error?w.message:String(w))}finally{y.session?.source==="announced"&&await vi(b,m,y.session.sessionId)}}a(Rt,"runObject");function WV(e,t,n){let r=typeof n.linked_object_id=="string"?n.linked_object_id:null,o=typeof n.linked_object_key=="string"?n.linked_object_key:null,i=o??r;return[i?`maind: object link: ${e} is already linked to ${i}${o&&r?` (${r})`:""}, not to ${t??"this object"} \u2014 refs are never re-pointed.`:`maind: object link: ${e} is already linked to another object you cannot see, not to ${t??"this object"} \u2014 refs are never re-pointed.`,` if the work belongs there, bind the branch to it: maind object bind --object ${r??"<uuid>"}`,` if the link is wrong, a person removes it on ${i??"that object"}'s page (or propose it: work_object_update refs_remove).`]}a(WV,"refAlreadyLinkedLines");async function Fn(e){let t=await kn(e);return t===null?null:{id:t.id,key:t.key}}a(Fn,"lookupObjectByRef");async function kn(e){let t,n;try{let s=Ae();if(n=dt().projectKey,!n)return null;t=new Me({apiKey:s.apiKey,deviceId:s.deviceId,clientVersion:fe,projectKey:n})}catch{return null}let r=null,o={session:null},i=wa(t,n,xt,o);try{if(r=o.session=await _a(t,n,void 0,xt),r===null)return null;let s=await i.callTool("get_my_work_objects",{project_key:n,session_id:r.sessionId,keys:[e]});if(s.ok!==!0||!Array.isArray(s.resolved)||s.resolved.length!==1)return null;let l=s.resolved[0];return typeof l.id!="string"?null:{id:l.id,key:typeof l.key=="string"?l.key:null,status:typeof l.status=="string"?l.status:"unknown"}}catch{return null}finally{o.session?.source==="announced"&&await vi(t,n,o.session.sessionId)}}a(kn,"resolveWorkObject");async function Fu(e=xt){try{let t=e.projectKey();if(!t)return[];let n=py(t,void 0,e);if(n===null)return[];let r=e.resolveAuth(),i=await e.createClient({apiKey:r.apiKey,deviceId:r.deviceId,clientVersion:fe,projectKey:t}).callTool("list_active_sessions",{project_key:t,session_id:n.sessionId});if(i.ok!==!0||!Array.isArray(i.sessions))return[];let s=i.sessions.find(l=>l.is_self===!0);return!s||!Array.isArray(s.bound_objects)?[]:s.bound_objects.map(l=>l).filter(l=>typeof l.id=="string"&&wi.test(l.id)&&typeof l.title=="string").map(l=>({id:l.id,key:typeof l.key=="string"?l.key:null,title:l.title})).slice(0,3)}catch{return[]}}a(Fu,"sessionBoundObjects");async function yo(e,t){let n,r;try{let s=Ae();if(r=dt().projectKey,!r)return{kind:"failed",reason:"no project key (no git remote)"};n=new Me({apiKey:s.apiKey,deviceId:s.deviceId,clientVersion:fe,projectKey:r})}catch(s){return{kind:"failed",reason:s instanceof Error?s.message:String(s)}}let o={session:null},i=wa(n,r,xt,o);try{return o.session=await _a(n,r,void 0,xt),o.session===null?{kind:"failed",reason:"no session could be announced"}:{kind:"ok",body:await i.callTool(e,sy(r,o.session.sessionId,t))}}catch(s){return W$(s)}finally{o.session?.source==="announced"&&await vi(n,r,o.session.sessionId)}}a(yo,"callMergeApprovalTool");function sy(e,t,n){return{project_key:e,session_id:t,...n.objectId!==null?{object_id:n.objectId}:{},ref:n.ref,head_sha:n.headSha,...n.base!==void 0?{base:n.base}:{},...n.chain!==void 0?{chain:n.chain}:{},...n.waitingUntil!==void 0?{waiting_until:n.waitingUntil}:{}}}a(sy,"mergeApprovalToolArgs");function W$(e){return e instanceof ut&&e.kind==="unknown_tool"?{kind:"unknown_tool"}:e instanceof ut&&e.kind==="invalid_params"?{kind:"invalid_params",reason:`the server refused the arguments \u2014 ${e.issues.map(n=>`${(n.path??[]).join(".")||"(input)"}: ${n.message??n.code??"invalid"}`).join("; ")||e.message}`}:e instanceof Ws?{kind:"failed",reason:e.message,quota:e.quota}:e instanceof gn?{kind:"failed",reason:e.message,status:e.status}:e instanceof ur?{kind:"failed",reason:e.message,network:!0}:{kind:"failed",reason:e instanceof Error?e.message:String(e)}}a(W$,"mergeApprovalFailure");var qV=uy*6e4/2;function VV(e){if(e===null||typeof e!="object")return!1;let t=e;return t.ok===!1&&t.error==="session_not_announced"}a(VV,"isSessionNotAnnounced");function xi(e=xt,t=Date.now){let n=null,r=null,o=0,i=a(()=>{if(n!==null)return n;try{let u=e.resolveAuth(),d=e.projectKey();return d?(n={client:e.createClient({apiKey:u.apiKey,deviceId:u.deviceId,clientVersion:fe,projectKey:d}),projectKey:d},n):{kind:"failed",reason:"no project key (no git remote)"}}catch(u){return{kind:"failed",reason:u instanceof Error?u.message:String(u)}}},"connect"),s=a(async u=>(r=await my(u.client,u.projectKey,e),o=t(),r!==null),"announceOwn"),l=a(async u=>r===null?(r=py(u.projectKey,void 0,e),r!==null||await s(u)):r.source!=="announced"||t()-o<qV?!0:(await u.client.callTool("announce_session",{project_key:u.projectKey,session_id:r.sessionId,focus:"cli:object",ttl_minutes:uy})).ok===!0?(o=t(),!0):s(u),"ensureSession"),c=a(async(u,d)=>{let f=i();if("kind"in f)return f;if(!await l(f)||r===null)return{kind:"failed",reason:"no session could be announced"};let p=await f.client.callTool(u,sy(f.projectKey,r.sessionId,d));if(VV(p)&&r.source!=="flag"&&r.source!=="env"){if(!await s(f)||r===null)return{kind:"ok",body:p};p=await f.client.callTool(u,sy(f.projectKey,r.sessionId,d))}return{kind:"ok",body:p}},"attempt");return{async call(u,d){for(let f=!1;;f=!0)try{return await c(u,d)}catch(p){if((p instanceof gn||p instanceof ur)&&(n=null),p instanceof gn&&p.status===404&&!f)continue;return W$(p)}},async close(){let u=r;if(r=null,u?.source!=="announced")return;let d=i();"kind"in d||await vi(d.client,d.projectKey,u.sessionId)}}}a(xi,"openMergeApprovalCaller");async function Bu(e,t){let n,r;try{let s=Ae();if(r=dt().projectKey,!r)return!1;n=new Me({apiKey:s.apiKey,deviceId:s.deviceId,clientVersion:fe,projectKey:r})}catch{return!1}let o={session:null},i=wa(n,r,xt,o);try{return o.session=await _a(n,r,void 0,xt),o.session===null?!1:(await i.callTool("work_object_post_comment",{project_key:r,session_id:o.session.sessionId,object_id:e,body:t})).ok===!0}catch{return!1}finally{o.session?.source==="announced"&&await vi(n,r,o.session.sessionId)}}a(Bu,"postObjectComment");var ka=a(e=>typeof e=="string"&&e.length>0?e:null,"str"),q$=a(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num"),V$=a(e=>typeof e=="boolean"?e:null,"bool");function YV(e){if(e===null||typeof e!="object")return null;let t=e,n=ka(t.state);return n===null?null:{state:n,isOwnUser:V$(t.is_own_user),expiresInSeconds:q$(t.expires_in_seconds),sessionIdShort:ka(t.session_id_short)}}a(YV,"takeOf");function zV(e){return Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"&&t.is_self!==!0).map(t=>({sessionIdShort:ka(t.session_id_short),isOwnUser:V$(t.is_own_user),title:ka(t.title),focus:ka(t.focus),lastSeenSeconds:q$(t.last_seen_seconds)})):[]}a(zV,"bindingsOf");function F$(e){let t=Math.round(e/60);return t<60?`${t}m`:`${Math.floor(t/60)}h ${t%60}m`}a(F$,"duration");function XV(e){if(e.unresolved)return[`${e.ident} UNRESOLVED`];let t=[`${e.key??e.id} ${e.status} ${e.availability??"-"} ${e.title}`],n=a((r,o)=>`${r===!0?"your":r===!1?"a teammate's":"a"} session${o?` ${o}`:""}`,"who");e.take&&e.take.state==="held"&&t.push(` taken by ${n(e.take.isOwnUser,e.take.sessionIdShort)}`+(e.take.expiresInSeconds!==null?` \u2014 lease ${F$(e.take.expiresInSeconds)} left`:""));for(let r of e.bindings??[]){let o=r.title??r.focus;t.push(` bound: ${n(r.isOwnUser,r.sessionIdShort)}`+(o?` \u2014 ${o}`:"")+(r.lastSeenSeconds!==null?` (seen ${F$(r.lastSeenSeconds)} ago)`:""))}return e.availabilityFact&&e.availability!=="free"&&t.push(` ${e.availabilityFact}`),t}a(XV,"resolveLines");function ay(e){return/^[a-z][a-z0-9_-]{0,31}:/.test(e.trim())}a(ay,"isRefIdent");function B$(e,t,n){let r=e.trim(),o=r.toLowerCase(),i=t.find(s=>s.id?.toLowerCase()===o||s.key?.toLowerCase()===o||(s.former_keys??[]).some(l=>l.toLowerCase()===o));if(i)return i;if(ay(r)){let s=t.find(l=>l.source_ref===r||(l.refs??[]).includes(r));if(s)return s;if(n&&t.length===1)return t[0]}return null}a(B$,"matchResolvedRow");async function JV(e,t){let n=await Ht(e);if(!n.ok)return process.stderr.write(`maind: object resolve: ${n.reason}
375
375
  `),3;if(t)process.stdout.write(JSON.stringify(n.refs)+`
376
376
  `);else for(let r of n.refs)process.stdout.write(XV(r).join(`
377
377
  `)+`
378
- `);return 0}a(JV,"runResolve");async function Ht(e){let t;try{t=Ae()}catch(s){return{ok:!1,reason:s instanceof De?s.message:String(s)}}let n=dt().projectKey;if(!n)return{ok:!1,reason:"not a git repo with a remote \u2014 no project_key."};let r=new Me({apiKey:t.apiKey,deviceId:t.deviceId,clientVersion:fe,projectKey:n}),o={session:null},i=wa(r,n,xt,o);try{let s=o.session=await _a(r,n,void 0,xt);if(s===null)return{ok:!1,reason:"no session could be resolved."};let l=a(async p=>{let m=await i.callTool("get_my_work_objects",{project_key:n,session_id:s.sessionId,keys:p});return m.ok===!0&&Array.isArray(m.resolved)?m.resolved:null},"ask"),c=e.filter(p=>!ay(p)),u=c.length>0?await l(c):[];if(u===null)return{ok:!1,reason:"server did not answer."};let d=new Map;for(let p of e.filter(ay)){let m=await l([p.trim()]);if(m===null)return{ok:!1,reason:"server did not answer."};d.set(p,m)}return{ok:!0,refs:e.map(p=>{let m=d.has(p)?B$(p,d.get(p),!0):B$(p,u,!1);return!m||typeof m.id!="string"?{ident:p,unresolved:!0}:{ident:p,id:m.id,key:m.key??null,title:m.title??"",status:m.status??"unknown",anchors:(m.anchors??[]).filter(h=>typeof h.path_prefix=="string"&&(!h.project_key||h.project_key===n)).map(h=>h.path_prefix),...typeof m.doc_duty=="string"?{docDuty:m.doc_duty}:{},...typeof m.doc_missing=="boolean"?{docMissing:m.doc_missing}:{},...m.doc_in_review===!0?{docInReview:!0}:{},...typeof m.lesson_check=="string"?{lessonCheck:m.lesson_check}:{},...typeof m.has_plan=="boolean"?{hasPlan:m.has_plan}:{},...typeof m.availability=="string"?{availability:m.availability}:{},...typeof m.availability_fact=="string"?{availabilityFact:m.availability_fact}:{},..."take"in m?{take:YV(m.take)}:{},...Array.isArray(m.bindings)?{bindings:zV(m.bindings)}:{}}})}}catch(s){return{ok:!1,reason:s instanceof Error?s.message:String(s)}}finally{o.session?.source==="announced"&&await vi(r,n,o.session.sessionId)}}a(Ht,"lookupObjects");function ZV(e){return e==="dashboard"||e==="terminal"||e==="carried"?e:null}a(ZV,"readVia");function QV(e){if(typeof e!="object"||e===null)return null;let t=e.head_sha;return typeof t=="string"?t:null}a(QV,"readCarriedFrom");function by(e){let t=ZV(e.answered_via),n=t==="dashboard"&&e.verified!==!1;return{answeredVia:t,carriedFrom:QV(e.carried_from),verified:n,mfa:n&&typeof e.mfa=="boolean"?e.mfa:null}}a(by,"readProof");function eY(e){return{answeredVia:e.answeredVia,carriedFrom:e.carriedFrom,verified:e.verified,mfa:e.mfa}}a(eY,"proofOf");function bo(e){return e.answeredVia==="terminal"?" in a terminal (reported, not verified)":e.answeredVia==="carried"?` \u2014 carried from ${e.carriedFrom?e.carriedFrom.slice(0,7):"an earlier head"} across promote's own commits (reported: checked by the CLI, not verified)`:e.verified?` in a browser session (verified${e.mfa===!0?", with a second factor":e.mfa===!1?", without a second factor":""})`:e.answeredVia==="dashboard"?" (reported, not verified)":" through a channel this CLI does not know (not shown as verified)"}a(bo,"viaPhrase");function ko(e,t){return t?`${e}/planning/${t}`:e}a(ko,"approvalPageUrl");function Bn(e){if(e.ok!==!0)return null;let t=e.state;if(t!=="not_required"&&t!=="none"&&t!=="pending"&&t!=="approved"&&t!=="declined")return null;let n=typeof e.object=="object"&&e.object!==null?e.object:{},r=typeof e.decision=="object"&&e.decision!==null?e.decision:{},o=typeof e.pr=="object"&&e.pr!==null?e.pr:null;return{state:t,objectKey:typeof n.key=="string"?n.key:null,...by(r),pr:o&&typeof o.state=="string"?{state:o.state,headSha:typeof o.head_sha=="string"?o.head_sha:null}:null,...tY(e.conflict)}}a(Bn,"readApprovalState");function tY(e){if(typeof e!="object"||e===null)return{};let t=e;return typeof t.at!="string"||t.at.length===0?{}:{conflict:{reportedAt:t.at,hint:typeof t.hint=="string"&&t.hint.length>0?t.hint:null}}}a(tY,"readConflict");var gr={timeoutMs:30*6e4,intervalMs:15e3,slowAfterMs:5*6e4,slowIntervalMs:6e4,jitter:.1};function nY(e,t,n=Math.random){let o=e.slowAfterMs!==void 0&&e.slowIntervalMs!==void 0&&t>=e.slowAfterMs?e.slowIntervalMs:e.intervalMs,i=e.jitter??0;return i>0?Math.round(o*(1+i*(2*n()-1))):o}a(nY,"waitPauseMs");function Y$(e){let t=`every ${Si(e.intervalMs)}`;return e.slowAfterMs===void 0||e.slowIntervalMs===void 0||e.slowAfterMs>=e.timeoutMs?t:`${t} for the first ${Si(e.slowAfterMs)}, then every ${Si(e.slowIntervalMs)}`}a(Y$,"waitCadence");var rY=24*60*6e4,oY=4;function ky(e){let t=/^\s*(\d+)\s*([smh]?)\s*$/i.exec(e);if(!t)return null;let n=Number(t[1]),r=(t[2]??"").toLowerCase(),o=r==="s"?n*1e3:r==="h"?n*36e5:n*6e4;return o>0&&o<=rY?o:null}a(ky,"parseWaitDuration");function Si(e){return e%36e5===0?`${e/36e5} h`:e%6e4===0?`${e/6e4} min`:`${Math.round(e/1e3)} s`}a(Si,"humanDuration");async function _y(e,t,n){let r=n.now(),o=r+t.timeoutMs,i=e.until==="asked";e.announced!==!0&&n.note((i?`waiting until a merge approval for PR #${e.prNumber} at ${e.headSha.slice(0,7)} is asked on ${e.url} `:`waiting for a person to approve PR #${e.prNumber} at ${e.headSha.slice(0,7)} on ${e.url} `)+`(up to ${Si(t.timeoutMs)}, checking ${Y$(t)}).`);let s=0;for(;;){let l=await n.readState();if(l.kind==="unknown_tool")return{kind:"failed",reason:"the server cannot read merge approvals yet (older maind server) \u2014 --wait needs it"};if(l.kind==="invalid_params")return{kind:"failed",reason:l.reason};let c=l.kind==="ok"?Bn(l.body):null;if(c===null){if(s+=1,s>=oY)return{kind:"failed",reason:l.kind==="failed"?l.reason:typeof l.body.error=="string"?l.body.error:"unreadable answer",...Hu(l)?{server:!0}:{}}}else switch(s=0,c.state){case"approved":return{kind:"approved",via:c.answeredVia??"unknown",proof:eY(c)};case"declined":return{kind:"declined"};case"not_required":return{kind:"approved",via:"not_required"};case"none":case"pending":{if(i&&c.state==="pending")return{kind:"asked"};let d=n.currentHead();if(d!==null&&d!==e.headSha)return{kind:"moved",head:d};let f=n.baseConflict?.()??null;if(f!==null&&f.length>0)return{kind:"base-conflict",files:f};if(c.conflict&&!n.baseConflict)return{kind:"server-conflict",reportedAt:c.conflict.reportedAt,hint:c.conflict.hint};if(c.state==="none"){let p=c.pr?.state??null;if(!i||p!==null&&p.toUpperCase()!=="OPEN")return{kind:"gone",prState:p}}break}}let u=o-n.now();if(u<=0)return{kind:"timeout"};n.tick?.(u),await n.sleep(Math.min(nY(t,n.now()-r,n.random),u))}}a(_y,"waitForApproval");function z$(e){if(e.ok!==!0)return null;let t=e.state;if(t!=="not_required"&&t!=="approved"&&t!=="declined"&&t!=="pending")return null;let n=typeof e.object=="object"&&e.object!==null?e.object:{},r=typeof e.decision=="object"&&e.decision!==null?e.decision:{};return{state:t,objectKey:typeof n.key=="string"?n.key:null,question:typeof r.question=="string"?r.question:null,terminalAccepted:e.terminal_accepted!==!1,...by(r)}}a(z$,"readApprovalAnswer");function X$(e,t){if(e.ok!==!0)return null;let n=typeof e.object=="object"&&e.object!==null?e.object:{},r=typeof n.key=="string"?n.key:null,o=typeof e.decision=="object"&&e.decision!==null?e.decision:{},i=typeof e.hint=="string"?e.hint:null;switch(e.state){case"approved":{if(e.carried!==!0)return{kind:"own",objectKey:r};let s=typeof e.carried_from=="object"&&e.carried_from!==null?e.carried_from:{};return{kind:"carries",from:typeof s.head_sha=="string"?s.head_sha:null,via:typeof s.via_sha=="string"?s.via_sha:null,links:typeof e.links=="number"?e.links:0,objectKey:r}}case"declined":{let s=o.head_sha;return typeof s=="string"&&s!==t?{kind:"declined",at:s,objectKey:r}:{kind:"own",objectKey:r}}case"none":return{kind:"none",reason:typeof e.reason=="string"?e.reason:null,hint:i,objectKey:r};case"not_required":return{kind:"own",objectKey:r};default:return null}}a(X$,"readCarryAnswer");function Gu(e){let t=e.via??e.from,n=e.links,r=t?`the approval of ${t.slice(0,7)}`:"an earlier approval",o=e.from&&t&&e.from!==t?` (itself carried from ${e.from.slice(0,7)})`:"";return`${r}${o} carries: the ${n} commit${n===1?"":"s"} on top ${n===1?"is":"are"} promote's own and re-derive exactly`}a(Gu,"carriesPhrase");function iY(e,t){if(e===null)return!1;let n=/^\s*#?\s*(\d+)\s*$/.exec(e);return n!==null&&Number(n[1])===t}a(iY,"confirmsPrNumber");function J$(e){return Si(e)}a(J$,"waitDuration");function Z$(e){return/^merge of PR #\d+ at [0-9a-f]+ (was already )?approved\b/.test(e)}a(Z$,"isApprovalGiven");async function Q$(e,t){let n=e.headSha.slice(0,7),r=await t.call("work_object_merge_approval",{objectId:e.objectId,ref:e.ref,headSha:e.headSha,base:e.base});if(r.kind==="unknown_tool")return t.note("the server does not create merge approval questions yet \u2014 the pull request is open, but no browser approval was requested."),{kind:"unavailable"};if(r.kind==="failed"||r.kind==="invalid_params")return t.note(`the browser merge approval could not be requested (${r.reason}) \u2014 the pull request is open, but no approval question was created.`),{kind:"unavailable"};let o=z$(r.body);if(o===null){let s=typeof r.body.error=="string"?r.body.error:"unreadable answer",l=typeof r.body.hint=="string"?` \u2014 ${r.body.hint}`:"";return t.note(`the browser merge approval could not be requested (${s}) \u2014 the pull request is open, but no approval question was created.${l}`),{kind:"unavailable"}}let i=ko(e.dashboardUrl,o.objectKey);switch(o.state){case"not_required":return t.note(`PR #${e.prNumber} at ${n}: this organization does not ask for a merge approval.`),{kind:"not-required"};case"approved":return t.note(`merge approval for PR #${e.prNumber} at ${n} is already approved${bo(o)}.`),{kind:"approved",url:i};case"declined":return t.note(`a person chose "Don't merge" for PR #${e.prNumber} at ${n} on ${i} \u2014 promote will not merge it.`),{kind:"declined",url:i};case"pending":return t.note(`merge approval requested for PR #${e.prNumber} at ${n} \u2014 approve it in a browser session on ${i} ("Waiting on you").`),{kind:"requested",url:i}}}a(Q$,"requestShipMergeApproval");var eT={declined:"approval_declined",head_moved:"head_moved",base_conflict:"base_conflict",unchecked:"approval_unchecked",not_given:"approval_not_given"};async function Uu(e,t,n){let r=e.headSha.slice(0,7);t.onWait&&t.onWait({url:n,prNumber:e.prNumber,shortSha:r,where:va(e,n,!1),timeoutMs:t.wait.options.timeoutMs,cadence:Y$(t.wait.options)});let o=await _y({prNumber:e.prNumber,headSha:e.headSha,url:n,announced:t.onWait!==void 0},t.wait.options,{readState:a(()=>(t.wait.call??t.call)("work_object_merge_approval_state",{objectId:e.objectId,ref:e.ref,headSha:e.headSha}),"readState"),currentHead:t.wait.currentHead,...t.wait.baseConflict?{baseConflict:t.wait.baseConflict}:{},sleep:t.wait.sleep,now:t.wait.now,...t.wait.random?{random:t.wait.random}:{},note:t.note,...t.wait.tick?{tick:t.wait.tick}:{}});switch(o.kind){case"asked":return{kind:"pending",url:n};case"approved":return o.via==="not_required"?(t.note("the organization no longer asks for merge approvals \u2014 continuing."),{kind:"proceed",via:"not_required"}):(t.note(`merge of PR #${e.prNumber} at ${r} approved${bo(o.proof)}.`),{kind:"proceed",via:o.via});case"declined":return t.note(`a person chose "Don't merge" for PR #${e.prNumber} at ${r} on ${n} \u2014 nothing was merged.`),{kind:"stop",reason:"declined"};case"timeout":return t.note(`still not approved after ${Si(t.wait.options.timeoutMs)} \u2014 nothing was merged. The question keeps waiting on ${n}; run promote again (with --wait to keep waiting).`),{kind:"pending",url:n};case"moved":return t.note(`PR #${e.prNumber} moved to ${o.head.slice(0,7)} while waiting \u2014 an approval of ${r} would not cover it. Nothing was merged; run promote again, it asks for the new head.`),{kind:"stop",reason:"head_moved"};case"base-conflict":{let i=o.files.length>3?`${o.files.slice(0,3).join(", ")} and ${o.files.length-3} more`:o.files.join(", ");t.note(`${e.base} moved while waiting, and PR #${e.prNumber} at ${r} now conflicts with it in ${i}. Stopped waiting \u2014 an approval of this head could not be merged.`),t.note("Merge the base into the branch, resolve, push, and run promote again: the open question would not cover the resolution. Nothing was merged.");try{await t.tellObject?.(`**Don't approve PR #${e.prNumber} at \`${r}\` yet** \u2014 \`${e.base}\` moved while the merge approval was waiting, and this head now conflicts with it in ${i}. An approval of it could not be merged; the resolution is a new head that will be asked for again. (maind feature promote --wait stopped waiting.)`)}catch{}return{kind:"stop",reason:"base_conflict"}}case"server-conflict":return t.note(o.hint??`PR #${e.prNumber} at ${r} was reported to conflict with ${e.base} \u2014 an approval of this head could not be merged.`),t.note("Merge the base into the branch, resolve, push, and run promote again. Nothing was merged."),{kind:"stop",reason:"base_conflict"};case"gone":return t.note(`the merge question for PR #${e.prNumber} disappeared without an answer`+(o.prState?` \u2014 the pull request is ${o.prState}`:"")+". Nothing was merged."),{kind:"stop",reason:"not_given"};case"failed":return t.note(`stopped waiting: ${o.reason}. Nothing was merged; the question still waits on ${n}.`),o.server&&t.note(yy),{kind:"stop",reason:"unchecked"}}}a(Uu,"awaitAnswer");async function sY(e,t,n){let r=e.carry?.links??[],o=e.carry?.stopLine??null;if(r.length===0)return o&&t.note(`no earlier approval carries \u2014 ${o}.`),null;let i=await t.call("work_object_carry_merge_approval",{...n,chain:r});if(i.kind==="unknown_tool")return t.note("the server cannot carry an approval across promote's own commits yet (older maind server) \u2014 asking for this head."),null;if(i.kind==="failed"||i.kind==="invalid_params")return t.note(`an earlier approval could not be carried (${i.reason}) \u2014 asking for this head.`),null;let s=X$(i.body,e.headSha);if(s===null){let c=typeof i.body.error=="string"?i.body.error:"unreadable answer";return t.note(`an earlier approval could not be carried (${c}) \u2014 asking for this head.`),null}let l=e.headSha.slice(0,7);switch(s.kind){case"carries":return t.note(`merge of PR #${e.prNumber} at ${l} approved \u2014 ${Gu(s)} (recorded as carried: reported, checked by the CLI, not verified).`),{kind:"proceed",via:"carried"};case"declined":{let c=ko(e.dashboardUrl,s.objectKey);return t.note(`a person chose "Don't merge" for ${s.at.slice(0,7)} on ${c}, and ${l} only adds promote's own commits to it \u2014 nothing was merged.`),t.note("A new push asks again; or discuss the answer at the object."),{kind:"stop",reason:"declined"}}case"none":return s.reason!=="no_approval"&&s.hint?t.note(s.hint):o&&t.note(`no earlier approval carries \u2014 ${o}.`),null;case"own":return null}}a(sY,"tryCarry");function va(e,t,n){return e.objectId!==null?`in a browser session on ${t} ("Waiting on you")`:n?"by running promote in their own terminal \u2014 no browser page shows a change request without a work object yet (ADR-393 Phase 4)":"nowhere yet: this organization counts only browser answers, and no browser page shows a change request without a work object (ADR-393 Phase 4)"}a(va,"whereToApprove");async function tT(e,t){let n={objectId:e.objectId,ref:e.ref,headSha:e.headSha,base:e.base},r=e.headSha.slice(0,7),o=await sY(e,t,n);if(o!==null)return o;let i=await t.call("work_object_merge_approval",n);if(i.kind==="unknown_tool")return t.note("the server does not know merge approvals yet (older maind server) \u2014 merging without the approval gate. Update the server to have it enforced."),{kind:"proceed",via:"server_without_gate"};if(i.kind==="failed"||i.kind==="invalid_params")return Hu(i)?(t.note(`the merge approval could not be checked: ${rT(i)} \u2014 nothing was merged.`),t.note(yy)):t.note(`the merge approval could not be checked (${i.reason}) \u2014 nothing was merged.`),{kind:"stop",reason:"unchecked"};let s=z$(i.body);if(s===null){let u=typeof i.body.error=="string"?i.body.error:"unreadable answer",d=typeof i.body.hint=="string"?` ${i.body.hint}`:"";return t.note(`the merge approval could not be checked (${u}).${d} Nothing was merged.`),{kind:"stop",reason:"unchecked"}}let l=ko(e.dashboardUrl,s.objectKey);switch(s.state){case"not_required":return{kind:"proceed",via:"not_required"};case"approved":return t.note(`merge of PR #${e.prNumber} at ${r} approved${bo(s)}.`),{kind:"proceed",via:s.answeredVia??"unknown"};case"declined":return t.note(`a person chose "Don't merge" for PR #${e.prNumber} at ${r} on ${l} \u2014 nothing was merged.`),t.note("A new push asks again; or change the answer's premise and discuss it at the object."),{kind:"stop",reason:"declined"};case"pending":break}let c=t.wait;if(t.isTty()&&s.terminalAccepted){t.note(`your organization asks a person to approve every merge. PR #${e.prNumber} at ${r} into ${e.base}.`);let u=await t.prompt(`Type the pull request number (${e.prNumber}) to approve the merge, or press Enter to `+(c?e.objectId!==null?"wait for an approval in a browser session: ":"wait for someone to approve it in their own terminal: ":"stop: "));if(!iY(u,e.prNumber))return c?Uu(e,{...t,wait:c},l):(t.note(e.objectId!==null?`not approved \u2014 nothing was merged. The question also waits on ${l}.`:"not approved \u2014 nothing was merged."),{kind:"stop",reason:"not_given"});let d=await t.call("work_object_record_terminal_approval",n);if(d.kind==="ok"&&d.body.ok!==!0&&d.body.error==="terminal_not_accepted")return t.note(`this organization counts only approvals given in a browser session \u2014 nothing was recorded from this terminal. A person approves it ${va(e,l,!1)}.`),c?Uu(e,{...t,wait:c},l):(t.note("Then run promote again \u2014 or run it with --wait. Nothing was merged."),{kind:"pending",url:l});if(d.kind!=="ok"||d.body.ok!==!0||d.body.state!=="approved"){let f=d.kind==="ok"?d.body.state==="declined"?`a person chose "Don't merge" on ${l} in the meantime`:String(d.body.error??"unreadable answer"):d.kind==="failed"||d.kind==="invalid_params"?d.reason:"the server does not know terminal approvals";return t.note(`the approval could not be recorded (${f}) \u2014 nothing was merged.`),Hu(d)&&t.note(yy),{kind:"stop",reason:d.kind==="ok"&&d.body.state==="declined"?"declined":"unchecked"}}if(d.body.recorded!==!0){let f=typeof d.body.decision=="object"&&d.body.decision!==null?d.body.decision:{},p=by(f);return t.note(`merge of PR #${e.prNumber} at ${r} was already approved${bo(p)} \u2014 `+(p.answeredVia==="terminal"?"that answer stands.":"that answer stands; nothing was recorded from this terminal.")),{kind:"proceed",via:p.answeredVia??"unknown"}}return t.note("approved in this terminal \u2014 recorded as reported, not verified (only a browser session gives a verified answer)."),{kind:"proceed",via:"terminal"}}return c&&t.onWait?Uu(e,{...t,wait:c},l):(t.note(`your organization asks a person to approve every merge \u2014 PR #${e.prNumber} at ${r} is not approved yet.`),c?(t.note(`A person approves it ${va(e,l,s.terminalAccepted)}; promote merges as soon as they do.`),Uu(e,{...t,wait:c},l)):(e.objectId===null||!s.terminalAccepted?t.note(`A person approves it ${va(e,l,s.terminalAccepted)}.`):t.note(`A person approves it ${va(e,l,!0)}, or runs promote in their own terminal.`),t.note("Then run promote again \u2014 or run it with --wait, which merges once approved. Nothing was merged. A new push to the branch asks again."),{kind:"pending",url:l}))}a(tT,"runMergeApproval");function wy(e,t,n){return n===0?0:n===1?1:e==="asked"&&t==="pending"?0:null}a(wy,"untilReached");function nT(e,t){let n=t.headSha.slice(0,7),r=[],o=`PR #${t.prNumber} at ${n}`,i,s=e.state==="none"||e.state==="pending"?t.carry??null:null;switch(e.state){case"not_required":r.push(`${o}: this organization does not ask for merge approvals.`),i=0;break;case"approved":r.push(`${o}: approved${bo(e)}.`),i=0;break;case"declined":r.push(`${o}: a person chose "Don't merge" on ${t.url}.`),i=1;break;case"pending":case"none":if(s?.kind==="carries"){r.push(`${o}: not answered for this head, but ${Gu(s)} \u2014 promote merges without asking.`),i=0;break}if(s?.kind==="declined"){r.push(`${o}: a person chose "Don't merge" for ${s.at.slice(0,7)} on ${t.url}, and this head only adds promote's own commits to it.`),i=1;break}r.push(e.state==="pending"?`${o}: waiting for a person to approve it in a browser session on ${t.url} ("Waiting on you").`:`${o}: nobody has been asked for this head yet \u2014 promote asks when it gets there (promote --wait waits for the answer).`),i=3;break}let l=s?vy(s):null;return l&&r.push(` ${l}`),e.pr?.headSha&&e.pr.headSha!==t.headSha&&r.push(` GitHub's connector last saw the pull request at ${e.pr.headSha.slice(0,7)} \u2014 an answer for ${n} would not cover that.`),t.localHead!==null&&t.localHead!==t.headSha&&r.push(` the local branch is at ${t.localHead.slice(0,7)}, not at the pull request head \u2014 push first; an approval covers only the pushed head.`),e.conflict&&(e.state==="pending"||e.state==="none")&&r.push(` ${e.conflict.hint??`${n} was reported to conflict with its base (${e.conflict.reportedAt}) \u2014 an approval of it cannot lead to a merge.`}`),{lines:r,exitCode:i}}a(nT,"approvalStateLines");async function Ku(e,t,n){if(n.links.length===0)return n.stopLine?{kind:"stops",line:n.stopLine}:null;let r=await e("work_object_merge_approval_state",{...t,chain:n.links});if(r.kind==="unknown_tool")return{kind:"unavailable",why:"the server cannot read merge approvals yet"};if(r.kind==="failed"||r.kind==="invalid_params")return{kind:"unavailable",why:r.reason};let o=X$(r.body,t.headSha);return o===null?{kind:"unavailable",why:typeof r.body.error=="string"?r.body.error:"unreadable answer"}:o}a(Ku,"previewCarry");function vy(e){switch(e.kind){case"stops":return`no earlier approval carries \u2014 ${e.line}.`;case"unavailable":return`whether an earlier approval carries could not be read (${e.why}).`;case"none":return e.reason!=="no_approval"&&e.hint?e.hint:null;default:return null}}a(vy,"carryNote");var aY={work_object_merge_approval_state:!0,work_object_merge_approval:!0,work_object_carry_merge_approval:!0,work_object_record_terminal_approval:!0},lY=[2e3,5e3,1e4];function Hu(e){return e.kind!=="failed"?!1:e.network===!0||e.status===502||e.status===503||e.status===504}a(Hu,"isTransientServerFailure");function rT(e){return e.kind==="failed"&&e.status!==void 0?`the maind server did not answer the call (HTTP ${e.status})`:`the maind server could not be reached (${e.kind==="failed"?e.reason:"no answer"})`}a(rT,"serverFailurePhrase");var yy="This is a server error, not a failure of the branch or its gate. Run promote again: a gate that was green on the same head and base does not run again.";function Qt(e,t){let n=t.delays??lY;return async(r,o)=>{for(let i=0;;i++){let s=await e(r,o);if(!Hu(s)||!aY[r]||i>=n.length)return s;let l=n[i];t.note(`${rT(s)} \u2014 retrying in ${Math.round(l/1e3)} s; nothing is lost.`),await t.sleep(l)}}}a(Qt,"retryOnServerError");var cY=[5e3,2e4,45e3];function uY(e){return e.kind==="failed"&&/\b429\b|rate limit/i.test(e.reason)}a(uY,"isRateLimited");var dY=[2e3,3e3,5e3,8e3];function fY(e){return e.kind==="ok"&&e.body.ok!==!0&&e.body.error==="head_mismatch"}a(fY,"isHeadMismatch");function oT(e,t){let n=t.delays??dY;return async(r,o)=>{for(let i=0;;i++){let s=await e(r,o);if(!fY(s)||i>=n.length)return s;await t.sleep(n[i])}}}a(oT,"retryOnHeadMismatch");function xy(e,t){let n=t.delays??cY,r=t.now??Date.now;return async(o,i)=>{let s=0;for(let l=0;;l++){let c=await e(o,i);if(c.kind==="failed"&&c.quota!==void 0){let d=s<3?pE(c.quota,r(),t.maxQuotaWaitMs??0):null;if(d===null)return c;s+=1,t.note(`${Uc(c.quota,r())} \u2014 waiting ${Math.ceil(d/6e4)} min for it; nothing is lost.`),await t.sleep(d);continue}if(!uY(c)||l>=n.length)return c;let u=n[l];t.note(`the maind server is rate-limiting this IP (429) \u2014 retrying in ${Math.round(u/1e3)} s; nothing is lost.`),await t.sleep(u)}}}a(xy,"retryOnRateLimit");import{execFileSync as Qd,spawn as HJ}from"node:child_process";import{existsSync as GJ,mkdirSync as KJ,mkdtempSync as gD,openSync as WJ,rmSync as yD,writeFileSync as ef}from"node:fs";import{tmpdir as bD}from"node:os";import{join as Ar,resolve as qJ}from"node:path";import{execFileSync as pY}from"node:child_process";function mY(e,t){if(e===0)return{kind:"clean"};if(e!==1)return{kind:"unknown",reason:e===129?"this git does not know `merge-tree --write-tree` (needs git 2.38+)":`git merge-tree failed (exit ${e??"signal"})`};let n=t.split(`
378
+ `);return 0}a(JV,"runResolve");async function Ht(e){let t;try{t=Ae()}catch(s){return{ok:!1,reason:s instanceof De?s.message:String(s)}}let n=dt().projectKey;if(!n)return{ok:!1,reason:"not a git repo with a remote \u2014 no project_key."};let r=new Me({apiKey:t.apiKey,deviceId:t.deviceId,clientVersion:fe,projectKey:n}),o={session:null},i=wa(r,n,xt,o);try{let s=o.session=await _a(r,n,void 0,xt);if(s===null)return{ok:!1,reason:"no session could be resolved."};let l=a(async p=>{let m=await i.callTool("get_my_work_objects",{project_key:n,session_id:s.sessionId,keys:p});return m.ok===!0&&Array.isArray(m.resolved)?m.resolved:null},"ask"),c=e.filter(p=>!ay(p)),u=c.length>0?await l(c):[];if(u===null)return{ok:!1,reason:"server did not answer."};let d=new Map;for(let p of e.filter(ay)){let m=await l([p.trim()]);if(m===null)return{ok:!1,reason:"server did not answer."};d.set(p,m)}return{ok:!0,refs:e.map(p=>{let m=d.has(p)?B$(p,d.get(p),!0):B$(p,u,!1);return!m||typeof m.id!="string"?{ident:p,unresolved:!0}:{ident:p,id:m.id,key:m.key??null,title:m.title??"",status:m.status??"unknown",anchors:(m.anchors??[]).filter(h=>typeof h.path_prefix=="string"&&(!h.project_key||h.project_key===n)).map(h=>h.path_prefix),...typeof m.doc_duty=="string"?{docDuty:m.doc_duty}:{},...typeof m.doc_missing=="boolean"?{docMissing:m.doc_missing}:{},...m.doc_in_review===!0?{docInReview:!0}:{},...typeof m.lesson_check=="string"?{lessonCheck:m.lesson_check}:{},...typeof m.has_plan=="boolean"?{hasPlan:m.has_plan}:{},...typeof m.availability=="string"?{availability:m.availability}:{},...typeof m.availability_fact=="string"?{availabilityFact:m.availability_fact}:{},..."take"in m?{take:YV(m.take)}:{},...Array.isArray(m.bindings)?{bindings:zV(m.bindings)}:{}}})}}catch(s){return{ok:!1,reason:s instanceof Error?s.message:String(s)}}finally{o.session?.source==="announced"&&await vi(r,n,o.session.sessionId)}}a(Ht,"lookupObjects");function ZV(e){return e==="dashboard"||e==="terminal"||e==="carried"?e:null}a(ZV,"readVia");function QV(e){if(typeof e!="object"||e===null)return null;let t=e.head_sha;return typeof t=="string"?t:null}a(QV,"readCarriedFrom");function by(e){let t=ZV(e.answered_via),n=t==="dashboard"&&e.verified!==!1;return{answeredVia:t,carriedFrom:QV(e.carried_from),verified:n,mfa:n&&typeof e.mfa=="boolean"?e.mfa:null}}a(by,"readProof");function eY(e){return{answeredVia:e.answeredVia,carriedFrom:e.carriedFrom,verified:e.verified,mfa:e.mfa}}a(eY,"proofOf");function bo(e){return e.answeredVia==="terminal"?" in a terminal (reported, not verified)":e.answeredVia==="carried"?` \u2014 carried from ${e.carriedFrom?e.carriedFrom.slice(0,7):"an earlier head"} across promote's own commits (reported: checked by the CLI, not verified)`:e.verified?` in a browser session (verified${e.mfa===!0?", with a second factor":e.mfa===!1?", without a second factor":""})`:e.answeredVia==="dashboard"?" (reported, not verified)":" through a channel this CLI does not know (not shown as verified)"}a(bo,"viaPhrase");function ko(e,t){return t?`${e}/planning/${t}`:e}a(ko,"approvalPageUrl");function Bn(e){if(e.ok!==!0)return null;let t=e.state;if(t!=="not_required"&&t!=="none"&&t!=="pending"&&t!=="approved"&&t!=="declined")return null;let n=typeof e.object=="object"&&e.object!==null?e.object:{},r=typeof e.decision=="object"&&e.decision!==null?e.decision:{},o=typeof e.pr=="object"&&e.pr!==null?e.pr:null;return{state:t,objectKey:typeof n.key=="string"?n.key:null,...by(r),pr:o&&typeof o.state=="string"?{state:o.state,headSha:typeof o.head_sha=="string"?o.head_sha:null}:null,...tY(e.conflict)}}a(Bn,"readApprovalState");function tY(e){if(typeof e!="object"||e===null)return{};let t=e;return typeof t.at!="string"||t.at.length===0?{}:{conflict:{reportedAt:t.at,hint:typeof t.hint=="string"&&t.hint.length>0?t.hint:null}}}a(tY,"readConflict");var gr={timeoutMs:30*6e4,intervalMs:15e3,slowAfterMs:5*6e4,slowIntervalMs:6e4,jitter:.1};function nY(e,t,n=Math.random){let o=e.slowAfterMs!==void 0&&e.slowIntervalMs!==void 0&&t>=e.slowAfterMs?e.slowIntervalMs:e.intervalMs,i=e.jitter??0;return i>0?Math.round(o*(1+i*(2*n()-1))):o}a(nY,"waitPauseMs");function Y$(e){let t=`every ${Si(e.intervalMs)}`;return e.slowAfterMs===void 0||e.slowIntervalMs===void 0||e.slowAfterMs>=e.timeoutMs?t:`${t} for the first ${Si(e.slowAfterMs)}, then every ${Si(e.slowIntervalMs)}`}a(Y$,"waitCadence");var rY=24*60*6e4,oY=4;function ky(e){let t=/^\s*(\d+)\s*([smh]?)\s*$/i.exec(e);if(!t)return null;let n=Number(t[1]),r=(t[2]??"").toLowerCase(),o=r==="s"?n*1e3:r==="h"?n*36e5:n*6e4;return o>0&&o<=rY?o:null}a(ky,"parseWaitDuration");function Si(e){return e%36e5===0?`${e/36e5} h`:e%6e4===0?`${e/6e4} min`:`${Math.round(e/1e3)} s`}a(Si,"humanDuration");async function _y(e,t,n){let r=n.now(),o=r+t.timeoutMs,i=e.until==="asked";e.announced!==!0&&n.note((i?`waiting until a merge approval for PR #${e.prNumber} at ${e.headSha.slice(0,7)} is asked on ${e.url} `:`waiting for a person to approve PR #${e.prNumber} at ${e.headSha.slice(0,7)} on ${e.url} `)+`(up to ${Si(t.timeoutMs)}, checking ${Y$(t)}).`);let s=0;for(;;){let l=await n.readState();if(l.kind==="unknown_tool")return{kind:"failed",reason:"the server cannot read merge approvals yet (older maind server) \u2014 --wait needs it"};if(l.kind==="invalid_params")return{kind:"failed",reason:l.reason};let c=l.kind==="ok"?Bn(l.body):null;if(c===null){if(s+=1,s>=oY)return{kind:"failed",reason:l.kind==="failed"?l.reason:typeof l.body.error=="string"?l.body.error:"unreadable answer",...Hu(l)?{server:!0}:{}}}else switch(s=0,c.state){case"approved":return{kind:"approved",via:c.answeredVia??"unknown",proof:eY(c)};case"declined":return{kind:"declined"};case"not_required":return{kind:"approved",via:"not_required"};case"none":case"pending":{if(i&&c.state==="pending")return{kind:"asked"};let d=n.currentHead();if(d!==null&&d!==e.headSha)return{kind:"moved",head:d};let f=n.baseConflict?.()??null;if(f!==null&&f.length>0)return{kind:"base-conflict",files:f};if(c.conflict&&!n.baseConflict)return{kind:"server-conflict",reportedAt:c.conflict.reportedAt,hint:c.conflict.hint};if(c.state==="none"){let p=c.pr?.state??null;if(!i||p!==null&&p.toUpperCase()!=="OPEN")return{kind:"gone",prState:p}}break}}let u=o-n.now();if(u<=0)return{kind:"timeout"};n.tick?.(u),await n.sleep(Math.min(nY(t,n.now()-r,n.random),u))}}a(_y,"waitForApproval");function z$(e){if(e.ok!==!0)return null;let t=e.state;if(t!=="not_required"&&t!=="approved"&&t!=="declined"&&t!=="pending")return null;let n=typeof e.object=="object"&&e.object!==null?e.object:{},r=typeof e.decision=="object"&&e.decision!==null?e.decision:{};return{state:t,objectKey:typeof n.key=="string"?n.key:null,question:typeof r.question=="string"?r.question:null,terminalAccepted:e.terminal_accepted!==!1,...by(r)}}a(z$,"readApprovalAnswer");function X$(e,t){if(e.ok!==!0)return null;let n=typeof e.object=="object"&&e.object!==null?e.object:{},r=typeof n.key=="string"?n.key:null,o=typeof e.decision=="object"&&e.decision!==null?e.decision:{},i=typeof e.hint=="string"?e.hint:null;switch(e.state){case"approved":{if(e.carried!==!0)return{kind:"own",objectKey:r};let s=typeof e.carried_from=="object"&&e.carried_from!==null?e.carried_from:{};return{kind:"carries",from:typeof s.head_sha=="string"?s.head_sha:null,via:typeof s.via_sha=="string"?s.via_sha:null,links:typeof e.links=="number"?e.links:0,objectKey:r}}case"declined":{let s=o.head_sha;return typeof s=="string"&&s!==t?{kind:"declined",at:s,objectKey:r}:{kind:"own",objectKey:r}}case"none":return{kind:"none",reason:typeof e.reason=="string"?e.reason:null,hint:i,objectKey:r};case"not_required":return{kind:"own",objectKey:r};default:return null}}a(X$,"readCarryAnswer");function Gu(e){let t=e.via??e.from,n=e.links,r=t?`the approval of ${t.slice(0,7)}`:"an earlier approval",o=e.from&&t&&e.from!==t?` (itself carried from ${e.from.slice(0,7)})`:"";return`${r}${o} carries: the ${n} commit${n===1?"":"s"} on top ${n===1?"is":"are"} promote's own and re-derive exactly`}a(Gu,"carriesPhrase");function iY(e,t){if(e===null)return!1;let n=/^\s*#?\s*(\d+)\s*$/.exec(e);return n!==null&&Number(n[1])===t}a(iY,"confirmsPrNumber");function J$(e){return Si(e)}a(J$,"waitDuration");function Z$(e){return/^merge of PR #\d+ at [0-9a-f]+ (was already )?approved\b/.test(e)}a(Z$,"isApprovalGiven");async function Q$(e,t){let n=e.headSha.slice(0,7),r=await t.call("work_object_merge_approval",{objectId:e.objectId,ref:e.ref,headSha:e.headSha,base:e.base});if(r.kind==="unknown_tool")return t.note("the server does not create merge approval questions yet \u2014 the pull request is open, but no browser approval was requested."),{kind:"unavailable"};if(r.kind==="failed"||r.kind==="invalid_params")return t.note(`the browser merge approval could not be requested (${r.reason}) \u2014 the pull request is open, but no approval question was created.`),{kind:"unavailable"};let o=z$(r.body);if(o===null){let s=typeof r.body.error=="string"?r.body.error:"unreadable answer",l=typeof r.body.hint=="string"?` \u2014 ${r.body.hint}`:"";return t.note(`the browser merge approval could not be requested (${s}) \u2014 the pull request is open, but no approval question was created.${l}`),{kind:"unavailable"}}let i=ko(e.dashboardUrl,o.objectKey);switch(o.state){case"not_required":return t.note(`PR #${e.prNumber} at ${n}: this organization does not ask for a merge approval.`),{kind:"not-required"};case"approved":return t.note(`merge approval for PR #${e.prNumber} at ${n} is already approved${bo(o)}.`),{kind:"approved",url:i};case"declined":return t.note(`a person chose "Don't merge" for PR #${e.prNumber} at ${n} on ${i} \u2014 promote will not merge it.`),{kind:"declined",url:i};case"pending":return t.note(`merge approval requested for PR #${e.prNumber} at ${n} \u2014 approve it in a browser session on ${i} ("Waiting on you").`),{kind:"requested",url:i}}}a(Q$,"requestShipMergeApproval");var eT={declined:"approval_declined",head_moved:"head_moved",base_conflict:"base_conflict",unchecked:"approval_unchecked",not_given:"approval_not_given"};async function Uu(e,t,n){let r=e.headSha.slice(0,7);t.onWait&&t.onWait({url:n,prNumber:e.prNumber,shortSha:r,where:va(e,n,!1),timeoutMs:t.wait.options.timeoutMs,cadence:Y$(t.wait.options)});let o=new Date(t.wait.now()+t.wait.options.timeoutMs).toISOString(),i=!0,s=a(c=>(t.wait.call??t.call)("work_object_merge_approval_state",{objectId:e.objectId,ref:e.ref,headSha:e.headSha,...c?{waitingUntil:o}:{}}),"read"),l=await _y({prNumber:e.prNumber,headSha:e.headSha,url:n,announced:t.onWait!==void 0},t.wait.options,{readState:a(async()=>{if(!i)return s(!1);let c=await s(!0);return c.kind!=="invalid_params"?c:(i=!1,s(!1))},"readState"),currentHead:t.wait.currentHead,...t.wait.baseConflict?{baseConflict:t.wait.baseConflict}:{},sleep:t.wait.sleep,now:t.wait.now,...t.wait.random?{random:t.wait.random}:{},note:t.note,...t.wait.tick?{tick:t.wait.tick}:{}});switch(l.kind){case"asked":return{kind:"pending",url:n};case"approved":return l.via==="not_required"?(t.note("the organization no longer asks for merge approvals \u2014 continuing."),{kind:"proceed",via:"not_required"}):(t.note(`merge of PR #${e.prNumber} at ${r} approved${bo(l.proof)}.`),{kind:"proceed",via:l.via});case"declined":return t.note(`a person chose "Don't merge" for PR #${e.prNumber} at ${r} on ${n} \u2014 nothing was merged.`),{kind:"stop",reason:"declined"};case"timeout":return t.note(`still not approved after ${Si(t.wait.options.timeoutMs)} \u2014 nothing was merged. The question keeps waiting on ${n}; run promote again (with --wait to keep waiting).`),{kind:"pending",url:n};case"moved":return t.note(`PR #${e.prNumber} moved to ${l.head.slice(0,7)} while waiting \u2014 an approval of ${r} would not cover it. Nothing was merged; run promote again, it asks for the new head.`),{kind:"stop",reason:"head_moved"};case"base-conflict":{let c=l.files.length>3?`${l.files.slice(0,3).join(", ")} and ${l.files.length-3} more`:l.files.join(", ");t.note(`${e.base} moved while waiting, and PR #${e.prNumber} at ${r} now conflicts with it in ${c}. Stopped waiting \u2014 an approval of this head could not be merged.`),t.note("Merge the base into the branch, resolve, push, and run promote again: the open question would not cover the resolution. Nothing was merged.");try{await t.tellObject?.(`**Don't approve PR #${e.prNumber} at \`${r}\` yet** \u2014 \`${e.base}\` moved while the merge approval was waiting, and this head now conflicts with it in ${c}. An approval of it could not be merged; the resolution is a new head that will be asked for again. (maind feature promote --wait stopped waiting.)`)}catch{}return{kind:"stop",reason:"base_conflict"}}case"server-conflict":return t.note(l.hint??`PR #${e.prNumber} at ${r} was reported to conflict with ${e.base} \u2014 an approval of this head could not be merged.`),t.note("Merge the base into the branch, resolve, push, and run promote again. Nothing was merged."),{kind:"stop",reason:"base_conflict"};case"gone":return t.note(`the merge question for PR #${e.prNumber} disappeared without an answer`+(l.prState?` \u2014 the pull request is ${l.prState}`:"")+". Nothing was merged."),{kind:"stop",reason:"not_given"};case"failed":return t.note(`stopped waiting: ${l.reason}. Nothing was merged; the question still waits on ${n}.`),l.server&&t.note(yy),{kind:"stop",reason:"unchecked"}}}a(Uu,"awaitAnswer");async function sY(e,t,n){let r=e.carry?.links??[],o=e.carry?.stopLine??null;if(r.length===0)return o&&t.note(`no earlier approval carries \u2014 ${o}.`),null;let i=await t.call("work_object_carry_merge_approval",{...n,chain:r});if(i.kind==="unknown_tool")return t.note("the server cannot carry an approval across promote's own commits yet (older maind server) \u2014 asking for this head."),null;if(i.kind==="failed"||i.kind==="invalid_params")return t.note(`an earlier approval could not be carried (${i.reason}) \u2014 asking for this head.`),null;let s=X$(i.body,e.headSha);if(s===null){let c=typeof i.body.error=="string"?i.body.error:"unreadable answer";return t.note(`an earlier approval could not be carried (${c}) \u2014 asking for this head.`),null}let l=e.headSha.slice(0,7);switch(s.kind){case"carries":return t.note(`merge of PR #${e.prNumber} at ${l} approved \u2014 ${Gu(s)} (recorded as carried: reported, checked by the CLI, not verified).`),{kind:"proceed",via:"carried"};case"declined":{let c=ko(e.dashboardUrl,s.objectKey);return t.note(`a person chose "Don't merge" for ${s.at.slice(0,7)} on ${c}, and ${l} only adds promote's own commits to it \u2014 nothing was merged.`),t.note("A new push asks again; or discuss the answer at the object."),{kind:"stop",reason:"declined"}}case"none":return s.reason!=="no_approval"&&s.hint?t.note(s.hint):o&&t.note(`no earlier approval carries \u2014 ${o}.`),null;case"own":return null}}a(sY,"tryCarry");function va(e,t,n){return e.objectId!==null?`in a browser session on ${t} ("Waiting on you")`:n?"by running promote in their own terminal \u2014 no browser page shows a change request without a work object yet (ADR-393 Phase 4)":"nowhere yet: this organization counts only browser answers, and no browser page shows a change request without a work object (ADR-393 Phase 4)"}a(va,"whereToApprove");async function tT(e,t){let n={objectId:e.objectId,ref:e.ref,headSha:e.headSha,base:e.base},r=e.headSha.slice(0,7),o=await sY(e,t,n);if(o!==null)return o;let i=await t.call("work_object_merge_approval",n);if(i.kind==="unknown_tool")return t.note("the server does not know merge approvals yet (older maind server) \u2014 merging without the approval gate. Update the server to have it enforced."),{kind:"proceed",via:"server_without_gate"};if(i.kind==="failed"||i.kind==="invalid_params")return Hu(i)?(t.note(`the merge approval could not be checked: ${rT(i)} \u2014 nothing was merged.`),t.note(yy)):t.note(`the merge approval could not be checked (${i.reason}) \u2014 nothing was merged.`),{kind:"stop",reason:"unchecked"};let s=z$(i.body);if(s===null){let u=typeof i.body.error=="string"?i.body.error:"unreadable answer",d=typeof i.body.hint=="string"?` ${i.body.hint}`:"";return t.note(`the merge approval could not be checked (${u}).${d} Nothing was merged.`),{kind:"stop",reason:"unchecked"}}let l=ko(e.dashboardUrl,s.objectKey);switch(s.state){case"not_required":return{kind:"proceed",via:"not_required"};case"approved":return t.note(`merge of PR #${e.prNumber} at ${r} approved${bo(s)}.`),{kind:"proceed",via:s.answeredVia??"unknown"};case"declined":return t.note(`a person chose "Don't merge" for PR #${e.prNumber} at ${r} on ${l} \u2014 nothing was merged.`),t.note("A new push asks again; or change the answer's premise and discuss it at the object."),{kind:"stop",reason:"declined"};case"pending":break}let c=t.wait;if(t.isTty()&&s.terminalAccepted){t.note(`your organization asks a person to approve every merge. PR #${e.prNumber} at ${r} into ${e.base}.`);let u=await t.prompt(`Type the pull request number (${e.prNumber}) to approve the merge, or press Enter to `+(c?e.objectId!==null?"wait for an approval in a browser session: ":"wait for someone to approve it in their own terminal: ":"stop: "));if(!iY(u,e.prNumber))return c?Uu(e,{...t,wait:c},l):(t.note(e.objectId!==null?`not approved \u2014 nothing was merged. The question also waits on ${l}.`:"not approved \u2014 nothing was merged."),{kind:"stop",reason:"not_given"});let d=await t.call("work_object_record_terminal_approval",n);if(d.kind==="ok"&&d.body.ok!==!0&&d.body.error==="terminal_not_accepted")return t.note(`this organization counts only approvals given in a browser session \u2014 nothing was recorded from this terminal. A person approves it ${va(e,l,!1)}.`),c?Uu(e,{...t,wait:c},l):(t.note("Then run promote again \u2014 or run it with --wait. Nothing was merged."),{kind:"pending",url:l});if(d.kind!=="ok"||d.body.ok!==!0||d.body.state!=="approved"){let f=d.kind==="ok"?d.body.state==="declined"?`a person chose "Don't merge" on ${l} in the meantime`:String(d.body.error??"unreadable answer"):d.kind==="failed"||d.kind==="invalid_params"?d.reason:"the server does not know terminal approvals";return t.note(`the approval could not be recorded (${f}) \u2014 nothing was merged.`),Hu(d)&&t.note(yy),{kind:"stop",reason:d.kind==="ok"&&d.body.state==="declined"?"declined":"unchecked"}}if(d.body.recorded!==!0){let f=typeof d.body.decision=="object"&&d.body.decision!==null?d.body.decision:{},p=by(f);return t.note(`merge of PR #${e.prNumber} at ${r} was already approved${bo(p)} \u2014 `+(p.answeredVia==="terminal"?"that answer stands.":"that answer stands; nothing was recorded from this terminal.")),{kind:"proceed",via:p.answeredVia??"unknown"}}return t.note("approved in this terminal \u2014 recorded as reported, not verified (only a browser session gives a verified answer)."),{kind:"proceed",via:"terminal"}}return c&&t.onWait?Uu(e,{...t,wait:c},l):(t.note(`your organization asks a person to approve every merge \u2014 PR #${e.prNumber} at ${r} is not approved yet.`),c?(t.note(`A person approves it ${va(e,l,s.terminalAccepted)}; promote merges as soon as they do.`),Uu(e,{...t,wait:c},l)):(e.objectId===null||!s.terminalAccepted?t.note(`A person approves it ${va(e,l,s.terminalAccepted)}.`):t.note(`A person approves it ${va(e,l,!0)}, or runs promote in their own terminal.`),t.note("Then run promote again \u2014 or run it with --wait, which merges once approved. Nothing was merged. A new push to the branch asks again."),{kind:"pending",url:l}))}a(tT,"runMergeApproval");function wy(e,t,n){return n===0?0:n===1?1:e==="asked"&&t==="pending"?0:null}a(wy,"untilReached");function nT(e,t){let n=t.headSha.slice(0,7),r=[],o=`PR #${t.prNumber} at ${n}`,i,s=e.state==="none"||e.state==="pending"?t.carry??null:null;switch(e.state){case"not_required":r.push(`${o}: this organization does not ask for merge approvals.`),i=0;break;case"approved":r.push(`${o}: approved${bo(e)}.`),i=0;break;case"declined":r.push(`${o}: a person chose "Don't merge" on ${t.url}.`),i=1;break;case"pending":case"none":if(s?.kind==="carries"){r.push(`${o}: not answered for this head, but ${Gu(s)} \u2014 promote merges without asking.`),i=0;break}if(s?.kind==="declined"){r.push(`${o}: a person chose "Don't merge" for ${s.at.slice(0,7)} on ${t.url}, and this head only adds promote's own commits to it.`),i=1;break}r.push(e.state==="pending"?`${o}: waiting for a person to approve it in a browser session on ${t.url} ("Waiting on you").`:`${o}: nobody has been asked for this head yet \u2014 promote asks when it gets there (promote --wait waits for the answer).`),i=3;break}let l=s?vy(s):null;return l&&r.push(` ${l}`),e.pr?.headSha&&e.pr.headSha!==t.headSha&&r.push(` GitHub's connector last saw the pull request at ${e.pr.headSha.slice(0,7)} \u2014 an answer for ${n} would not cover that.`),t.localHead!==null&&t.localHead!==t.headSha&&r.push(` the local branch is at ${t.localHead.slice(0,7)}, not at the pull request head \u2014 push first; an approval covers only the pushed head.`),e.conflict&&(e.state==="pending"||e.state==="none")&&r.push(` ${e.conflict.hint??`${n} was reported to conflict with its base (${e.conflict.reportedAt}) \u2014 an approval of it cannot lead to a merge.`}`),{lines:r,exitCode:i}}a(nT,"approvalStateLines");async function Ku(e,t,n){if(n.links.length===0)return n.stopLine?{kind:"stops",line:n.stopLine}:null;let r=await e("work_object_merge_approval_state",{...t,chain:n.links});if(r.kind==="unknown_tool")return{kind:"unavailable",why:"the server cannot read merge approvals yet"};if(r.kind==="failed"||r.kind==="invalid_params")return{kind:"unavailable",why:r.reason};let o=X$(r.body,t.headSha);return o===null?{kind:"unavailable",why:typeof r.body.error=="string"?r.body.error:"unreadable answer"}:o}a(Ku,"previewCarry");function vy(e){switch(e.kind){case"stops":return`no earlier approval carries \u2014 ${e.line}.`;case"unavailable":return`whether an earlier approval carries could not be read (${e.why}).`;case"none":return e.reason!=="no_approval"&&e.hint?e.hint:null;default:return null}}a(vy,"carryNote");var aY={work_object_merge_approval_state:!0,work_object_merge_approval:!0,work_object_carry_merge_approval:!0,work_object_record_terminal_approval:!0},lY=[2e3,5e3,1e4];function Hu(e){return e.kind!=="failed"?!1:e.network===!0||e.status===502||e.status===503||e.status===504}a(Hu,"isTransientServerFailure");function rT(e){return e.kind==="failed"&&e.status!==void 0?`the maind server did not answer the call (HTTP ${e.status})`:`the maind server could not be reached (${e.kind==="failed"?e.reason:"no answer"})`}a(rT,"serverFailurePhrase");var yy="This is a server error, not a failure of the branch or its gate. Run promote again: a gate that was green on the same head and base does not run again.";function Qt(e,t){let n=t.delays??lY;return async(r,o)=>{for(let i=0;;i++){let s=await e(r,o);if(!Hu(s)||!aY[r]||i>=n.length)return s;let l=n[i];t.note(`${rT(s)} \u2014 retrying in ${Math.round(l/1e3)} s; nothing is lost.`),await t.sleep(l)}}}a(Qt,"retryOnServerError");var cY=[5e3,2e4,45e3];function uY(e){return e.kind==="failed"&&/\b429\b|rate limit/i.test(e.reason)}a(uY,"isRateLimited");var dY=[2e3,3e3,5e3,8e3];function fY(e){return e.kind==="ok"&&e.body.ok!==!0&&e.body.error==="head_mismatch"}a(fY,"isHeadMismatch");function oT(e,t){let n=t.delays??dY;return async(r,o)=>{for(let i=0;;i++){let s=await e(r,o);if(!fY(s)||i>=n.length)return s;await t.sleep(n[i])}}}a(oT,"retryOnHeadMismatch");function xy(e,t){let n=t.delays??cY,r=t.now??Date.now;return async(o,i)=>{let s=0;for(let l=0;;l++){let c=await e(o,i);if(c.kind==="failed"&&c.quota!==void 0){let d=s<3?pE(c.quota,r(),t.maxQuotaWaitMs??0):null;if(d===null)return c;s+=1,t.note(`${Uc(c.quota,r())} \u2014 waiting ${Math.ceil(d/6e4)} min for it; nothing is lost.`),await t.sleep(d);continue}if(!uY(c)||l>=n.length)return c;let u=n[l];t.note(`the maind server is rate-limiting this IP (429) \u2014 retrying in ${Math.round(u/1e3)} s; nothing is lost.`),await t.sleep(u)}}}a(xy,"retryOnRateLimit");import{execFileSync as Qd,spawn as HJ}from"node:child_process";import{existsSync as GJ,mkdirSync as KJ,mkdtempSync as gD,openSync as WJ,rmSync as yD,writeFileSync as ef}from"node:fs";import{tmpdir as bD}from"node:os";import{join as Ar,resolve as qJ}from"node:path";import{execFileSync as pY}from"node:child_process";function mY(e,t){if(e===0)return{kind:"clean"};if(e!==1)return{kind:"unknown",reason:e===129?"this git does not know `merge-tree --write-tree` (needs git 2.38+)":`git merge-tree failed (exit ${e??"signal"})`};let n=t.split(`
379
379
  `),r=[];for(let o of n.slice(1)){if(o.trim()==="")break;r.includes(o)||r.push(o)}return{kind:"conflict",files:r}}a(mY,"classifyMergeTree");function iT(e,t=5){if(e.length===0)return"(git named no file)";let n=e.slice(0,t).join(", ");return e.length>t?`${n} and ${e.length-t} more`:n}a(iT,"fileList");function en(e,t){switch(e.kind){case"clean":return`applies cleanly to ${t}.`;case"conflict":return`conflicts with ${t} in ${iT(e.files)} \u2014 merge ${t} into the branch, resolve, push.`;case"unknown":return`could not check against ${t}: ${e.reason}.`}}a(en,"baseConflictLine");function sT(e,t){return{id:"base-conflict",verdict:e.kind==="clean"?"pass":e.kind==="conflict"?"fail":"not-checked",blocking:!0,note:e.kind==="clean"?void 0:en(e,t)}}a(sT,"baseConflictResult");var Sy=a((e,t)=>{try{return{status:0,stdout:pY("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:12e4,maxBuffer:16777216})}}catch(n){let r=n,o=typeof r.stdout=="string"?r.stdout:r.stdout?.toString("utf8")??"";return{status:typeof r.status=="number"?r.status:null,stdout:o}}},"realRunner");function Un(e,t,n="HEAD",r=Sy){if(r(["rev-parse","--verify","--quiet",`${t}^{commit}`],e).status!==0)return{kind:"unknown",reason:`${t} does not resolve`};let i=r(["merge-tree","--write-tree","--name-only","--no-messages",t,n],e);return mY(i.status,i.stdout)}a(Un,"readBaseConflict");function Wu(e,t,n,r,o=Sy){return Ry(e,t,n,r,o).verdict}a(Wu,"conflictBeforeApproval");function Ry(e,t,n,r,o=Sy){let i=Un(e,t,n,o);if(i.kind!=="conflict"||r===n)return{verdict:i,ownOnly:[]};let s=Un(e,t,r,o);return{verdict:s,ownOnly:s.kind==="clean"?i.files:[]}}a(Ry,"readBaseConflictUnderOwnCommits");function xa(e,t){return`only promote's own commits of an earlier run conflict with ${t} (${iT(e)}) \u2014 promote takes its release commit back and numbers anew; the commits under them apply cleanly.`}a(xa,"ownCommitsConflictLine");import{execFileSync as hY}from"node:child_process";import{mkdirSync as aT,readFileSync as gY,writeFileSync as lT}from"node:fs";import{homedir as cT}from"node:os";import{join as qu}from"node:path";function yY(e,t){try{return hY("git",["-c","core.quotepath=off",...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}a(yY,"git");function bY(e,t){return mp(yY(e,["log",`--format=${pp}`,`${t}..HEAD`])??"")}a(bY,"branchCommits");async function Sa(e,t,n,r={}){try{let o=hp((r.commits??bY)(e,t));if(o.length===0)return[];let i=qu(r.home??cT(),".maind",Vl,yp),s=qu(i,Yl(n.id)),l=null;try{l=gY(s,"utf8")}catch{l=null}let c=bp(l),u=kp(o,c);if(u===null)return[];let d=await(r.lookup??Ht)([n.id]),f=d.ok?d.refs[0]:void 0;if(f===void 0||f.unresolved)return[];try{let p=qu(r.home??cT(),".maind",Vl,_p);aT(p,{recursive:!0}),lT(qu(p,Yl(n.id)),wp(f.lessonCheck==="on",new Date))}catch{}if(f.lessonCheck!=="on")return[];try{aT(i,{recursive:!0}),lT(s,JSON.stringify({key:n.key,asked:[...c,zl(u.source)]}))}catch{}return[gp(u.source,u.check)]}catch{return[]}}a(Sa,"lessonCheck");function uT(e,t,n={}){let r=n.graceMs??3e4,o=n.pollMs??6e4,i=n.maxMs??864e5,s=e.now();e.sleep(r);let l=null;for(;;){if(!e.exists(t))return{kind:"gone"};if(l=e.occupants(t),l!==null&&l.length===0)return{kind:"free",waitedMs:e.now()-s};if(e.now()-s+o>i)return{kind:"timeout",occupants:l};e.sleep(o)}}a(uT,"waitUntilFree");function dT(e){return e.byBranch?["feature","done","--branch",e.branch,"--when-free"]:["feature","done",e.label,"--when-free"]}a(dT,"whenFreeArgs");import{execFileSync as kY}from"node:child_process";import{mkdirSync as _Y,writeFileSync as wY}from"node:fs";import{homedir as vY}from"node:os";import{join as fT}from"node:path";function pT(e){return e.documents>0?{remind:!1,why:"document_in_branch"}:e.decision.kind==="ok"?{remind:!1,why:"doc_decision"}:null}a(pT,"decideLocally");function xY(e){let t=pT(e);if(t)return t;let n=e.server;return n?.status==="passed"||n?.status==="canceled"?{remind:!1,why:"finished"}:n?.duty==="off"?{remind:!1,why:"duty_off"}:n?.inReview?{remind:!1,why:"in_review"}:n&&n.docMissing===!1?{remind:!1,why:"documented_elsewhere"}:{remind:!0,text:Hp(e.key,n?.duty==="require")}}a(xY,"decideDocReminder");function SY(e,t){return e.remind?t?[e.text]:[e.text,"(the server did not answer \u2014 reminded anyway)"]:[]}a(SY,"docReminderLines");function Ey(e,t){try{return kY("git",["-c","core.quotepath=off",...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}a(Ey,"git");function RY(e){return e===void 0||e.unresolved?null:{duty:e.docDuty??null,docMissing:e.docMissing??null,inReview:e.docInReview===!0,status:e.status??null}}a(RY,"serverOf");async function Ra(e,t,n,r={}){try{let o=(Ey(e,["diff","--name-only",`${t}...HEAD`])??"").split(`
380
380
  `).filter(Boolean),i=dn(o,f=>Ey(e,["show",`HEAD:${f}`]),n.key).length,s=(Ey(e,["log","--reverse","--format=%B%x00",`${t}..HEAD`])??"").split("\0").filter(f=>f.trim()!==""),l={key:n.key,documents:i,decision:rr(s)};if(pT(l))return[];let c=await(r.lookup??Ht)([n.id]),u=c.ok?RY(c.refs[0]):null,d=xY({...l,server:u});if(!d.remind)return[];try{let f=fT(r.home??vY(),".maind","doc-duty",Gp);_Y(f,{recursive:!0}),wY(fT(f,Kp(n.id)),JSON.stringify({said_at:(r.now?.()??new Date).toISOString(),key:n.key}))}catch{}return SY(d,u!==null)}catch{return[]}}a(Ra,"docReminder");import{execFileSync as EY}from"node:child_process";function AY(e,t){return e.kind!=="absent"?[]:[`${t.key} has no plan attached \u2014 if a plan was accepted for this work, attach it before the merge: maind object plan --object ${t.id} --file <plan.md> (or work_object_attach_plan)`]}a(AY,"planNoteLines");function $Y(e,t){try{let n=EY("git",["config","--get",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n===""?null:n}catch{return null}}a($Y,"gitConfig");async function Vu(e,t,n,r={}){try{if($Y(e,`branch.${t}.maindPlan`)!==null)return[];let o=await(r.lookup??Ht)([n.id]);return AY(Tu(o,n.id),n)}catch{return[]}}a(Vu,"planNote");import{execFileSync as TY}from"node:child_process";function CY(e,t){return e.some(n=>{let r=n.endsWith("/")?n:`${n}/`;return t.some(o=>o===n||o.startsWith(r))})}a(CY,"inArea");function OY(e){let t=/#(\d+)$/.exec(e);return t?`#${t[1]}`:e}a(OY,"refLabel");var mT=80;function Ay(e){return e.length>mT?`${e.slice(0,mT-1)}\u2026`:e}a(Ay,"clip");function IY(e,t,n){let r=[];for(let o of e){if(o.objectId===n||!CY(o.anchors,t))continue;let i=o.key??Ay(o.title),s=[...new Set(o.refs.map(OY))].join(", "),l=o.documents[0];r.push(`since you branched: ${i}${s?` (${s})`:""} landed in this area`+(l?` \u2014 ${l.kind==="decision"?"decision":"read"} ${Ay(l.title)}`:` \u2014 ${Ay(o.title)}`))}return r}a(IY,"landedLines");function NY(e){let t=e?.objects;if(!Array.isArray(t))return[];let n=a(r=>Array.isArray(r)?r.filter(o=>typeof o=="string"):[],"strings");return t.flatMap(r=>{if(typeof r!="object"||r===null)return[];let o=r;if(typeof o.object_id!="string")return[];let i=Array.isArray(o.merges)?o.merges:[],s=Array.isArray(o.documents)?o.documents:[];return[{objectId:o.object_id,key:typeof o.key=="string"?o.key:null,title:typeof o.title=="string"?o.title:"",refs:i.flatMap(l=>typeof l?.ref=="string"?[l.ref]:[]),anchors:n(o.anchors),documents:s.flatMap(l=>{let c=l;return typeof c?.title=="string"?[{title:c.title,kind:typeof c.kind=="string"?c.kind:"other"}]:[]})}]})}a(NY,"parseLandedObjects");function Ea(e,t){try{return TY("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}a(Ea,"git");function DY(e,t){let n=(Ea(e,["rev-list","--first-parent","--reverse",`${t}..HEAD`])??"").split(`
381
381
  `)[0]?.trim();return n&&Ea(e,["show","-s","--format=%cI",`${n}^`])||null}a(DY,"forkPointDate");function MY(e,t){let n=Ea(e,["merge-base",t,"HEAD"]);if(!n)return null;let r=Ea(e,["-c","core.quotepath=off","diff","--name-only",n]);return r===null?null:r.split(`
@@ -585,7 +585,8 @@ ${i.stderr??""}`.split(`
585
585
  # for the answer (default 30 min; read every 15 s for the first
586
586
  # 5 min, then every minute) and merge once
587
587
  # approved \u2014 instead of stopping with exit 3. In a terminal
588
- # promote waits by default; --no-wait stops instead
588
+ # promote waits by default; --no-wait stops instead. While it
589
+ # waits, the object's page says so, with the time it waits until
589
590
  # gate, wait on required checks, merge, clean up
590
591
  # a branch bound to a work object must say which of the two
591
592
  # --override: a declared gate is red for a reason an OPEN