@maind-dev/cli 0.172.1 → 0.173.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
@@ -8,7 +8,7 @@ ${rc(e.body)}`:[...e.verbs,e.solvedBy??""].join(`
8
8
  `))return{meta:"",body:e};let t=e.indexOf(`
9
9
  ---`,3);if(t===-1)return{meta:"",body:e};let n=e.indexOf(`
10
10
  `,t+4);return{meta:e.slice(4,t),body:n===-1?"":e.slice(n+1)}}a(rm,"splitFrontMatter");var QB=/^\s*\*\*[^*]{1,40}:\*\*/;function ac(e){return e.replace(/\s+/g," ").trim()}a(ac,"clean");function om(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(" ");return`${r>t*.6?n.slice(0,r):n}\u2026`}a(om,"cap");function im(e,t){let{meta:n,body:r}=rm(e),i=/^#\s+(.+)$/m.exec(r)??/^#{2,6}\s+(.+)$/m.exec(r),s=/^title:\s*["']?(.+?)["']?\s*$/m.exec(n),l=i?.[1]??s?.[1]??ox(t);return om(ac(l),JB)}a(im,"documentTitle");function sm(e){let{body:t}=rm(e),n=t.split(/\r?\n/),r=[],o=!1;for(let i of n){let s=i.trim();if(o){s.includes("-->")&&(o=!1);continue}if(s.startsWith("<!--")){s.includes("-->")||(o=!0);continue}if(s===""){if(r.length>0)break;continue}r.length===0&&(s.startsWith("#")||QB.test(s)||/^[-*_]{3,}$/.test(s))||r.push(s)}if(r.length!==0)return om(ac(r.join(" ")),ZB)}a(sm,"documentExcerpt");function am(e){return(/\*\*(?:Datum|Date):\*\*\s*(\d{4}-\d{2}-\d{2})/.exec(e)??/^date:\s*["']?(\d{4}-\d{2}-\d{2})/m.exec(rm(e).meta))?.[1]}a(am,"documentDate");function pn(e,t,n,r){let o=tm(n);if(!o)return[];let i=[];for(let s of e){let l=s.trim();if(l===""||!Es(l)||i.some(m=>m.path===l))continue;let c=t(l);if(c===null||!o.test(c))continue;let u={path:l,title:im(c,l),kind:nm(l)},d=sm(c);d&&(u.excerpt=d);let f=am(c);f&&(u.doc_date=f);let p=r?.(l);if(p&&(u.url=p),i.push(u),i.length>=Ip)break}return i}a(pn,"collectDocuments");function As(e){let t=e.trim();return t.length<4?!1:!["1","true","false","yes","no","on","skip","none","n/a","na","ok"].includes(t.toLowerCase())}a(As,"isDocDecisionReason");var eU=/^Doc-Decision:[ \t]*(none|elsewhere)[ \t]*(?:[-–—:][ \t]*)?(.*)$/gim;function cr(e){let t={kind:"none"};for(let n of e)for(let r of n.matchAll(eU)){let o=ac(r[2]??"");t=As(o)?{kind:"ok",decision:{decision:r[1].toLowerCase(),reason:om(o,nc)}}:{kind:"invalid",line:ac(r[0])}}return t}a(cr,"parseDocDecision");function lc(e,t,n){return`https://github.com/${e}/blob/${encodeURIComponent(t)}/${n.split("/").map(r=>encodeURIComponent(r)).join("/")}`}a(lc,"githubBlobUrl");var tU="([A-Z][A-Z0-9]{0,5})-0*([0-9]{1,9})",nU=new RegExp(`^${tU}$`),rU=/\(([^()]{1,200})\)/g,lm=String.raw`close[sd]?|fix(?:e[sd])?|resolve[sd]?`,oU=String.raw`refs?|references|part\s+of|related\s+to|contributes\s+to|towards?`,iU=new RegExp(String.raw`^\s*(?:${lm}|${oU}):?\s+(.+)$`,"i"),sU=new RegExp(String.raw`^\s*(?:${lm}):?\s+(.+)$`,"i"),ix=20;function Qp(e){let t=e.split(/\s*[,/]\s*/).map(r=>r.trim()),n=[];for(let r of t){let o=nU.exec(r);if(!o)return null;n.push(`${o[1]}-${Number.parseInt(o[2],10)}`)}return n.length>0?n:null}a(Qp,"keysOfList");function cc(e){let t=[],n=a(r=>{for(let o of r??[])!t.includes(o)&&t.length<ix&&t.push(o)},"add");for(let r of e){let o=r.split(/\r?\n/),i=o[0]??"";for(let s of i.matchAll(rU))n(Qp(s[1].trim()));for(let s of o.slice(1)){let l=iU.exec(s);l&&n(Qp(l[1].trim()))}}return t}a(cc,"objectKeysInCommits");function uc(e){let t=[];for(let n of e)for(let r of n.split(/\r?\n/).slice(1)){let o=sU.exec(r);for(let i of(o?Qp(o[1].trim()):null)??[])!t.includes(i)&&t.length<ix&&t.push(i)}return t}a(uc,"closingKeysInCommits");function cm(e){return e.duty==="off"?"off":e.duty==="require"&&e.docMissing===!0?"block":"warn"}a(cm,"docGateAction");function um(e,t){return`[maind] Documentation duty for ${e} is still open: this work has no document that names ${e} and no recorded exception. In THIS branch, before the merge approval, either add or update a Markdown document (ADR, note, session note) that names ${e}, or \u2014 if none is needed \u2014 put a trailer in a commit: "Doc-Decision: none - <reason>" (or "Doc-Decision: elsewhere - <owner/repo#pr>"). The approval binds the head, and a document written after the merge needs a pull request of its own.`+(t?" This organization requires it: `maind feature promote` refuses to merge without it.":"")}a(um,"docDutyReminderText");var dm="said",aU=12*60*60*1e3;function fm(e){return`${e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)}.json`}a(fm,"docDutySaidFile");var sx=y.object({version:y.literal(1).default(1),org_visibility:y.boolean().default(!1),session_span_visibility:y.boolean().default(!0)}),lU=sx.parse({});var ax=y.object({tools:y.array(y.string()).default([]),languages:y.array(y.string()).default([]),platforms:y.array(y.string()).default([]),tags:y.array(y.string()).default([])}),lx=y.object({id:y.string().uuid(),user_id:y.string().uuid(),project:y.string().max(200).nullable().optional(),title:y.string().min(1).max(200),body:y.string().min(1).max(2e4),context:ax.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:y.string(),updated_at:y.string(),last_recalled_at:y.string().nullable().optional(),recall_count:y.number().int().nonnegative().default(0),graduated_draft_id:y.string().uuid().nullable().optional(),deleted_at:y.string().nullable().optional()}),cU=lx.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:y.number()}),uU=y.object({id:y.string().uuid(),title:y.string(),summary:y.string(),tags:y.array(y.string()).default([])});var dU=new Set(["|",">","|-",">-","|+",">+"]),fU=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;function dc(e){let t=[],n=null;return e.split(`
11
- `).forEach((r,o)=>{let i=r.trim(),s=r.length-r.trimStart().length;if(n!==null){if(i===""||s>n)return;n=null}if(i===""||i.startsWith("#"))return;let l=fU.exec(r);if(!l)return;let c=l[3]??"";if(dU.has(c.trim())){n=s;return}let u=c.split(/\s+#/)[0].trim();u===""||`'"[{&*`.includes(u[0])||u.includes(": ")&&t.push({line:o+1,value:u})}),t}a(dc,"plainScalarViolations");function mn(e,t){let n=a(l=>{let[c,u=""]=l.split("-",2),d=c.split(".").map(f=>{let p=Number(f);return Number.isFinite(p)?p:0});for(;d.length<3;)d.push(0);return[d,u.length>0?u.split("."):[]]},"split"),[r,o]=n(e),[i,s]=n(t);for(let l=0;l<Math.max(r.length,i.length);l+=1){let c=(r[l]??0)-(i[l]??0);if(c!==0)return c<0?-1:1}if(o.length===0&&s.length===0)return 0;if(o.length===0)return 1;if(s.length===0)return-1;for(let l=0;l<Math.max(o.length,s.length);l+=1){let c=o[l],u=s[l];if(c===void 0)return-1;if(u===void 0)return 1;let d=/^\d+$/.test(c),f=/^\d+$/.test(u);if(d&&f){let p=Number(c)-Number(u);if(p!==0)return p<0?-1:1}else{if(d!==f)return d?-1:1;if(c!==u)return c<u?-1:1}}return 0}a(mn,"compareSemver");var cx=["gate","base_conflict","checks_red","checks_unknown","head_moved","not_pushed","merge_failed","number_taken","release_failed","rebase_merge_commit","title_not_conventional","commits_not_conventional","wrong_base","method_not_allowed","approval_declined","approval_not_given","approval_unchecked"];function pm(e){return typeof e=="string"&&cx.includes(e)}a(pm,"isPromoteStopReason");var mm={gate:"the gate was red",base_conflict:"the branch conflicts with the base",checks_red:"required checks were red",checks_unknown:"required checks could not be determined",head_moved:"someone pushed while promote prepared the merge",not_pushed:"the local branch was ahead of the pull request",merge_failed:"the forge refused the merge",number_taken:"a version number was taken in the meantime",release_failed:"preparing the release failed",rebase_merge_commit:"a rebase merge would have carried a merge commit",title_not_conventional:"the title is not a conventional commit",commits_not_conventional:"a commit is not a conventional commit",wrong_base:"the pull request targets another base",method_not_allowed:"the chosen merge method is not allowed",approval_declined:"the merge approval said don't merge",approval_not_given:"the merge approval was not given",approval_unchecked:"the merge approval could not be checked"},hm={approval_unchecked:"approval_not_given"};var ux=/^[A-Za-z0-9][A-Za-z0-9:._/@-]{0,99}$/;function fc(e){return typeof e=="string"&&ux.test(e)}a(fc,"isGateId");function gm(e){let t=[];for(let n of e)if(!(!fc(n.id)||t.some(r=>r.id===n.id))&&(t.push({id:n.id,timedOut:n.timedOut===!0}),t.length===20))break;return t}a(gm,"reportableRedGates");var Ot=".maind/gates.json",fx=["block","warn","off"],pU="det_doc_decision";function mU(e){return typeof e=="string"&&fx.includes(e)}a(mU,"isDetectorSetting");function hU(e,t){let n={},r=[];if(e==null)return{settings:n,ignored:r};if(typeof e!="object"||Array.isArray(e))return t.push('"detectors" must be an object: detector id \u2192 "block", "warn" or "off"'),{settings:n,ignored:r};for(let[o,i]of Object.entries(e))if(!o.startsWith("_")){if(!mU(i)){t.push(`"detectors" \u2192 "${o}" must be "block", "warn" or "off"`);continue}if(o===pU){r.push({id:o,why:"its severity follows the organisation's documentation duty (doc_duty in the planning policy) \u2014 set it there"});continue}if(!ro(o)){r.push({id:o,why:"not a detector this version knows \u2014 ignored, so the run is no milder for it"});continue}n[o]=i}return{settings:n,ignored:r}}a(hU,"parseDetectorsSection");var px=10,ii=10,mx=!0;function pc(){return{skip:[],timeoutMinutes:px,commands:{}}}a(pc,"defaultTestsConfig");function si(){return mx?{...pc(),implicit:!0}:null}a(si,"implicitTestsConfig");function $s(e){let t=e.trim().replace(/^\.\//,"").replace(/\/+$/,"");return t===""||t==="."?".":t}a($s,"normalizeTestDir");function gU(e,t){if(e==null)return si();if(e===!0)return pc();if(e===!1)return null;if(typeof e!="object"||Array.isArray(e))return t.push('"tests" must be true, false or an object'),null;let n=e,r=pc(),o=t.length;if(n.skip!==void 0&&(!Array.isArray(n.skip)||n.skip.some(i=>typeof i!="string"||i.trim().length===0)?t.push('"tests.skip" must be an array of package directories'):r.skip=[...new Set(n.skip.map($s))]),n.timeoutMinutes!==void 0){let i=n.timeoutMinutes;typeof i!="number"||!Number.isFinite(i)||i<1||i>120?t.push('"tests.timeoutMinutes" must be a number between 1 and 120'):r.timeoutMinutes=i}if(n.commands!==void 0){let i=n.commands;if(i===null||typeof i!="object"||Array.isArray(i))t.push('"tests.commands" must be an object: package directory \u2192 command');else for(let[s,l]of Object.entries(i)){if(typeof l!="string"||l.trim().length===0){t.push(`"tests.commands" \u2192 "${s}" must be a non-empty command string`);continue}r.commands[$s(s)]=l.trim()}}if(n.inputs!==void 0){let i=n.inputs;if(i===null||typeof i!="object"||Array.isArray(i))t.push('"tests.inputs" must be an object: package directory \u2192 array of path prefixes');else{let s={};for(let[l,c]of Object.entries(i)){if(!Array.isArray(c)||c.length===0||c.some(u=>typeof u!="string"||u.trim().length===0)){t.push(`"tests.inputs" \u2192 "${l}" must be a non-empty array of path prefixes`);continue}s[$s(l)]=[...new Set(c.map(u=>u.trim().replace(/^\.\//,"")))]}Object.keys(s).length>0&&(r.inputs=s)}}if(n.databases!==void 0){let i=n.databases;if(i===null||typeof i!="object"||Array.isArray(i))t.push('"tests.databases" must be an object: package directory \u2192 { "supabase": "<directory that holds supabase/>" }');else{let s={};for(let[l,c]of Object.entries(i)){let u=c,d=u!==null&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u).filter(f=>!f.startsWith("_")):null;if(d===null||d.length!==1||d[0]!=="supabase"||typeof u.supabase!="string"||u.supabase.trim().length===0){t.push(`"tests.databases" \u2192 "${l}" must be { "supabase": "<directory that holds supabase/>" }`);continue}s[$s(l)]={supabase:$s(u.supabase)}}Object.keys(s).length>0&&(r.databases=s)}}for(let i of Object.keys(n))i.startsWith("_")||["skip","timeoutMinutes","commands","inputs","databases"].includes(i)||t.push(`"tests.${i}" is not a known setting (known: skip, timeoutMinutes, commands, inputs, databases)`);return t.length>o?null:r}a(gU,"parseTestsSection");var ur=".maind/gates.d";function dx(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e))return{problem:`${t} must be an object`};let r=e,o=r.id;if(n!==null){if(o!==void 0&&o!==n)return{problem:`${t}: "id" is "${String(o)}", but the file name says "${n}" \u2014 the file name is the id`};o=n}if(typeof o!="string"||o.trim().length===0)return{problem:`${t}.id must be a non-empty string`};let i=r.run;if(typeof i!="string"||i.trim().length===0)return{problem:`${t}.run must be a non-empty command string`};let s=!0;if("blocking"in r&&r.blocking!==void 0&&r.blocking!==null){if(typeof r.blocking!="boolean")return{problem:`${t}.blocking must be a boolean`};s=r.blocking}let l,c=r.when;if(c!=null){if(typeof c!="object"||Array.isArray(c))return{problem:`${t}.when must be an object`};let f=c.paths;if(f!=null){if(!Array.isArray(f)||f.some(p=>typeof p!="string"||p.trim().length===0))return{problem:`${t}.when.paths must be an array of non-empty path prefixes`};l=f}}let u=!1;if("onShip"in r&&r.onShip!==void 0&&r.onShip!==null){if(typeof r.onShip!="boolean")return{problem:`${t}.onShip must be a boolean`};u=r.onShip}let d=!1;if("beforeApproval"in r&&r.beforeApproval!==void 0&&r.beforeApproval!==null){if(typeof r.beforeApproval!="boolean")return{problem:`${t}.beforeApproval must be a boolean`};d=r.beforeApproval}return{id:o,run:i,blocking:s,...l?{paths:l}:{},...u?{onShip:u}:{},...d?{beforeApproval:d}:{}}}a(dx,"parseGateEntry");function ym(e,t=[]){let n=[],r=e===void 0;if(!r&&(e===null||typeof e!="object"||Array.isArray(e)))return{problems:["the manifest must be a JSON object"]};let o=r?{}:e,i=o.gates;if(i===void 0&&t.length===0&&o.tests===void 0&&o.detectors===void 0)return{problems:[`the manifest needs a "gates" array (or one file per gate under ${ur}/)`]};if(i!==void 0&&!Array.isArray(i))return{problems:['"gates" must be an array']};let s=[],l=new Map,c=a((_,w)=>{if("problem"in _){n.push(_.problem);return}let v=l.get(_.id);if(v!==void 0){n.push(`${w}.id "${_.id}" is declared more than once (also ${v})`);return}l.set(_.id,w),s.push(_)},"take");(Array.isArray(i)?i:[]).forEach((_,w)=>c(dx(_,`gates[${w}]`,null),`gates[${w}]`));for(let _ of t){let w=`${ur}/${_.file}`;if(_.parseError!==void 0){n.push(`${w}: not valid JSON: ${_.parseError}`);continue}c(dx(_.raw,w,_.file.replace(/\.json$/,"")),w)}let u=[],d=o.versionedPackages!==void 0,f=o.versionedPackages;if(f!==void 0)if(!Array.isArray(f))n.push('"versionedPackages" must be an array');else{let _=new Set;f.forEach((w,v)=>{let R=`versionedPackages[${v}]`;if(w===null||typeof w!="object"||Array.isArray(w)){n.push(`${R} must be an object`);return}let x=w,O=x.dir;if(typeof O!="string"||O.trim().length===0){n.push(`${R}.dir must be a non-empty path`);return}if(_.has(O)){n.push(`${R}.dir "${O}" is declared more than once`);return}_.add(O);let T=x.mirror;if(T!==void 0&&(typeof T!="string"||T.trim().length===0)){n.push(`${R}.mirror must be a non-empty path relative to dir`);return}let S=x.changelog;if(S!==void 0&&typeof S!="boolean"){n.push(`${R}.changelog must be a boolean`);return}let $=x.numbering;if($!==void 0&&$!=="hand"&&$!=="promote"){n.push(`${R}.numbering must be "hand" or "promote"`);return}let C=x.tag;if(C!==void 0&&(typeof C!="string"||!C.includes("{version}"))){n.push(`${R}.tag must be a template containing {version}, e.g. "my-pkg-v{version}"`);return}if(C!==void 0&&$!=="promote"){n.push(`${R}.tag only applies with numbering "promote" \u2014 promote is what sets it`);return}let I=x.fragments;if(I!==void 0&&(typeof I!="string"||I.trim().length===0)){n.push(`${R}.fragments must be a non-empty path relative to dir`);return}u.push({dir:O.replace(/\/+$/,""),changelog:S??!0,numbering:$??"hand",fragments:typeof I=="string"?I.replace(/\/+$/,""):"changelog.d",...typeof T=="string"?{mirror:T}:{},...typeof C=="string"?{tag:C}:{}})})}let p=!1,m=o.requireWorkObject;m!==void 0&&(typeof m!="boolean"?n.push('"requireWorkObject" must be a boolean'):p=m);let h=!1,b=o.review;b!==void 0&&(typeof b!="boolean"?n.push('"review" must be a boolean'):h=b);let g=gU(o.tests,n),k=hU(o.detectors,n);return n.length>0?{problems:n}:{gates:s,versioned:u,versionedDeclared:d,requireWorkObject:p,review:h,tests:g,detectors:k.settings,detectorsIgnored:k.ignored}}a(ym,"parseGatesManifest");function Ts(e,t){let n=e.file(Ot),r=e.list(ur).filter(s=>s.endsWith(".json")).sort().map(s=>{let l=e.file(`${ur}/${s}`)??"";try{return{file:s,raw:JSON.parse(l)}}catch(c){return{file:s,parseError:c.message}}});if(n===null&&r.length===0)return{kind:"absent",gates:[],versioned:[],versionedDeclared:!1,requireWorkObject:!1,review:!1,tests:si(),detectors:{},detectorsIgnored:[]};let o;if(n!==null)try{o=JSON.parse(n)}catch(s){return{kind:"invalid",path:t,problems:[`not valid JSON: ${s.message}`]}}let i=ym(o,r);return"problems"in i?{kind:"invalid",path:t,problems:i.problems}:{kind:"loaded",gates:i.gates,versioned:i.versioned,versionedDeclared:i.versionedDeclared,requireWorkObject:i.requireWorkObject,review:i.review,tests:i.tests,detectors:i.detectors,detectorsIgnored:i.detectorsIgnored,path:t}}a(Ts,"readGatesManifest");function Xt(e,t){let n=`${e.dir.replace(/\/+$/,"")}/`,r=new Set([`${n}package.json`]);return e.mirror&&r.add(`${n}${e.mirror}`),t.some(o=>o.startsWith(n)&&!o.endsWith(".md")&&!r.has(o))}a(Xt,"versionClaimApplies");function dr(e,t){let n=`${e.dir.replace(/\/+$/,"")}/${e.fragments}/`;if(!t.startsWith(n))return!1;let r=t.slice(n.length);return!r.includes("/")&&/\.md$/i.test(r)&&!/^readme\.md$/i.test(r)}a(dr,"isFragmentPath");var jn={gates:"https://maind.dev/schemas/gates.schema.json",gateFile:"https://maind.dev/schemas/gate-file.schema.json",specContracts:"https://maind.dev/schemas/spec-contracts.schema.json",mockupLabels:"https://maind.dev/schemas/mockup-labels.schema.json"},mc="http://json-schema.org/draft-07/schema#",Dn={"^_":{}},hc={type:"string",description:"Pointer to this schema, so an editor validates the file while you type."},Te={type:"string",minLength:1},gx={run:{...Te,description:'Shell command, run in the repository root. Exit code 0 passes, any other fails; output containing the sentence "skipping the gate" reports the gate as NOT CHECKED instead of passed.'},blocking:{type:"boolean",default:!0,description:"Does a failure stop ship and promote? Default true. A non-blocking failure is REPORTED and lets the merge continue."},when:{type:"object",additionalProperties:!1,properties:{paths:{type:"array",items:Te,description:"Repository-relative path PREFIXES, not globs. The gate runs only when the diff touches one of them; without `when`, it always runs."}}},onShip:{type:"boolean",default:!1,description:"Also run before `maind feature ship` pushes. For cheap gates only (seconds)."},beforeApproval:{type:"boolean",default:!1,description:"Run after the push and before the merge approval is asked; a red result means the approval is not asked. For cheap gates that turn red with time (deadlines, pins)."}},yU=Object.keys(ar).filter(e=>e!=="det_doc_decision"),bU={$schema:mc,$id:jn.gates,title:".maind/gates.json",description:'What this repository declares for `maind gate`, `maind feature ship` and `maind feature promote`. The built-in checks run without this file; it adds the repository\'s own gates and settings. A missing file is fine, a broken one refuses to run \u2014 an empty gate list would look like "all green".',type:"object",additionalProperties:!1,patternProperties:Dn,properties:{$schema:hc,gates:{type:"array",description:"This repository's own gates, run in order. Each gate can also live in its own file `.maind/gates.d/<id>.json` (the file name is the id) \u2014 then two branches that each add a gate never edit the same file.",items:{type:"object",additionalProperties:!1,required:["id","run"],patternProperties:Dn,properties:{id:{...Te,description:"Unique name of the gate; it appears in every result line."},...gx}}},tests:{description:"The built-in test gate: the test script of every package the diff affects (and of the packages that depend on it). On by default; `false` turns it off, an object tunes it.",oneOf:[{type:"boolean"},{type:"object",additionalProperties:!1,patternProperties:Dn,properties:{skip:{type:"array",items:Te,description:"Package directories whose suite does not run."},timeoutMinutes:{type:"number",minimum:1,maximum:120,default:10,description:"Time limit per suite."},commands:{type:"object",additionalProperties:Te,description:"Package directory \u2192 command, run in that directory. The way to test packages that are not JS/TS."},inputs:{type:"object",additionalProperties:{type:"array",minItems:1,items:Te},description:"Package directory \u2192 path prefixes the suite reads outside its package and its dependencies. A change there makes the suite affected."},databases:{type:"object",additionalProperties:{type:"object",additionalProperties:!1,required:["supabase"],patternProperties:Dn,properties:{supabase:{...Te,description:"The directory that holds `supabase/` with its migrations (`.` for the repository root)."}}},description:"Package directory \u2192 the clean database its suite needs. The gate starts a throwaway database for the run, applies the migrations of the tree it judges (base plus branch), hands the suite the connection as DATABASE_URL and PG* variables, and removes it afterwards. Never the database you develop against. Needs Docker and the Supabase CLI; without them the suite is NOT CHECKED, with the reason."}}}]},detectors:{type:"object",description:"The severity of a built-in detector in this repository: block, warn (reported, does not stop the merge) or off (NOT CHECKED, with the number of findings it would have reported). Replaces the catalog default, never a review verdict \u2014 where the server judged the findings, the organisation's policy decides. A branch that makes a detector milder weakens its own gates and is reported by the gate-manifest check. det_doc_decision follows the organisation's doc_duty and cannot be set here.",patternProperties:Dn,propertyNames:{anyOf:[{enum:yU},{pattern:"^_"}]},additionalProperties:{enum:["block","warn","off"]}},requireWorkObject:{type:"boolean",default:!1,description:"Every branch must be bound to a work object of maind planning. Off by default \u2014 a repository without maind planning is never blocked."},review:{type:"boolean",default:!1,description:"Run the review against the repository's conventions as a gate. It calls the maind server and needs the Team plan, so it is off by default."},versionedPackages:{type:"array",description:`Packages whose version number is assigned deliberately. A change to a package's code needs a number greater than the base's, or \u2014 with numbering "promote" \u2014 a changelog fragment, and promote assigns the number right before the merge.`,items:{type:"object",additionalProperties:!1,required:["dir"],patternProperties:Dn,properties:{dir:{...Te,description:"Repository-relative package directory."},mirror:{...Te,description:"A second file (relative to dir) that carries the same number, e.g. src/version.ts."},changelog:{type:"boolean",default:!0,description:"Does the package keep a CHANGELOG.md that must name the number?"},numbering:{enum:["hand","promote"],default:"hand",description:"Who assigns the number: the branch (hand) or `maind feature promote` right before the merge (promote)."},tag:{type:"string",pattern:"\\{version\\}",description:'Tag template promote sets after the merge, e.g. "my-cli-v{version}". Only with numbering "promote".'},fragments:{...Te,default:"changelog.d",description:"Directory of changelog fragments, relative to dir."}}}}}},kU={$schema:mc,$id:jn.gateFile,title:".maind/gates.d/<id>.json",description:"One declared gate in a file of its own. The file name is the gate's id; an `id` field, if present, must match it.",type:"object",additionalProperties:!1,required:["run"],patternProperties:Dn,properties:{$schema:hc,id:Te,...gx}},hx={type:"array",items:Te,uniqueItems:!0},_U={$schema:mc,$id:jn.specContracts,title:".maind/spec-contracts.json",description:"Pairs of a NORMATIVE LIST and its IMPLEMENTATION that det_spec_drift compares \u2014 a design artefact against a navigation registry, an API spec against a router, a permission matrix against middleware. A contract declares EXTRACTION, NOT CONTENT: where the entries stand and how to read them, never which entries there should be. Without this file the detector abstains.",type:"object",additionalProperties:!1,patternProperties:Dn,required:["contracts"],properties:{$schema:hc,contracts:{type:"array",minItems:1,description:"All contracts. An empty list is not a green state \u2014 the detector abstains.",items:{$ref:"#/definitions/contract"}}},definitions:{contract:{type:"object",additionalProperties:!1,required:["id","reason","spec","impl"],properties:{id:{type:"string",pattern:"^[a-z0-9][a-z0-9-]*$",description:"Stable kebab-case id. It is part of every finding id (spec.drift:<id>#\u2026), so renaming it changes the output."},reason:{...Te,description:"Why this pair is guarded \u2014 ideally the incident that made it necessary. Without it nobody can tell in a year whether the contract still applies."},spec:{$ref:"#/definitions/recordSource",description:"The NORMATIVE side. Where the two disagree, it wins."},impl:{$ref:"#/definitions/recordSource",description:"The IMPLEMENTING side."},compare_fields:{...hx,description:"Fields the `fields` dimension compares. Omitted: membership and order only. Each field must be declared on both sides."},grounding:{$ref:"#/definitions/pathExists"},exceptions:{type:"array",items:{$ref:"#/definitions/exception"},description:"Deliberate, explained deviations. They are reported as info and stay visible."},assertions:{type:"array",items:{$ref:"#/definitions/proseAssertion"}}}},recordSource:{oneOf:[{$ref:"#/definitions/objectArray"},{$ref:"#/definitions/nestedLiteralList"}]},objectArray:{type:"object",additionalProperties:!1,required:["extractor","path","symbol","key_field"],description:"`const X = [{\u2026}, {\u2026}]` in a .ts/.tsx/.js/.mjs file or a <script> block. Read as TEXT, never evaluated. Fields that are not strings are ignored.",properties:{extractor:{const:"object-array"},path:{...Te,description:"Repository-relative path. An unreadable path is reported as contract.unreadable \u2014 a pointer error, not drift."},symbol:{...Te,description:"Name of the constant \u2014 the anchor of the contract. Renaming it without updating the manifest is reported as contract.unreadable."},key_field:{...Te,description:"The field that carries identity across both sides, e.g. href. An entry without it makes the contract partial; it does not vanish."},fields:{...hx,description:"Fields taken into each record. Omitted: all string fields."},partition_by:{type:"array",items:Te,description:"Fields whose values form the order partitions; order is compared within a partition. Omitted: one flat partition."}}},nestedLiteralList:{type:"object",additionalProperties:!1,required:["extractor","path","symbol","levels","key_field"],description:"A nested literal whose LEVELS are declared here. Fields accumulate inwards \u2014 the outer level contributes e.g. the area, the middle one the group, the leaf the label and target. Only leaves become records.",properties:{extractor:{const:"nested-literal-list"},path:{$ref:"#/definitions/objectArray/properties/path"},symbol:{$ref:"#/definitions/objectArray/properties/symbol"},key_field:{$ref:"#/definitions/objectArray/properties/key_field"},fields:{$ref:"#/definitions/objectArray/properties/fields"},partition_by:{$ref:"#/definitions/objectArray/properties/partition_by"},levels:{type:"array",minItems:1,items:{$ref:"#/definitions/level"},description:"Outer to inner. The LAST level is the leaf and yields the records."}}},level:{type:"object",additionalProperties:!1,required:["name","shape"],properties:{name:{...Te,description:"For readability only \u2014 the extractor works by position."},shape:{enum:["object","tuple"],description:"object: { id: '\u2026' }, fields by name. tuple: ['Label', '/target'], fields by position."},fields:{type:"object",additionalProperties:{oneOf:[Te,{type:"integer",minimum:0}]},description:"Output field name \u2192 source field name (object) or tuple index (tuple)."},children:{oneOf:[Te,{type:"integer",minimum:0}],description:"Where the child list stands: field name (object) or tuple index (tuple). Omit on the leaf level."}}},pathExists:{type:"object",additionalProperties:!1,required:["extractor","templates"],description:"Grounding: is there an artefact behind each key? Checked against TRACKED files, so build output cannot ground a key.",properties:{extractor:{const:"path-exists"},templates:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:"\\{key\\}"},description:"Repository-relative templates with exactly one {key}. Several mean OR (e.g. page.tsx or page.ts)."},strip_prefix:{...Te,description:"Cut from the front of the key before it is inserted, e.g. /."}}},exception:{type:"object",additionalProperties:!1,required:["dimension","key","reason"],properties:{dimension:{enum:["coverage","fields","order","extra","unrealized"],description:"The five comparison dimensions are closed; extend with new contracts, not new dimensions."},key:{...Te,description:"The record key; for fields: <key>.<field>."},reason:{...Te,description:"Why the deviation is right \u2014 so it can be removed once it no longer is."}}},proseAssertion:{type:"object",additionalProperties:!1,required:["path","prefix","counts","reason"],description:'A counted number in a prose document, e.g. "NAV_ITEMS (41)". Always a warning, never blocking. The expected number is DERIVED from one side, never written here.',properties:{path:Te,prefix:{...Te,description:"Literal text right BEFORE the number. Not a regular expression."},counts:{enum:["spec","impl"],description:"Which side supplies the expected number."},reason:Te}}}},wU={$schema:mc,$id:jn.mockupLabels,title:".maind/mockup-labels.json",description:"Sets of product mockups \u2014 a product tour, a demo, a screenshot rebuilt in code \u2014 whose labels det_mockup_label_drift holds against the product source. Each label is PINNED to the file that renders it, and the pin is checked both ways: the source still contains the label, and some mockup still shows it. Without this file the detector abstains.",type:"object",additionalProperties:!1,patternProperties:Dn,required:["sets"],properties:{$schema:hc,sets:{type:"array",minItems:1,description:"All sets. An empty list is not a green state \u2014 the detector abstains.",items:{$ref:"#/definitions/set"}}},definitions:{set:{type:"object",additionalProperties:!1,required:["id","reason","mockups"],oneOf:[{required:["pins_file"]},{required:["pins"]}],properties:{id:{type:"string",pattern:"^[a-z0-9][a-z0-9._-]*$",description:"Stable id; part of every finding."},reason:{...Te,description:"Why these mockups are pinned \u2014 the occasion, not the mechanics."},pins_file:{...Te,description:'Repository-relative JSON file with the pins: {"pins": [{"label", "source"}]} or a bare array.'},pins:{type:"array",items:{$ref:"#/definitions/pin"},description:"Pins inline, for small sets."},source_root:{...Te,description:"Repository-relative directory each pin's source is resolved against. Default: the repository root."},mockups:{type:"array",minItems:1,items:Te,description:"Repository-relative path prefixes of the mockups: a directory (ending in /) or a file. Tests and the pins file never count as mockups."},extensions:{type:"array",items:{type:"string",pattern:"^\\.[A-Za-z0-9]+$"},description:"File extensions read as mockups. Default: .ts .tsx .js .jsx .mjs .cjs .json .md .mdx .html .vue .svelte .astro."}}},pin:{type:"object",additionalProperties:!1,required:["label","source"],properties:{label:{...Te,description:"The text as the product renders it and the mockup shows it. Whitespace runs collapse on both sides."},source:{...Te,description:"The file that renders the label in the product, relative to source_root."}}}}};var vU={gates:{$schema:jn.gates,gates:[{id:"lint",run:"npm run lint",when:{paths:["src/"]}}],tests:{commands:{api:"pytest"}},detectors:{det_theme_class_drift:"warn"}},gateFile:{$schema:jn.gateFile,run:"node scripts/check-licenses.mjs",when:{paths:["package.json","pnpm-lock.yaml"]}},specContracts:{$schema:jn.specContracts,contracts:[{id:"nav-registry",reason:"Built from a summary once and shipped half the targets.",spec:{extractor:"object-array",path:"design/nav-spec.ts",symbol:"NAV_SPEC",key_field:"href",fields:["label"]},impl:{extractor:"object-array",path:"src/nav/registry.ts",symbol:"NAV_ITEMS",key_field:"href",fields:["label"]},compare_fields:["label"],grounding:{extractor:"path-exists",templates:["src/app/{key}/page.tsx"],strip_prefix:"/"}}]},mockupLabels:{$schema:jn.mockupLabels,sets:[{id:"product-tour",reason:"The tour kept a renamed sidebar item for weeks.",source_root:"apps/dashboard",pins:[{label:"Work objects",source:"src/components/Sidebar.tsx"}],mockups:["apps/website/src/components/tour/"]}]}};var Rx="1";function Ex(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
11
+ `).forEach((r,o)=>{let i=r.trim(),s=r.length-r.trimStart().length;if(n!==null){if(i===""||s>n)return;n=null}if(i===""||i.startsWith("#"))return;let l=fU.exec(r);if(!l)return;let c=l[3]??"";if(dU.has(c.trim())){n=s;return}let u=c.split(/\s+#/)[0].trim();u===""||`'"[{&*`.includes(u[0])||u.includes(": ")&&t.push({line:o+1,value:u})}),t}a(dc,"plainScalarViolations");function mn(e,t){let n=a(l=>{let[c,u=""]=l.split("-",2),d=c.split(".").map(f=>{let p=Number(f);return Number.isFinite(p)?p:0});for(;d.length<3;)d.push(0);return[d,u.length>0?u.split("."):[]]},"split"),[r,o]=n(e),[i,s]=n(t);for(let l=0;l<Math.max(r.length,i.length);l+=1){let c=(r[l]??0)-(i[l]??0);if(c!==0)return c<0?-1:1}if(o.length===0&&s.length===0)return 0;if(o.length===0)return 1;if(s.length===0)return-1;for(let l=0;l<Math.max(o.length,s.length);l+=1){let c=o[l],u=s[l];if(c===void 0)return-1;if(u===void 0)return 1;let d=/^\d+$/.test(c),f=/^\d+$/.test(u);if(d&&f){let p=Number(c)-Number(u);if(p!==0)return p<0?-1:1}else{if(d!==f)return d?-1:1;if(c!==u)return c<u?-1:1}}return 0}a(mn,"compareSemver");var cx=["gate","base_conflict","checks_red","checks_unknown","head_moved","not_pushed","merge_failed","number_taken","release_failed","rebase_merge_commit","title_not_conventional","commits_not_conventional","wrong_base","method_not_allowed","approval_declined","approval_not_given","approval_unchecked"];function pm(e){return typeof e=="string"&&cx.includes(e)}a(pm,"isPromoteStopReason");var mm={gate:"the gate was red",base_conflict:"the branch conflicts with the base",checks_red:"required checks were red",checks_unknown:"required checks could not be determined",head_moved:"someone pushed while promote prepared the merge",not_pushed:"the local branch was ahead of the pull request",merge_failed:"the forge refused the merge",number_taken:"a version number was taken in the meantime",release_failed:"preparing the release failed",rebase_merge_commit:"a rebase merge would have carried a merge commit",title_not_conventional:"the title is not a conventional commit",commits_not_conventional:"a commit is not a conventional commit",wrong_base:"the pull request targets another base",method_not_allowed:"the chosen merge method is not allowed",approval_declined:"the merge approval said don't merge",approval_not_given:"the merge approval was not given",approval_unchecked:"the merge approval could not be checked"},hm={approval_unchecked:"approval_not_given"};var ux=/^[A-Za-z0-9][A-Za-z0-9:._/@-]{0,99}$/;function fc(e){return typeof e=="string"&&ux.test(e)}a(fc,"isGateId");function gm(e){let t=[];for(let n of e)if(!(!fc(n.id)||t.some(r=>r.id===n.id))&&(t.push({id:n.id,timedOut:n.timedOut===!0}),t.length===20))break;return t}a(gm,"reportableRedGates");var Ot=".maind/gates.json",fx=["block","warn","off"],pU="det_doc_decision";function mU(e){return typeof e=="string"&&fx.includes(e)}a(mU,"isDetectorSetting");function hU(e,t){let n={},r=[];if(e==null)return{settings:n,ignored:r};if(typeof e!="object"||Array.isArray(e))return t.push('"detectors" must be an object: detector id \u2192 "block", "warn" or "off"'),{settings:n,ignored:r};for(let[o,i]of Object.entries(e))if(!o.startsWith("_")){if(!mU(i)){t.push(`"detectors" \u2192 "${o}" must be "block", "warn" or "off"`);continue}if(o===pU){r.push({id:o,why:"its severity follows the organisation's documentation duty (doc_duty in the planning policy) \u2014 set it there"});continue}if(!ro(o)){r.push({id:o,why:"not a detector this version knows \u2014 ignored, so the run is no milder for it"});continue}n[o]=i}return{settings:n,ignored:r}}a(hU,"parseDetectorsSection");var px=10,ii=10,mx=!0;function pc(){return{skip:[],timeoutMinutes:px,commands:{}}}a(pc,"defaultTestsConfig");function si(){return mx?{...pc(),implicit:!0}:null}a(si,"implicitTestsConfig");function $s(e){let t=e.trim().replace(/^\.\//,"").replace(/\/+$/,"");return t===""||t==="."?".":t}a($s,"normalizeTestDir");function gU(e,t){if(e==null)return si();if(e===!0)return pc();if(e===!1)return null;if(typeof e!="object"||Array.isArray(e))return t.push('"tests" must be true, false or an object'),null;let n=e,r=pc(),o=t.length;if(n.skip!==void 0&&(!Array.isArray(n.skip)||n.skip.some(i=>typeof i!="string"||i.trim().length===0)?t.push('"tests.skip" must be an array of package directories'):r.skip=[...new Set(n.skip.map($s))]),n.timeoutMinutes!==void 0){let i=n.timeoutMinutes;typeof i!="number"||!Number.isFinite(i)||i<1||i>120?t.push('"tests.timeoutMinutes" must be a number between 1 and 120'):r.timeoutMinutes=i}if(n.commands!==void 0){let i=n.commands;if(i===null||typeof i!="object"||Array.isArray(i))t.push('"tests.commands" must be an object: package directory \u2192 command');else for(let[s,l]of Object.entries(i)){if(typeof l!="string"||l.trim().length===0){t.push(`"tests.commands" \u2192 "${s}" must be a non-empty command string`);continue}r.commands[$s(s)]=l.trim()}}if(n.inputs!==void 0){let i=n.inputs;if(i===null||typeof i!="object"||Array.isArray(i))t.push('"tests.inputs" must be an object: package directory \u2192 array of path prefixes');else{let s={};for(let[l,c]of Object.entries(i)){if(!Array.isArray(c)||c.length===0||c.some(u=>typeof u!="string"||u.trim().length===0)){t.push(`"tests.inputs" \u2192 "${l}" must be a non-empty array of path prefixes`);continue}s[$s(l)]=[...new Set(c.map(u=>u.trim().replace(/^\.\//,"")))]}Object.keys(s).length>0&&(r.inputs=s)}}if(n.databases!==void 0){let i=n.databases;if(i===null||typeof i!="object"||Array.isArray(i))t.push('"tests.databases" must be an object: package directory \u2192 { "supabase": "<directory that holds supabase/>" }');else{let s={};for(let[l,c]of Object.entries(i)){let u=c,d=u!==null&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u).filter(f=>!f.startsWith("_")):null;if(d===null||d.length!==1||d[0]!=="supabase"||typeof u.supabase!="string"||u.supabase.trim().length===0){t.push(`"tests.databases" \u2192 "${l}" must be { "supabase": "<directory that holds supabase/>" }`);continue}s[$s(l)]={supabase:$s(u.supabase)}}Object.keys(s).length>0&&(r.databases=s)}}for(let i of Object.keys(n))i.startsWith("_")||["skip","timeoutMinutes","commands","inputs","databases"].includes(i)||t.push(`"tests.${i}" is not a known setting (known: skip, timeoutMinutes, commands, inputs, databases)`);return t.length>o?null:r}a(gU,"parseTestsSection");var ur=".maind/gates.d";function dx(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e))return{problem:`${t} must be an object`};let r=e,o=r.id;if(n!==null){if(o!==void 0&&o!==n)return{problem:`${t}: "id" is "${String(o)}", but the file name says "${n}" \u2014 the file name is the id`};o=n}if(typeof o!="string"||o.trim().length===0)return{problem:`${t}.id must be a non-empty string`};let i=r.run;if(typeof i!="string"||i.trim().length===0)return{problem:`${t}.run must be a non-empty command string`};let s=!0;if("blocking"in r&&r.blocking!==void 0&&r.blocking!==null){if(typeof r.blocking!="boolean")return{problem:`${t}.blocking must be a boolean`};s=r.blocking}let l,c=r.when;if(c!=null){if(typeof c!="object"||Array.isArray(c))return{problem:`${t}.when must be an object`};let f=c.paths;if(f!=null){if(!Array.isArray(f)||f.some(p=>typeof p!="string"||p.trim().length===0))return{problem:`${t}.when.paths must be an array of non-empty path prefixes`};l=f}}let u=!1;if("onShip"in r&&r.onShip!==void 0&&r.onShip!==null){if(typeof r.onShip!="boolean")return{problem:`${t}.onShip must be a boolean`};u=r.onShip}let d=!1;if("beforeApproval"in r&&r.beforeApproval!==void 0&&r.beforeApproval!==null){if(typeof r.beforeApproval!="boolean")return{problem:`${t}.beforeApproval must be a boolean`};d=r.beforeApproval}return{id:o,run:i,blocking:s,...l?{paths:l}:{},...u?{onShip:u}:{},...d?{beforeApproval:d}:{}}}a(dx,"parseGateEntry");function ym(e,t=[]){let n=[],r=e===void 0;if(!r&&(e===null||typeof e!="object"||Array.isArray(e)))return{problems:["the manifest must be a JSON object"]};let o=r?{}:e,i=o.gates;if(i===void 0&&t.length===0&&o.tests===void 0&&o.detectors===void 0)return{problems:[`the manifest needs a "gates" array (or one file per gate under ${ur}/)`]};if(i!==void 0&&!Array.isArray(i))return{problems:['"gates" must be an array']};let s=[],l=new Map,c=a((_,w)=>{if("problem"in _){n.push(_.problem);return}let v=l.get(_.id);if(v!==void 0){n.push(`${w}.id "${_.id}" is declared more than once (also ${v})`);return}l.set(_.id,w),s.push(_)},"take");(Array.isArray(i)?i:[]).forEach((_,w)=>c(dx(_,`gates[${w}]`,null),`gates[${w}]`));for(let _ of t){let w=`${ur}/${_.file}`;if(_.parseError!==void 0){n.push(`${w}: not valid JSON: ${_.parseError}`);continue}c(dx(_.raw,w,_.file.replace(/\.json$/,"")),w)}let u=[],d=o.versionedPackages!==void 0,f=o.versionedPackages;if(f!==void 0)if(!Array.isArray(f))n.push('"versionedPackages" must be an array');else{let _=new Set;f.forEach((w,v)=>{let R=`versionedPackages[${v}]`;if(w===null||typeof w!="object"||Array.isArray(w)){n.push(`${R} must be an object`);return}let x=w,O=x.dir;if(typeof O!="string"||O.trim().length===0){n.push(`${R}.dir must be a non-empty path`);return}if(_.has(O)){n.push(`${R}.dir "${O}" is declared more than once`);return}_.add(O);let T=x.mirror;if(T!==void 0&&(typeof T!="string"||T.trim().length===0)){n.push(`${R}.mirror must be a non-empty path relative to dir`);return}let S=x.changelog;if(S!==void 0&&typeof S!="boolean"){n.push(`${R}.changelog must be a boolean`);return}let $=x.numbering;if($!==void 0&&$!=="hand"&&$!=="promote"){n.push(`${R}.numbering must be "hand" or "promote"`);return}let C=x.tag;if(C!==void 0&&(typeof C!="string"||!C.includes("{version}"))){n.push(`${R}.tag must be a template containing {version}, e.g. "my-pkg-v{version}"`);return}if(C!==void 0&&$!=="promote"){n.push(`${R}.tag only applies with numbering "promote" \u2014 promote is what sets it`);return}let I=x.fragments;if(I!==void 0&&(typeof I!="string"||I.trim().length===0)){n.push(`${R}.fragments must be a non-empty path relative to dir`);return}u.push({dir:O.replace(/\/+$/,""),changelog:S??!0,numbering:$??"hand",fragments:typeof I=="string"?I.replace(/\/+$/,""):"changelog.d",...typeof T=="string"?{mirror:T}:{},...typeof C=="string"?{tag:C}:{}})})}let p=!1,m=o.requireWorkObject;m!==void 0&&(typeof m!="boolean"?n.push('"requireWorkObject" must be a boolean'):p=m);let h=!1,b=o.review;b!==void 0&&(typeof b!="boolean"?n.push('"review" must be a boolean'):h=b);let g=gU(o.tests,n),k=hU(o.detectors,n);return n.length>0?{problems:n}:{gates:s,versioned:u,versionedDeclared:d,requireWorkObject:p,review:h,tests:g,detectors:k.settings,detectorsIgnored:k.ignored}}a(ym,"parseGatesManifest");function Ts(e,t){let n=e.file(Ot),r=e.list(ur).filter(s=>s.endsWith(".json")).sort().map(s=>{let l=e.file(`${ur}/${s}`)??"";try{return{file:s,raw:JSON.parse(l)}}catch(c){return{file:s,parseError:c.message}}});if(n===null&&r.length===0)return{kind:"absent",gates:[],versioned:[],versionedDeclared:!1,requireWorkObject:!1,review:!1,tests:si(),detectors:{},detectorsIgnored:[]};let o;if(n!==null)try{o=JSON.parse(n)}catch(s){return{kind:"invalid",path:t,problems:[`not valid JSON: ${s.message}`]}}let i=ym(o,r);return"problems"in i?{kind:"invalid",path:t,problems:i.problems}:{kind:"loaded",gates:i.gates,versioned:i.versioned,versionedDeclared:i.versionedDeclared,requireWorkObject:i.requireWorkObject,review:i.review,tests:i.tests,detectors:i.detectors,detectorsIgnored:i.detectorsIgnored,path:t}}a(Ts,"readGatesManifest");function Xt(e,t){let n=`${e.dir.replace(/\/+$/,"")}/`,r=new Set([`${n}package.json`]);return e.mirror&&r.add(`${n}${e.mirror}`),t.some(o=>o.startsWith(n)&&!o.endsWith(".md")&&!r.has(o))}a(Xt,"versionClaimApplies");function dr(e,t){let n=`${e.dir.replace(/\/+$/,"")}/${e.fragments}/`;if(!t.startsWith(n))return!1;let r=t.slice(n.length);return!r.includes("/")&&/\.md$/i.test(r)&&!/^readme\.md$/i.test(r)}a(dr,"isFragmentPath");var jn={gates:"https://maind.dev/schemas/gates.schema.json",gateFile:"https://maind.dev/schemas/gate-file.schema.json",specContracts:"https://maind.dev/schemas/spec-contracts.schema.json",mockupLabels:"https://maind.dev/schemas/mockup-labels.schema.json"},mc="http://json-schema.org/draft-07/schema#",Dn={"^_":{}},hc={type:"string",description:"Pointer to this schema, so an editor validates the file while you type."},Te={type:"string",minLength:1},gx={run:{...Te,description:'Shell command, run in the repository root. Exit code 0 passes, any other fails; output containing the sentence "skipping the gate" reports the gate as NOT CHECKED instead of passed. A branch that changes the command of an existing gate changes what it is measured by: the gate-manifest check reports it as a weakening until the change is on the base branch or someone gives a reason.'},blocking:{type:"boolean",default:!0,description:"Does a failure stop ship and promote? Default true. A non-blocking failure is REPORTED and lets the merge continue."},when:{type:"object",additionalProperties:!1,properties:{paths:{type:"array",items:Te,description:"Repository-relative path PREFIXES, not globs. The gate runs only when the diff touches one of them; without `when`, it always runs."}}},onShip:{type:"boolean",default:!1,description:"Also run before `maind feature ship` pushes. For cheap gates only (seconds)."},beforeApproval:{type:"boolean",default:!1,description:"Run after the push and before the merge approval is asked; a red result means the approval is not asked. For cheap gates that turn red with time (deadlines, pins)."}},yU=Object.keys(ar).filter(e=>e!=="det_doc_decision"),bU={$schema:mc,$id:jn.gates,title:".maind/gates.json",description:'What this repository declares for `maind gate`, `maind feature ship` and `maind feature promote`. The built-in checks run without this file; it adds the repository\'s own gates and settings. A missing file is fine, a broken one refuses to run \u2014 an empty gate list would look like "all green".',type:"object",additionalProperties:!1,patternProperties:Dn,properties:{$schema:hc,gates:{type:"array",description:"This repository's own gates, run in order. Each gate can also live in its own file `.maind/gates.d/<id>.json` (the file name is the id) \u2014 then two branches that each add a gate never edit the same file.",items:{type:"object",additionalProperties:!1,required:["id","run"],patternProperties:Dn,properties:{id:{...Te,description:"Unique name of the gate; it appears in every result line."},...gx}}},tests:{description:"The built-in test gate: the test script of every package the diff affects (and of the packages that depend on it). On by default; `false` turns it off, an object tunes it.",oneOf:[{type:"boolean"},{type:"object",additionalProperties:!1,patternProperties:Dn,properties:{skip:{type:"array",items:Te,description:"Package directories whose suite does not run."},timeoutMinutes:{type:"number",minimum:1,maximum:120,default:10,description:"Time limit per suite."},commands:{type:"object",additionalProperties:Te,description:"Package directory \u2192 command, run in that directory. The way to test packages that are not JS/TS."},inputs:{type:"object",additionalProperties:{type:"array",minItems:1,items:Te},description:"Package directory \u2192 path prefixes the suite reads outside its package and its dependencies. A change there makes the suite affected."},databases:{type:"object",additionalProperties:{type:"object",additionalProperties:!1,required:["supabase"],patternProperties:Dn,properties:{supabase:{...Te,description:"The directory that holds `supabase/` with its migrations (`.` for the repository root)."}}},description:"Package directory \u2192 the clean database its suite needs. The gate starts a throwaway database for the run, applies the migrations of the tree it judges (base plus branch), hands the suite the connection as DATABASE_URL and PG* variables, and removes it afterwards. Never the database you develop against. Needs Docker and the Supabase CLI; without them the suite is NOT CHECKED, with the reason."}}}]},detectors:{type:"object",description:"The severity of a built-in detector in this repository: block, warn (reported, does not stop the merge) or off (NOT CHECKED, with the number of findings it would have reported). Replaces the catalog default, never a review verdict \u2014 where the server judged the findings, the organisation's policy decides. A branch that makes a detector milder weakens its own gates and is reported by the gate-manifest check. det_doc_decision follows the organisation's doc_duty and cannot be set here.",patternProperties:Dn,propertyNames:{anyOf:[{enum:yU},{pattern:"^_"}]},additionalProperties:{enum:["block","warn","off"]}},requireWorkObject:{type:"boolean",default:!1,description:"Every branch must be bound to a work object of maind planning. Off by default \u2014 a repository without maind planning is never blocked."},review:{type:"boolean",default:!1,description:"Run the review against the repository's conventions as a gate. It calls the maind server and needs the Team plan, so it is off by default."},versionedPackages:{type:"array",description:`Packages whose version number is assigned deliberately. A change to a package's code needs a number greater than the base's, or \u2014 with numbering "promote" \u2014 a changelog fragment, and promote assigns the number right before the merge.`,items:{type:"object",additionalProperties:!1,required:["dir"],patternProperties:Dn,properties:{dir:{...Te,description:"Repository-relative package directory."},mirror:{...Te,description:"A second file (relative to dir) that carries the same number, e.g. src/version.ts."},changelog:{type:"boolean",default:!0,description:"Does the package keep a CHANGELOG.md that must name the number?"},numbering:{enum:["hand","promote"],default:"hand",description:"Who assigns the number: the branch (hand) or `maind feature promote` right before the merge (promote)."},tag:{type:"string",pattern:"\\{version\\}",description:'Tag template promote sets after the merge, e.g. "my-cli-v{version}". Only with numbering "promote".'},fragments:{...Te,default:"changelog.d",description:"Directory of changelog fragments, relative to dir."}}}}}},kU={$schema:mc,$id:jn.gateFile,title:".maind/gates.d/<id>.json",description:"One declared gate in a file of its own. The file name is the gate's id; an `id` field, if present, must match it.",type:"object",additionalProperties:!1,required:["run"],patternProperties:Dn,properties:{$schema:hc,id:Te,...gx}},hx={type:"array",items:Te,uniqueItems:!0},_U={$schema:mc,$id:jn.specContracts,title:".maind/spec-contracts.json",description:"Pairs of a NORMATIVE LIST and its IMPLEMENTATION that det_spec_drift compares \u2014 a design artefact against a navigation registry, an API spec against a router, a permission matrix against middleware. A contract declares EXTRACTION, NOT CONTENT: where the entries stand and how to read them, never which entries there should be. Without this file the detector abstains.",type:"object",additionalProperties:!1,patternProperties:Dn,required:["contracts"],properties:{$schema:hc,contracts:{type:"array",minItems:1,description:"All contracts. An empty list is not a green state \u2014 the detector abstains.",items:{$ref:"#/definitions/contract"}}},definitions:{contract:{type:"object",additionalProperties:!1,required:["id","reason","spec","impl"],properties:{id:{type:"string",pattern:"^[a-z0-9][a-z0-9-]*$",description:"Stable kebab-case id. It is part of every finding id (spec.drift:<id>#\u2026), so renaming it changes the output."},reason:{...Te,description:"Why this pair is guarded \u2014 ideally the incident that made it necessary. Without it nobody can tell in a year whether the contract still applies."},spec:{$ref:"#/definitions/recordSource",description:"The NORMATIVE side. Where the two disagree, it wins."},impl:{$ref:"#/definitions/recordSource",description:"The IMPLEMENTING side."},compare_fields:{...hx,description:"Fields the `fields` dimension compares. Omitted: membership and order only. Each field must be declared on both sides."},grounding:{$ref:"#/definitions/pathExists"},exceptions:{type:"array",items:{$ref:"#/definitions/exception"},description:"Deliberate, explained deviations. They are reported as info and stay visible."},assertions:{type:"array",items:{$ref:"#/definitions/proseAssertion"}}}},recordSource:{oneOf:[{$ref:"#/definitions/objectArray"},{$ref:"#/definitions/nestedLiteralList"}]},objectArray:{type:"object",additionalProperties:!1,required:["extractor","path","symbol","key_field"],description:"`const X = [{\u2026}, {\u2026}]` in a .ts/.tsx/.js/.mjs file or a <script> block. Read as TEXT, never evaluated. Fields that are not strings are ignored.",properties:{extractor:{const:"object-array"},path:{...Te,description:"Repository-relative path. An unreadable path is reported as contract.unreadable \u2014 a pointer error, not drift."},symbol:{...Te,description:"Name of the constant \u2014 the anchor of the contract. Renaming it without updating the manifest is reported as contract.unreadable."},key_field:{...Te,description:"The field that carries identity across both sides, e.g. href. An entry without it makes the contract partial; it does not vanish."},fields:{...hx,description:"Fields taken into each record. Omitted: all string fields."},partition_by:{type:"array",items:Te,description:"Fields whose values form the order partitions; order is compared within a partition. Omitted: one flat partition."}}},nestedLiteralList:{type:"object",additionalProperties:!1,required:["extractor","path","symbol","levels","key_field"],description:"A nested literal whose LEVELS are declared here. Fields accumulate inwards \u2014 the outer level contributes e.g. the area, the middle one the group, the leaf the label and target. Only leaves become records.",properties:{extractor:{const:"nested-literal-list"},path:{$ref:"#/definitions/objectArray/properties/path"},symbol:{$ref:"#/definitions/objectArray/properties/symbol"},key_field:{$ref:"#/definitions/objectArray/properties/key_field"},fields:{$ref:"#/definitions/objectArray/properties/fields"},partition_by:{$ref:"#/definitions/objectArray/properties/partition_by"},levels:{type:"array",minItems:1,items:{$ref:"#/definitions/level"},description:"Outer to inner. The LAST level is the leaf and yields the records."}}},level:{type:"object",additionalProperties:!1,required:["name","shape"],properties:{name:{...Te,description:"For readability only \u2014 the extractor works by position."},shape:{enum:["object","tuple"],description:"object: { id: '\u2026' }, fields by name. tuple: ['Label', '/target'], fields by position."},fields:{type:"object",additionalProperties:{oneOf:[Te,{type:"integer",minimum:0}]},description:"Output field name \u2192 source field name (object) or tuple index (tuple)."},children:{oneOf:[Te,{type:"integer",minimum:0}],description:"Where the child list stands: field name (object) or tuple index (tuple). Omit on the leaf level."}}},pathExists:{type:"object",additionalProperties:!1,required:["extractor","templates"],description:"Grounding: is there an artefact behind each key? Checked against TRACKED files, so build output cannot ground a key.",properties:{extractor:{const:"path-exists"},templates:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:"\\{key\\}"},description:"Repository-relative templates with exactly one {key}. Several mean OR (e.g. page.tsx or page.ts)."},strip_prefix:{...Te,description:"Cut from the front of the key before it is inserted, e.g. /."}}},exception:{type:"object",additionalProperties:!1,required:["dimension","key","reason"],properties:{dimension:{enum:["coverage","fields","order","extra","unrealized"],description:"The five comparison dimensions are closed; extend with new contracts, not new dimensions."},key:{...Te,description:"The record key; for fields: <key>.<field>."},reason:{...Te,description:"Why the deviation is right \u2014 so it can be removed once it no longer is."}}},proseAssertion:{type:"object",additionalProperties:!1,required:["path","prefix","counts","reason"],description:'A counted number in a prose document, e.g. "NAV_ITEMS (41)". Always a warning, never blocking. The expected number is DERIVED from one side, never written here.',properties:{path:Te,prefix:{...Te,description:"Literal text right BEFORE the number. Not a regular expression."},counts:{enum:["spec","impl"],description:"Which side supplies the expected number."},reason:Te}}}},wU={$schema:mc,$id:jn.mockupLabels,title:".maind/mockup-labels.json",description:"Sets of product mockups \u2014 a product tour, a demo, a screenshot rebuilt in code \u2014 whose labels det_mockup_label_drift holds against the product source. Each label is PINNED to the file that renders it, and the pin is checked both ways: the source still contains the label, and some mockup still shows it. Without this file the detector abstains.",type:"object",additionalProperties:!1,patternProperties:Dn,required:["sets"],properties:{$schema:hc,sets:{type:"array",minItems:1,description:"All sets. An empty list is not a green state \u2014 the detector abstains.",items:{$ref:"#/definitions/set"}}},definitions:{set:{type:"object",additionalProperties:!1,required:["id","reason","mockups"],oneOf:[{required:["pins_file"]},{required:["pins"]}],properties:{id:{type:"string",pattern:"^[a-z0-9][a-z0-9._-]*$",description:"Stable id; part of every finding."},reason:{...Te,description:"Why these mockups are pinned \u2014 the occasion, not the mechanics."},pins_file:{...Te,description:'Repository-relative JSON file with the pins: {"pins": [{"label", "source"}]} or a bare array.'},pins:{type:"array",items:{$ref:"#/definitions/pin"},description:"Pins inline, for small sets."},source_root:{...Te,description:"Repository-relative directory each pin's source is resolved against. Default: the repository root."},mockups:{type:"array",minItems:1,items:Te,description:"Repository-relative path prefixes of the mockups: a directory (ending in /) or a file. Tests and the pins file never count as mockups."},extensions:{type:"array",items:{type:"string",pattern:"^\\.[A-Za-z0-9]+$"},description:"File extensions read as mockups. Default: .ts .tsx .js .jsx .mjs .cjs .json .md .mdx .html .vue .svelte .astro."}}},pin:{type:"object",additionalProperties:!1,required:["label","source"],properties:{label:{...Te,description:"The text as the product renders it and the mockup shows it. Whitespace runs collapse on both sides."},source:{...Te,description:"The file that renders the label in the product, relative to source_root."}}}}};var vU={gates:{$schema:jn.gates,gates:[{id:"lint",run:"npm run lint",when:{paths:["src/"]}}],tests:{commands:{api:"pytest"}},detectors:{det_theme_class_drift:"warn"}},gateFile:{$schema:jn.gateFile,run:"node scripts/check-licenses.mjs",when:{paths:["package.json","pnpm-lock.yaml"]}},specContracts:{$schema:jn.specContracts,contracts:[{id:"nav-registry",reason:"Built from a summary once and shipped half the targets.",spec:{extractor:"object-array",path:"design/nav-spec.ts",symbol:"NAV_SPEC",key_field:"href",fields:["label"]},impl:{extractor:"object-array",path:"src/nav/registry.ts",symbol:"NAV_ITEMS",key_field:"href",fields:["label"]},compare_fields:["label"],grounding:{extractor:"path-exists",templates:["src/app/{key}/page.tsx"],strip_prefix:"/"}}]},mockupLabels:{$schema:jn.mockupLabels,sets:[{id:"product-tour",reason:"The tour kept a renamed sidebar item for weeks.",source_root:"apps/dashboard",pins:[{label:"Work objects",source:"src/components/Sidebar.tsx"}],mockups:["apps/website/src/components/tour/"]}]}};var Rx="1";function Ex(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
12
12
  `).slice(0,1e3)}a(Ex,"nodeEmbedText");var bm=["function","method","class","interface","enum","type_alias"];function Ax(e,t){let n=Math.min(e.length,t.length),r=0,o=0,i=0;for(let s=0;s<n;s++){let l=e[s],c=t[s];r+=l*c,o+=l*l,i+=c*c}return o===0||i===0?0:r/(Math.sqrt(o)*Math.sqrt(i))}a(Ax,"cosineSimilarity");import{execFileSync as xU}from"node:child_process";import{createHash as SU}from"node:crypto";import{readFileSync as RU}from"node:fs";import{posix as Jt}from"node:path";var EU=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;function $x(e){let t=SU("sha256"),n=[];try{n=xU("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
13
13
  `).filter(c=>EU.test(c)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,o=a(c=>{if(r.has(c))return r.get(c);try{let u=RU(Jt.join(e,c),"utf8");return r.set(c,u),u}catch{return null}},"read"),i=[],s=new Map;for(let c of n.filter(u=>!u.endsWith("package.json"))){let u=Tx(c,o,0),d=Jt.dirname(c)==="."?"":Jt.dirname(c);c.endsWith("tsconfig.json")&&s.set(d,u),u.paths&&i.push({dir:u.pathsDir??d,baseUrl:u.baseUrl,paths:u.paths})}let l=[];for(let c of n.filter(u=>u.endsWith("package.json"))){let u=Cx(o(c));if(!u||typeof u.name!="string")continue;let d=Jt.dirname(c)==="."?"":Jt.dirname(c),f=s.get(d);l.push({name:u.name,dir:d,exports:u.exports,main:typeof u.main=="string"?u.main:void 0,module:typeof u.module=="string"?u.module:void 0,types:typeof u.types=="string"?u.types:void 0,outDir:f?.outDir,rootDir:f?.rootDir})}for(let c of[...r.keys()].sort())t.update(c).update("\0").update(r.get(c)).update("\0");return{config:{packages:l,tsconfigs:i},fingerprint:t.digest("hex")}}a($x,"loadModuleConfig");function Tx(e,t,n){let r=Cx(t(e));if(!r)return{};let o=Jt.dirname(e)==="."?"":Jt.dirname(e),i={},s=r.extends;if(typeof s=="string"&&s.startsWith(".")&&n<4){let u=Jt.normalize(Jt.join(o,s.endsWith(".json")?s:s+".json"));i=Tx(u,t,n+1)}let l=r.compilerOptions??{},c={...i};return typeof l.outDir=="string"&&(c.outDir=Jt.normalize(l.outDir)),typeof l.rootDir=="string"&&(c.rootDir=Jt.normalize(l.rootDir)),l.paths&&typeof l.paths=="object"&&(c.paths=l.paths,c.pathsDir=o,c.baseUrl=typeof l.baseUrl=="string"?l.baseUrl:void 0),c}a(Tx,"compilerFacts");function Cx(e){if(e===null)return null;let t="",n=!1;for(let r=0;r<e.length;r++){let o=e[r];if(n){t+=o,o==="\\"?t+=e[++r]??"":o==='"'&&(n=!1);continue}if(o==='"')n=!0,t+=o;else if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
14
14
  `;)r++;t+=`
@@ -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(n$,"renderDryRun");import{createRequire as RV}from"node:module";function EV(){return"0.172.1";try{return RV(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a(EV,"resolveVersion");var ce=EV();var DV=5e3;function xt(e){process.stderr.write(`maind: ${e}
271
+ `}}a(n$,"renderDryRun");import{createRequire as RV}from"node:module";function EV(){return"0.173.0";try{return RV(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}a(EV,"resolveVersion");var ce=EV();var DV=5e3;function xt(e){process.stderr.write(`maind: ${e}
272
272
  `)}a(xt,"err");function jV(e){return e instanceof Error?e.message:String(e)}a(jV,"msg");var PV=new Set(["--config","--route","--mcp-url"]);function o$(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("-")){PV.has(i)&&o++;continue}r=i;break}return{agent:r,dryRun:n("--dry-run"),config:t("--config")??null,route:t("--route")??GA,direct:n("--direct"),noFallback:n("--no-fallback"),noInstall:n("--no-install"),json:n("--json"),mcpUrl:t("--mcp-url")??null}}a(o$,"parseLaunchArgs");var LV={probe(e,t){let n=r$(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 r$("uv",[...e],{stdio:["ignore","inherit","inherit"]}).status},spawnInteractive(e){let t=Date.now();return new Promise(n=>{let r=!1,o=AV(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 je)return null;throw r}try{let r=new Ne({apiKey:n.apiKey,deviceId:n.deviceId,clientVersion:ce,mcpUrl:e??void 0,projectKey:t}),o=new Promise(s=>{setTimeout(()=>s(null),DV).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=MV(e);n&&n!=="."&&CV(n,{recursive:!0}),IV(e,t,"utf8")},readFile(e){try{return OV(e,"utf8")}catch{return null}},fileExists(e){return TV(e)},repoRoot(){try{let e=$V("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return e.length>0?e:null}catch{return null}},projectKey(){return lt().projectKey},userConfigDir(){return Yo()},homeDir(){return NV()},env:process.env,platform:process.platform};function FV(e,t){return e!==null?ty(e,".maind",Vg):ty(t,Vg)}a(FV,"resolveRoutesPath");async function i$(e,t=LV){let n=WA(e.agent);if(n.kind==="unknown")return xt(`usage: maind launch <agent> [--dry-run] [--config <path>] [--route <name>] [--direct] [--no-fallback] [--no-install] \u2014 supported: ${Yg.join(", ")}`),2;if(n.kind==="planned")return xt(`agent '${n.agent}' is planned but not yet supported \u2014 v1 supports: ${Yg.join(", ")}.`),2;if(e.json&&!e.dryRun)return xt("--json is only valid together with --dry-run (stdout belongs to the agent session)."),2;let r=n.agent;if(e.direct)return xt(t$()),s$(t,Zg(r));let o=qA(t.env);o.warning!==null&&xt(o.warning);let i,s,l;if(e.config!==null){if(!t.fileExists(e.config))return xt(`config not found: ${e.config}`),2;let f=t.readFile(e.config);if(f===null||zA(f,e.route)===null)return xt(`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:YA(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)`;xt(`using builtin routing policy (${m}).`)}i=FV(t.repoRoot(),t.userConfigDir())}let c=Mu,u=t.probe(Mu,["--version"]).ok;if(e.dryRun){let f={agent:r,configPath:i,configSource:l,toml:s,argv:Jg(c,r,e.route,i),backendKind:o.kind,switchyardDetected:u},p=n$(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 xt(`switchyard not found (--no-install). Install it with:
273
273
  maind: ${Du}`),1;if(!t.probe("uv",["--version"]).ok)return xt(ZA()),1;if(xt(JA()),t.install(HA),t.probe(Mu,["--version"]).ok)u=!0;else{let f=ty(t.homeDir(),".local","bin",t.platform==="win32"?"switchyard.exe":"switchyard");t.probe(f,["--version"]).ok&&(c=f,u=!0)}if(!u)return ey(t,e,r,QA())}if(l!=="flag"&&s!==null)try{t.writeConfig(i,s)}catch(f){return xt(`could not write ${i}: ${jV(f)}`),1}let d=await t.spawnInteractive(Jg(c,r,e.route,i));return d.spawnError!==null?ey(t,e,r,`could not start switchyard (${d.spawnError})`):XA(d.code,d.signal,d.elapsedMs)==="fallback-eligible"?ey(t,e,r,`switchyard exited with code ${d.code} after ${(d.elapsedMs/1e3).toFixed(1)}s`):Qg(d.code,d.signal)}a(i$,"runLaunch");async function ey(e,t,n,r){return t.noFallback?(xt(`${r} (--no-fallback set \u2014 not degrading to a direct spawn).`),1):(process.stderr.write(e$(r)+`
274
274
  `),s$(e,Zg(n)))}a(ey,"degradeOrFail");async function s$(e,t){let n=await e.spawnInteractive(t);return n.spawnError!==null?(xt(`'${t[0]}' not found on PATH \u2014 install the agent CLI first (${n.spawnError}).`),1):Qg(n.code,n.signal)}a(s$,"spawnAndPropagate");var ny="tests:";function ju(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(ju,"parseOverride");function BV(e){return e==="open"||e==="warn"}a(BV,"objectCarriesOverride");async function Pu(e,t,n){let r=[];for(let i of e)!t.has(i.gate)&&!i.gate.startsWith(ny)&&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`):BV(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(Pu,"checkOverrides");function a$(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(a$,"applyOverrides");function l$(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(l$,"unusedOverrideLines");var Lu=["squash","merge","rebase"];function Fu(e){return typeof e=="string"&&Lu.includes(e)}a(Fu,"isMergeMethod");function c$(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(c$,"githubMergeMethods");function u$(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(u$,"gitlabMergeMethods");function ry(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?Lu.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(ry,"chooseMergeMethod");var UV={squash:"squash",merge:"merge commit",rebase:"rebase"};function xi(e){return UV[e]}a(xi,"methodLabel");function oy(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 ${xi(e.method)} (${t[e.source]})`}a(oy,"methodLine");function iy(e){let t=e.source==="flag"?"--merge-method":"mergeMethod in .maind/feature.json",n=e.allowed.length>0?e.allowed.map(xi).join(", "):"none";return[`${t} asks for ${xi(e.method)}, and this repository's forge does not allow it (allowed: ${n}).`,"Nothing ran and nothing was merged."]}a(iy,"notAllowedLines");function Bu(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(Bu,"rebaseMergeCommitLines");import{readFileSync as M$}from"node:fs";import{join as D$}from"node:path";import{spawn as HV,spawnSync as GV}from"node:child_process";function sy(e){return e==="work"||e==="always"||e==="off"}a(sy,"isStayAwakeSetting");function KV(e,t){if(e.CI||e.NODE_TEST_CONTEXT)return"off";let n=e.MAIND_STAY_AWAKE?.trim().toLowerCase();return sy(n)?n:t??"work"}a(KV,"resolveStayAwake");function WV(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(WV,"inhibitCommand");function qV(e,t,n){let r=null,o=a(()=>{if(e==="off"||r!==null)return;let s=WV(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(qV,"makeAwake");function VV(e){try{return GV("sh",["-c",`command -v ${e}`],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}a(VV,"hasBinary");var YV={platform:process.platform,pid:process.pid,has:VV,start:a((e,t)=>{try{let n=HV(e,[...t],{stdio:"ignore"});return n.on("error",()=>{}),n.unref(),typeof n.pid=="number"?()=>n.kill():null}catch{return null}},"start")},vo=null;function Uu(e,t,n={}){let r=vo===null;return r&&(vo=qV(KV(n.env??process.env,e),t,n.deps??YV)),vo.work(),{end:a(()=>{r&&(vo?.end(),vo=null)},"end")}}a(Uu,"beginAwake");function d$(){vo?.work()}a(d$,"awakeWork");function f$(){vo?.waiting()}a(f$,"awakeWaiting");import{execFileSync as tY}from"node:child_process";import{realpathSync as nY}from"node:fs";function Hu(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(Hu,"serverPlanAnswer");var _a="MAIND_GATE_OBJECT_REASON",zV=/^[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 XV(e){if(e===null)return!1;let t=e.trim();return t.length<4?!1:!["1","true","yes","on","skip"].includes(t.toLowerCase())}a(XV,"isReason");function Gu(e){let t=JV(e);return t.kind!=="linked"&&XV(e.overrideReason)?{kind:"overridden",reason:e.overrideReason.trim()}:t}a(Gu,"classifyWorkObject");function JV(e){if(e.branch===null)return{kind:"detached"};let t=e.objectId?.trim()??"";return t.length===0?{kind:"missing",branch:e.branch}:zV.test(t)?{kind:"linked",objectId:t,objectKey:e.objectKey?.trim()||null,planRevision:e.planRevision?.trim()||null}:{kind:"malformed",branch:e.branch,value:t}}a(JV,"judge");function Ku(e){return e.kind==="linked"||e.kind==="overridden"}a(Ku,"workObjectPasses");function p$(e,t,n){let r=a(o=>[" Link it, or say why not:",` git config branch.${o}.maindObject <object-uuid>`,` ${t}="<reason>" maind gate`],"fix");switch(e.kind){case"linked":{let o=`work object: ${e.objectKey?`${e.objectKey} \u2014 `:""}${e.objectId}`;if(e.planRevision)return[o,` plan attached (rev ${e.planRevision})`];let i=` maind object plan --object ${e.objectId} --file <plan.md>`,s=n??{kind:"unchecked",reason:"the server was not asked"};switch(s.kind){case"attached":return[o," plan attached (server)"];case"absent":return[o," no plan attached \u2014 advisory, never a failure. Attach the accepted plan:",i];case"unchecked":return[o,` plan not checked (${s.reason}) \u2014 no local marker; advisory, never a failure. If none is attached:`,i]}}case"overridden":return[`work object check overridden \u2014 reason: ${e.reason}`];case"missing":return[`branch ${e.branch} has no linked work object.`,...r(e.branch)];case"malformed":return[`branch ${e.branch}: "${e.value}" is not an object id.`," The check reads the id, never the display key \u2014 a key can be renamed, an id cannot.",...r(e.branch)];case"detached":return["detached HEAD \u2014 this check needs a branch to read the link from."]}}a(p$,"workObjectLines");function ay(e){return`${e.dir}\0${e.check??""}`}a(ay,"checkKey");function m$(e){return`${e.replace(/[/\\]+$/,"")}-apply`}a(m$,"applyCheckoutPath");function h$(e){return[...new Set(e.filter(t=>t.command!==null).map(t=>t.trigger))].sort()}a(h$,"applyTriggers");function it(e){return/^[A-Za-z0-9_./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}a(it,"shellQuote");function ZV(e,t){let n=t.replace(/^\/+|\/+$/g,"");return n.length===0?e:`${e.replace(/\/+$/,"")}/${n}`}a(ZV,"joinAbs");function QV(e){return e.endsWith("/")?e:`${e}/`}a(QV,"withPrefix");function eY(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(eY,"defaultPostMergeSteps");function ly(e,t,n){let r=e.map(s=>s.trim()).filter(s=>s.length>0),o=t??eY(r),i=[];for(let s of o){let l=QV(s.when),c=r.filter(h=>h.startsWith(l));if(c.length===0)continue;let u=ZV(n,s.cwd??""),d=`cd ${it(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),g=f(s.run,h),k=f(s.check,h);i.push({reason:`${l}${h}/ changed`+(b?` \u2014 ${b}`:""),command:g?d+g:null,trigger:l,dir:u,check:g&&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(ly,"postMergeActions");function g$(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 ${it(i)} worktree remove ${it(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(ay(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(g$,"postMergeLines");function wa(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(wa,"decideCompletion");function y$(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(y$,"missingCompletionLines");function cy(e){if(!e.required)return null;let t=Gu({branch:e.branch,objectId:e.boundObject,objectKey:null,overrideReason:e.overrideReason,planRevision:null});return Ku(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: ${Si}="<reason>" ${e.promoteCommand} --yes`,"Nothing was merged."]}a(cy,"unboundObjectLines");var Si=_a;function Gn(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)}a(Gn,"cwdInside");function St(e,t){return`cd ${it(e)} && ${t}`}a(St,"cleanupCommand");function b$(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(b$,"alreadyMergedLines");function k$(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(k$,"doneInsideLines");function _$(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(_$,"deferredCleanupLines");function w$(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:`,` ${St(e.mainRoot,e.doneCommand)}`,` or, later, for every merged worktree at once: ${St(e.mainRoot,"maind feature done --merged")}`]}a(w$,"keptWorktreeLines");async function uy(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(uy,"recoverBinding");async function va(e,t){let n=t.prNumber(),r=t.slug();if(n===null||r===null)return{kind:"no-pr"};let o=t.ref(r,n),i=null;try{i=await t.lookup(o)}catch{i=null}if(i!==null)return i.id===e?{kind:"already",ref:o}:{kind:"mismatch",ref:o,other:i};await t.link(e,o);let s=null;try{s=await t.lookup(o)}catch{s=null}return s!==null&&s.id!==e?{kind:"mismatch",ref:o,other:s}:{kind:"link-attempted",ref:o}}a(va,"ensurePrLinked");function Ri(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(Ri,"linkMismatchLines");function v$(e,t){let n=t?.trim().toUpperCase()??null;return e.filter(r=>r.toUpperCase()!==n)}a(v$,"fanOutKeys");function x$(e,t){let n=it(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 (${Xc(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:[` ${Xc(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(x$,"fastForwardLines");function rY(e){let t=[],n=null,r="";for(let o of e.split(`
@@ -419,7 +419,7 @@ Fallback: run the MCP calls from an agent session (work_object_create/link_ref/r
419
419
  `).filter(b=>b&&dr(r,b)).sort(),p=[];for(let b of f){if(Vn(e,n,b)!==null)return`the fragment ${b} was not consumed`;let g=ud(Vn(e,t,b)??"");if("problem"in g)return`${b}: ${g.problem}`;p.push(g.body),i.add(b)}let m=`${s}/CHANGELOG.md`,h=tC(Vn(e,t,m),Vn(e,n,m),o,p,r.changelog);return h!==null?h:(r.changelog&&i.add(m),null)}a(oX,"checkPackage");function iX(e,t,n,r){let{repo:o,baseRef:i,rules:s}=e,l=(Be(o,["-c","core.quotepath=off","diff","--name-only",`${i}...${t}`])??"").split(`
420
420
  `).filter(Boolean),c=s.regenerate.filter(f=>l.some(p=>p.startsWith(f.when)));if(c.length===0)return`changes ${r[0]} outside the release files, and no regenerate step applies`;let u=rO(Ga(iO(),"maind-carry-")),d=Ga(u,"wt");try{if(Be(o,["worktree","add","--detach","--quiet",d,t])===null)return"could not check out the parent to reproduce the derived files";let f=nO(d,c);if(f!==null&&s.postCreate.length>0){e.note(`installing a scratch tree to reproduce the derived files (${f} failed without it)`);for(let h of s.postCreate)if($d("sh",["-c",h],{cwd:d,encoding:"utf8",timeout:6e5}).status!==0)return`not reproducible here: the install it needs failed (${h})`;if(Be(d,["reset","--hard","--quiet"]),Be(d,["clean","-fd","--quiet"]),f=nO(d,c),f!==null)return`the regenerate step failed while reproducing it, also after the install: ${f}`}if(f!==null)return`the regenerate step failed while reproducing it: ${f}`;let p=(Be(d,["-c","core.quotepath=off","status","--porcelain=v1","-z","--untracked-files=all"])??"").split("\0").filter(h=>h.length>3).map(h=>h.slice(3)),m=new Set(r);if(p.length!==m.size||p.some(h=>!m.has(h)))return"the derived files differ from what the regenerate steps produce";for(let h of r){let b=Vn(o,n,h),g;try{g=Y4(Ga(d,h),"utf8")}catch{g=null}if(b!==g)return`${h} differs from what the regenerate steps produce`}return null}finally{Be(o,["worktree","remove","--force",d]),Be(o,["worktree","prune"]),oO(u,{recursive:!0,force:!0})}}a(iX,"reproduceRegenerate");function nO(e,t){for(let n of t)if($d("sh",["-c",n.run],{cwd:e,encoding:"utf8",timeout:3e5}).status!==0)return n.run;return null}a(nO,"runSteps");import{execFileSync as sX}from"node:child_process";function Va(e,t){try{return sX("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}a(Va,"sh");function _b(e){let{wt:t,root:n,branch:r,baseRef:o,packages:i,regenerate:s,method:l,utcTodayIso:c,phase:u,note:d}=e,f=u==="merge",p=Va(t,["rev-parse","HEAD"]),m=i.length>0||s.length>0,h=null;if(m){let _=kd(t,o,i,c);if(_.kind==="keep"){if(qn(n,o,r).kind==="conflict")f&&d(`the release commit of an earlier run (${_.sha.slice(0,9)}) conflicts with ${o} \u2014 withdrawing it.`);else if(h={sha:_.sha,releases:_.releases},f){let w=_.releases.map(v=>`${v.name} ${v.to}`).join(", ");d(`kept the release commit of an earlier run (${_.sha.slice(0,9)})`+(w?` \u2014 ${w} ${_.releases.length===1?"is":"are"} still free on ${o}.`:"."))}}else _.kind==="withdraw"&&f&&d(`the release commit of an earlier run (${_.sha.slice(0,9)}) cannot stay: ${_.why}.`)}if(m&&h===null){let _=aC(t,o);if(_.kind==="failed")return{kind:"stop",reason:"release_failed",lines:[_.reason]};_.kind==="withdrawn"&&f&&d(`withdrew the release commit of an earlier promote run (${_.sha.slice(0,9)}) \u2014 the number is assigned anew.`)}let b=Io(n,o,{verdict:qn(n,o,r),ownOnly:[]}).verdict;if(b.kind==="conflict")return{kind:"stop",reason:"base_conflict",lines:[`${r} ${nn(b,o)}`]};let g={kind:"none"};if(m){if(g=lC({wt:t,baseRef:o,packages:[...i],regenerate:[...s],utcTodayIso:c,...h?{kept:h}:{}}),g.kind==="failed")return{kind:"stop",reason:"release_failed",lines:[g.reason,...(g.lines??[]).filter(Boolean)]};if(g.kind==="released"&&f){for(let _ of g.releases){let w=h?.releases.some(v=>v.dir===_.dir)??!1;d(`release: ${_.dir} ${_.from} \u2192 ${_.to} (${_.level}${w?", kept":""})${_.tag?`, tag ${_.tag} after the merge`:""}.`)}g.kept&&!g.moved&&d("nothing to add \u2014 the pull request head stays where it was approved.");for(let _ of g.regenerated)d(`regenerated: ${_}`);for(let _ of g.handBumped)d(`${_}: bumped on the branch by hand \u2014 the gate judges that number as before.`)}}if(l==="rebase"){let _=(Va(t,["rev-list","--merges",`${o}..HEAD`])??"").split(`
421
421
  `).filter(Boolean);if(_.length>0){let w=p!==null&&(Va(t,["rev-list","--merges",`${p}..HEAD`])??"").length>0;return{kind:"stop",reason:"rebase_merge_commit",lines:Bu({branch:r,baseRef:o,merges:_,ownBaseMerge:w})}}}let k=dC(t,o);if(k.kind==="failed")return{kind:"stop",reason:"base_conflict",lines:[k.reason]};if(!f){let _=Va(t,["rev-parse","--short=9",o])??"?",v=[k.kind==="merged"||(Va(t,["rev-list","--merges",`${p??"HEAD"}..HEAD`])??"").length>0?`${o} at ${_} merged in`:`${o} at ${_} already in the branch`];g.kind==="released"&&g.releases.length>0&&v.push(`release ${g.releases.map(R=>`${R.name} ${R.to}`).join(", ")}`),g.kind==="released"&&g.regenerated.length>0&&v.push("derived files regenerated"),d(`built the merge result locally (${v.join(", ")}) \u2014 the gate checks what would land, not the branch alone.`)}return{kind:"ready",release:g,kept:h,trialFrom:k.kind==="merged"?k.from:null}}a(_b,"buildMergeResult");import{execFileSync as aX,spawnSync as cO}from"node:child_process";import{existsSync as lX,readFileSync as cX,rmSync as uX,writeFileSync as dX}from"node:fs";import{isAbsolute as fX,resolve as pX}from"node:path";var wb="maind-promote-hold.json";function Td(e,t){try{return aX("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:6e4}).trim()}catch{return null}}a(Td,"git");function Cd(e,t){let n=Td(e,["rev-parse","--git-path",t]);return n?fX(n)?n:pX(e,n):null}a(Cd,"gitPath");function vb(e,t,n,r=Date.now()){let o=Cd(e,wb);if(!o||uO(e)!==null)return;let i={v:1,startHead:t,at:new Date(r).toISOString(),by:n};try{dX(o,`${JSON.stringify(i)}
422
- `)}catch{}}a(vb,"beginHold");function Yn(e){let t=Cd(e,wb);if(t)try{uX(t,{force:!0})}catch{}}a(Yn,"endHold");function uO(e){let t=Cd(e,wb);if(!t)return null;try{let n=JSON.parse(cX(t,"utf8")),r=typeof n.startHead=="string"&&/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(n.startHead)?n.startHead:null,o=typeof n.at=="string"?n.at:null,i=n.by==="check"||n.by==="promote"?n.by:null;return n.v!==1||!r||!o||!i?null:{v:1,startHead:r,at:o,by:i}}catch{return null}}a(uO,"readHold");function mX(e,t,n){if(!e||!t||e===t)return{kind:"none"};if(n.links.length===0||n.links[0].sha!==e)return{kind:"foreign"};if(n.stoppedAt.sha===t)return{kind:"own",count:n.links.length,to:t};let r=n.links.findIndex(o=>o.sha===t);return r>0?{kind:"own",count:r,to:t}:{kind:"foreign"}}a(mX,"classifyLeftover");function Ya(e,t,n){let r=uO(e);if(r===null)return{kind:"none"};let o=r.startHead,i=!1,s=Cd(e,"MERGE_HEAD");s!==null&&lX(s)&&(i=cO("git",["merge","--abort"],{cwd:e,encoding:"utf8",timeout:6e4}).status===0);let l=Td(e,["rev-parse","HEAD"]);if(!l||l===o)return l===o&&(Td(e,["status","--porcelain"])??"")!==""?{kind:"uncommitted",by:r.by}:(Yn(e),i?{kind:"recovered",count:0,from:o,to:o,by:r.by,abortedMerge:i}:{kind:"cleared"});if(n!==null&&Td(e,["merge-base","--is-ancestor",l,n])!==null)return Yn(e),{kind:"cleared"};let c=mX(l,o,rn(e,l,t));if(c.kind!=="own")return Yn(e),{kind:"foreign",from:l,to:o};let u=cO("git",["reset","--keep",o],{cwd:e,encoding:"utf8",timeout:6e4});return u.status!==0?{kind:"failed",from:l,to:o,output:`${u.stdout??""}${u.stderr??""}`.trim()}:(Yn(e),{kind:"recovered",count:c.count,from:l,to:o,by:r.by,abortedMerge:i})}a(Ya,"recoverHold");function za(e,t,n){switch(e.kind){case"none":case"cleared":return[];case"recovered":return[`an earlier ${e.by==="check"?"promote --check":"promote"} run was interrupted while it held `+(e.count>0?`${e.count} local commit(s) of its own`:"a half-finished merge of the base")+` \u2014 they were never pushed. ${t} is back at ${e.to.slice(0,9)}.`];case"uncommitted":return[`an earlier ${e.by==="check"?"promote --check":"promote"} run ended while it was writing its own files (a release number, derived files) \u2014 they are in the worktree, not committed.`,`if you changed nothing here since, discard them and run it again: cd ${n} && ${ob}`];case"foreign":return[`an earlier promote run was interrupted at ${e.to.slice(0,9)}, but ${t} has moved on to ${e.from.slice(0,9)} with commits promote did not make \u2014 nothing was touched.`];case"failed":return[`an earlier promote run was interrupted and left local commits, and ${t} could not be moved back to ${e.to.slice(0,9)} (${e.output}).`,`undo them before the next run: cd ${n} && git reset --keep ${e.to}`]}}a(za,"holdRecoveryLines");function dO(e){let t=`${e.base} moved from ${e.from.slice(0,9)} to ${e.to.slice(0,9)}${e.commits?` (${e.commits} commit(s))`:""}`,n="the gate judged the merge result with the earlier base, so what would land now is unchecked",r=[e.when==="after-red-gate"?`${t} while the gate ran, and the gate was red \u2014 its verdict was on a combination that would no longer land (a number the base took meanwhile reads as taken, for one). Nothing was pushed and nothing was merged.`:e.when==="after-gate"?`${t} while the gate ran \u2014 ${n}. Nothing was pushed and nothing was merged.`:e.conflicting?`${t} before the merge, and the pull request now conflicts with it. Nothing was merged.`:`${t} before the merge \u2014 ${n}. Nothing was merged.`];return e.retriesSoFar>=e.maxRetries?(r.push(`${e.base} moved ${e.maxRetries+1} times in a row before the merge \u2014 run promote again when it is quieter.`),{retry:!1,lines:r}):(r.push(`promoting again against ${e.base} as it is now (attempt ${e.retriesSoFar+2} of ${e.maxRetries+1}) \u2014 the approval stands, only the base moved.`+(e.conflicting?" A conflict in promote's own release commit is solved there (the commit is withdrawn and the number assigned anew); a conflict in the branch's own content stops that attempt and names the files.":"")),{retry:!0,lines:r})}a(dO,"movedBasePlan");function fO(e,t,n){return[n?`${e} conflicts with ${t} \u2014 nothing was merged. GitHub reported the conflict only after the merge attempt (${t} moved since the checks ran).`:`${e} conflicts with ${t} \u2014 nothing was merged. GitHub builds no merge ref for a conflicting pull request, so the required checks never start.`,`run promote again: it rebuilds the merge result against ${t} and solves a conflict in its own release commit itself. If the branch's own content conflicts, it names the files \u2014 then merge ${t} into the branch, resolve, push (a pushed commit needs a new approval).`]}a(fO,"conflictLines");import{spawn as hX}from"node:child_process";var gX=a((e,t)=>{try{let n=hX(e,t,{stdio:"ignore"});return{kill:a(()=>void n.kill(),"kill"),unref:a(()=>n.unref(),"unref"),on:a((r,o)=>void n.on(r,o),"on")}}catch{return null}},"realSpawn");function yX(e,t){return e==="darwin"?{cmd:"caffeinate",args:["-i","-w",String(t)]}:e==="linux"?{cmd:"systemd-inhibit",args:["--what=idle:sleep","--who=maind","--why=a gate or merge run is in progress","tail",`--pid=${t}`,"-f","/dev/null"]}:null}a(yX,"awakeCommand");var Od=0,Id=null;function Nd(e=process.platform,t=process.pid,n=gX){let r=!1;if(Od===0){let o=yX(e,t),i=o?n(o.cmd,o.args):null;i&&(i.on("error",()=>{}),i.unref(),Id=a(()=>i.kill(),"stop"))}return Od+=1,()=>{r||(r=!0,Od-=1,Od===0&&Id&&(Id(),Id=null))}}a(Nd,"keepAwake");import{randomUUID as bX}from"node:crypto";var kX=45*6e4,_X=3e4,wX=6e4;function pO(e){if(e.kind==="unknown_tool")return{kind:"unavailable",reason:"this MAIND server has no merge lane yet"};if(e.kind==="invalid_params")return{kind:"unavailable",reason:e.reason};if(e.kind==="failed")return{kind:"unavailable",reason:e.reason};let t=e.body;if(t.ok!==!0)return{kind:"unavailable",reason:typeof t.hint=="string"?t.hint:String(t.error??"the server refused")};let n=t.requeued===!0;if(t.granted===!0)return{kind:"granted",requeued:n};let r=typeof t.position=="number"?t.position:0,o=Array.isArray(t.ahead)?t.ahead.map(i=>{let s=i??{};return{ref:typeof s.ref=="string"?s.ref:null,label:typeof s.label=="string"?s.label:null,own:s.own===!0,inLaneSeconds:typeof s.in_lane_seconds=="number"?s.in_lane_seconds:0}}):[];return r<2?{kind:"unavailable",reason:"the server's answer named no place in the lane"}:{kind:"waiting",position:r,ahead:o,requeued:n}}a(pO,"readLane");function mO(e){let t=Math.floor(e/60);return t<1?"less than a minute":t===1?"1 minute":`${t} minutes`}a(mO,"minutesText");function vX(e,t){let n=e.ahead[0],r=n?`${n.own&&n.label?`your run of ${n.label}`:n.own?"another run of yours":"a teammate's run"}${n.ref?` (${n.ref})`:""}, in the lane for ${mO(n.inLaneSeconds)}`:"another promote run",o=e.position>2?` \u2014 ${e.position-1} runs ahead`:"";return`waiting in the merge lane of ${t} for ${r}${o}. promote builds and gates once it is this run's turn, so the base does not move under it.`}a(vX,"waitingLine");var Md=class{constructor(t,n=bX()){this.deps=t;this.runId=n}static{a(this,"MergeLane")}runId;stopHeartbeat=null;entered=!1;lostSaid=!1;async enter(t){if(this.stopHeartbeat)return{kind:"held",waitedMs:0};let n=this.deps,r=n.now(),o=n.maxWaitMs??kX,i="";for(;;){let s=pO(await n.call({action:"enter",runId:this.runId,...t}));if(s.kind==="unavailable")return this.entered&&await this.leave(),n.note(`the merge lane could not be used (${s.reason}) \u2014 promote runs without it, as before.`),{kind:"without",reason:s.reason};if(this.entered=!0,s.kind==="granted"){let c=n.now()-r;return c>0&&i&&n.note(`this run's turn in the merge lane of ${t.base} \u2014 building the merge result now.`),this.stopHeartbeat=n.every(n.heartbeatMs??wX,()=>{this.beat(t)}),{kind:"held",waitedMs:c}}let l=vX(s,t.base);if(l!==i&&(n.note(l),i=l),n.now()-r>=o){await this.leave();let c=`still not this run's turn after ${mO(Math.round(o/1e3))}`;return n.note(`${c} in the merge lane \u2014 promote goes ahead without it; the base may move while it gates.`),{kind:"without",reason:c}}await n.pause(n.pollMs??_X)}}async beat(t){pO(await this.deps.call({action:"enter",runId:this.runId,base:t.base})).kind==="waiting"&&!this.lostSaid&&(this.lostSaid=!0,this.deps.note("this run lost its turn in the merge lane (it was silent for three minutes) \u2014 it goes on; if the base moves, promote starts again as before."))}async leave(){if(this.stopHeartbeat&&(this.stopHeartbeat(),this.stopHeartbeat=null),!!this.entered){this.entered=!1;try{await this.deps.call({action:"leave",runId:this.runId})}catch{}}}};import{execFileSync as BN,spawnSync as KJ}from"node:child_process";import{existsSync as WJ,readFileSync as qJ}from"node:fs";import{join as Qd}from"node:path";var xX={"migration-first":"push the migration before the code goes live","code-first":"release and deploy the code before you push the migration","any-order":"either order works"};function hO(e){return e.verdict==="declared"&&e.declared!==null?[`note rollout \u2014 ${e.declared.order}: ${xX[e.declared.order]} (${e.declared.reason})`]:e.verdict==="undeclared"?e.findings.map(t=>`note rollout \u2014 ${t.title}`):[]}a(hO,"rolloutRows");function SX(e,t){return t===void 0||t.length===0?!0:e===void 0||e.length===0?!1:e.every(n=>t.some(r=>n===r||n.startsWith(r)))}a(SX,"scopeCovers");function RX(e,t){if(t===null)return[{kind:"manifest-removed",subject:""}];let n=[],r=new Map(t.gates.map(i=>[i.id,i]));for(let i of e.gates){let s=r.get(i.id);if(s===void 0){n.push({kind:"gate-removed",subject:i.id});continue}i.blocking&&!s.blocking&&n.push({kind:"gate-non-blocking",subject:i.id}),SX(i.paths,s.paths)||n.push({kind:"gate-narrowed",subject:i.id})}let o=new Set(t.versionedDirs);for(let i of e.versionedDirs)o.has(i)||n.push({kind:"versioned-removed",subject:i});return e.requireWorkObject&&!t.requireWorkObject&&n.push({kind:"work-object-off",subject:""}),e.review&&!t.review&&n.push({kind:"review-off",subject:""}),e.tests!==void 0&&t.tests!==void 0&&n.push(...kO(e.tests,t.tests)),e.detectors!==void 0&&t.detectors!==void 0&&n.push(...bO(e.detectors,t.detectors)),n}a(RX,"weakenings");var gO={off:0,note:1,warn:1,block:2};function yO(e,t){return t[e]??(ro(e)?ar[e].default_action:"warn")}a(yO,"effectiveSetting");function bO(e,t){let n=[];for(let r of[...new Set([...Object.keys(e),...Object.keys(t)])].sort()){let o=yO(r,e),i=yO(r,t);(gO[i]??1)<(gO[o]??1)&&n.push({kind:"detector-lowered",subject:`${r} (${o} \u2192 ${i})`})}return n}a(bO,"detectorWeakenings");function kO(e,t){let n=[];if(e===null)return n;if(t===null)return[{kind:"tests-off",subject:""}];let r=new Set(e.skip);for(let o of t.skip)r.has(o)||n.push({kind:"tests-skipped",subject:o});for(let[o,i]of Object.entries(t.commands))e.commands[o]!==i&&n.push({kind:"tests-command",subject:o});for(let o of Object.keys(e.commands))t.commands[o]===void 0&&n.push({kind:"tests-command",subject:o});for(let[o,i]of Object.entries(e.inputs??{})){let s=t.inputs?.[o]??[];i.every(l=>s.some(c=>l===c||l.startsWith(c)))||n.push({kind:"tests-inputs",subject:o})}for(let[o,i]of Object.entries(e.databases??{}))t.databases?.[o]?.supabase!==i.supabase&&n.push({kind:"tests-database",subject:o});return n}a(kO,"testsWeakenings");function EX(e){if(e===null)return!1;let t=e.trim();return t.length<4?!1:!["1","true","yes","on","skip"].includes(t.toLowerCase())}a(EX,"isManifestReason");function _O(e){if(e.base===null||!e.baseRefResolvable)return{kind:"no-base"};if(e.baseUnparsable)return{kind:"base-unparsable"};let t=e.headManifest,n=e.baseManifest===null?t===null?[]:[...t.tests===void 0?[]:kO(e.testsWithoutManifest??null,t.tests),...t.detectors===void 0?[]:bO({},t.detectors)]:RX(e.baseManifest,t);return e.baseManifest===null&&n.length===0?{kind:"base-absent"}:n.length===0?{kind:"intact"}:EX(e.overrideReason)?{kind:"overridden",weakenings:n,reason:e.overrideReason.trim()}:{kind:"weakened",weakenings:n}}a(_O,"classifyManifestDrift");var AX={"manifest-removed":a(()=>"the whole manifest is gone \u2014 every declared gate with it","manifest-removed"),"gate-removed":a(e=>`gate "${e}" is gone`,"gate-removed"),"gate-non-blocking":a(e=>`gate "${e}" no longer blocks`,"gate-non-blocking"),"gate-narrowed":a(e=>`gate "${e}" now applies to less than it did`,"gate-narrowed"),"versioned-removed":a(e=>`"${e}" no longer claims a hand-assigned version`,"versioned-removed"),"work-object-off":a(()=>"a branch no longer needs a work object","work-object-off"),"review-off":a(()=>"the review gate is switched off","review-off"),"tests-off":a(()=>"the built-in test gate is switched off","tests-off"),"tests-skipped":a(e=>`the test suite of "${e}" is skipped now`,"tests-skipped"),"tests-command":a(e=>`the test command of "${e}" changed`,"tests-command"),"tests-inputs":a(e=>`the test suite of "${e}" now runs for less than it did (tests.inputs)`,"tests-inputs"),"tests-database":a(e=>`the test suite of "${e}" no longer gets the clean database it had (tests.databases)`,"tests-database"),"detector-lowered":a(e=>`built-in detector ${e} is milder now (detectors)`,"detector-lowered")};function xb(e){return AX[e.kind](e.subject)}a(xb,"weakeningLine");function wO(e,t,n=null){if(e.branch===null)return{kind:"no-branch"};if(e.remoteSha===null)return{kind:"not-shipped",branch:e.branch};if(e.upstream!==null){let r=`${t}/${e.branch}`;if(e.upstream!==r)return{kind:"upstream-mismatch",branch:e.branch,upstream:e.upstream}}return e.localSha===null?{kind:"unknown",reason:"the local HEAD could not be resolved"}:e.localSha===e.remoteSha?{kind:"match",sha:e.localSha}:n!==null&&e.remoteSha===n&&e.behind===0?{kind:"push-pending",branch:e.branch,local:e.localSha,remote:e.remoteSha,ahead:e.ahead}:{kind:"diverged",branch:e.branch,local:e.localSha,remote:e.remoteSha,ahead:e.ahead,behind:e.behind}}a(wO,"classifyParity");function vO(e){return e.kind==="diverged"||e.kind==="upstream-mismatch"||e.kind==="unknown"}a(vO,"parityBlocks");function Sb(e,t,n=!1){let r=["the working tree has uncommitted changes \u2014 the gates below also judge files that are"," NOT in the commit that gets merged. Commit or discard them before relying on this verdict."];if(n&&e.kind==="match")return[`HEAD == ${t}/HEAD (${e.sha.slice(0,9)}), but ${r[0]}`,r[1]];if(n)return[...Sb(e,t,!1),...r];switch(e.kind){case"match":return[`checked state == ${t}/HEAD (${e.sha.slice(0,9)}).`];case"push-pending":return[`checked state == ${t}/${e.branch} (${e.remote.slice(0,9)}) + ${e.ahead??"?"} commit(s) of promote, not pushed yet (${e.local.slice(0,9)}).`," promote pushes exactly this state, and only if every gate below passes."];case"not-shipped":return[`branch ${e.branch}: no remote yet \u2014 the gate checks the local state.`];case"no-branch":return["detached HEAD \u2014 no remote counterpart to compare against."];case"upstream-mismatch":return[`branch ${e.branch} tracks ${e.upstream}, not ${t}/${e.branch}.`,` A merge takes ${t}/${e.branch}. Every verdict below would describe a different tree.`,` Fix: git branch --set-upstream-to=${t}/${e.branch} ${e.branch}`];case"diverged":{let o=["the gate would NOT check the state that gets merged:",` local HEAD ${e.local.slice(0,9)}${e.ahead!==null?` (${e.ahead} commit(s) ahead)`:""}`,` remote ${t}/${e.branch} ${e.remote.slice(0,9)}${e.behind!==null?` (${e.behind} commit(s) ahead)`:""}`," A merge takes the REMOTE state. Align first:"];return e.ahead!==0&&e.behind!==0?(o.push(" (history was rewritten \u2014 a plain push is rejected and a pull would bring the"," replaced commit back. On your OWN feature branch:)",` git push --force-with-lease ${t} ${e.branch}`),o):(e.ahead!==0&&o.push(` git push ${t} ${e.branch}`),e.behind!==0&&o.push(` git pull --ff-only ${t} ${e.branch}`),o)}case"unknown":return[`could not determine whether the checked state matches ${t}: ${e.reason}.`," This is not a pass \u2014 a verdict about the wrong tree is worse than none."]}}a(Sb,"parityLines");import{execFileSync as Z6}from"node:child_process";import{readFileSync as Q6}from"node:fs";import{join as HI}from"node:path";var Ui=".";function Dd(e){let t=e.lastIndexOf("/");return t<0?Ui:e.slice(0,t)}a(Dd,"dirOf");function Rb(e,t){return e===Ui?t:`${e}/${t}`}a(Rb,"joinDir");function Hi(e,t){return t===Ui||e===t||e.startsWith(`${t}/`)}a(Hi,"isUnder");function $X(e,t){return t===Ui?e:e===t?"":e.slice(t.length+1)}a($X,"relativeTo");function Eb(e){if(typeof e!="string")return!1;let t=e.trim();return t.length===0?!1:!/no test specified/i.test(t)}a(Eb,"isRealTestScript");function TX(e){let t=e.split(`
422
+ `)}catch{}}a(vb,"beginHold");function Yn(e){let t=Cd(e,wb);if(t)try{uX(t,{force:!0})}catch{}}a(Yn,"endHold");function uO(e){let t=Cd(e,wb);if(!t)return null;try{let n=JSON.parse(cX(t,"utf8")),r=typeof n.startHead=="string"&&/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(n.startHead)?n.startHead:null,o=typeof n.at=="string"?n.at:null,i=n.by==="check"||n.by==="promote"?n.by:null;return n.v!==1||!r||!o||!i?null:{v:1,startHead:r,at:o,by:i}}catch{return null}}a(uO,"readHold");function mX(e,t,n){if(!e||!t||e===t)return{kind:"none"};if(n.links.length===0||n.links[0].sha!==e)return{kind:"foreign"};if(n.stoppedAt.sha===t)return{kind:"own",count:n.links.length,to:t};let r=n.links.findIndex(o=>o.sha===t);return r>0?{kind:"own",count:r,to:t}:{kind:"foreign"}}a(mX,"classifyLeftover");function Ya(e,t,n){let r=uO(e);if(r===null)return{kind:"none"};let o=r.startHead,i=!1,s=Cd(e,"MERGE_HEAD");s!==null&&lX(s)&&(i=cO("git",["merge","--abort"],{cwd:e,encoding:"utf8",timeout:6e4}).status===0);let l=Td(e,["rev-parse","HEAD"]);if(!l||l===o)return l===o&&(Td(e,["status","--porcelain"])??"")!==""?{kind:"uncommitted",by:r.by}:(Yn(e),i?{kind:"recovered",count:0,from:o,to:o,by:r.by,abortedMerge:i}:{kind:"cleared"});if(n!==null&&Td(e,["merge-base","--is-ancestor",l,n])!==null)return Yn(e),{kind:"cleared"};let c=mX(l,o,rn(e,l,t));if(c.kind!=="own")return Yn(e),{kind:"foreign",from:l,to:o};let u=cO("git",["reset","--keep",o],{cwd:e,encoding:"utf8",timeout:6e4});return u.status!==0?{kind:"failed",from:l,to:o,output:`${u.stdout??""}${u.stderr??""}`.trim()}:(Yn(e),{kind:"recovered",count:c.count,from:l,to:o,by:r.by,abortedMerge:i})}a(Ya,"recoverHold");function za(e,t,n){switch(e.kind){case"none":case"cleared":return[];case"recovered":return[`an earlier ${e.by==="check"?"promote --check":"promote"} run was interrupted while it held `+(e.count>0?`${e.count} local commit(s) of its own`:"a half-finished merge of the base")+` \u2014 they were never pushed. ${t} is back at ${e.to.slice(0,9)}.`];case"uncommitted":return[`an earlier ${e.by==="check"?"promote --check":"promote"} run ended while it was writing its own files (a release number, derived files) \u2014 they are in the worktree, not committed.`,`if you changed nothing here since, discard them and run it again: cd ${n} && ${ob}`];case"foreign":return[`an earlier promote run was interrupted at ${e.to.slice(0,9)}, but ${t} has moved on to ${e.from.slice(0,9)} with commits promote did not make \u2014 nothing was touched.`];case"failed":return[`an earlier promote run was interrupted and left local commits, and ${t} could not be moved back to ${e.to.slice(0,9)} (${e.output}).`,`undo them before the next run: cd ${n} && git reset --keep ${e.to}`]}}a(za,"holdRecoveryLines");function dO(e){let t=`${e.base} moved from ${e.from.slice(0,9)} to ${e.to.slice(0,9)}${e.commits?` (${e.commits} commit(s))`:""}`,n="the gate judged the merge result with the earlier base, so what would land now is unchecked",r=[e.when==="after-red-gate"?`${t} while the gate ran, and the gate was red \u2014 its verdict was on a combination that would no longer land (a number the base took meanwhile reads as taken, for one). Nothing was pushed and nothing was merged.`:e.when==="after-gate"?`${t} while the gate ran \u2014 ${n}. Nothing was pushed and nothing was merged.`:e.conflicting?`${t} before the merge, and the pull request now conflicts with it. Nothing was merged.`:`${t} before the merge \u2014 ${n}. Nothing was merged.`];return e.retriesSoFar>=e.maxRetries?(r.push(`${e.base} moved ${e.maxRetries+1} times in a row before the merge \u2014 run promote again when it is quieter.`),{retry:!1,lines:r}):(r.push(`promoting again against ${e.base} as it is now (attempt ${e.retriesSoFar+2} of ${e.maxRetries+1}) \u2014 the approval stands, only the base moved.`+(e.conflicting?" A conflict in promote's own release commit is solved there (the commit is withdrawn and the number assigned anew); a conflict in the branch's own content stops that attempt and names the files.":"")),{retry:!0,lines:r})}a(dO,"movedBasePlan");function fO(e,t,n){return[n?`${e} conflicts with ${t} \u2014 nothing was merged. GitHub reported the conflict only after the merge attempt (${t} moved since the checks ran).`:`${e} conflicts with ${t} \u2014 nothing was merged. GitHub builds no merge ref for a conflicting pull request, so the required checks never start.`,`run promote again: it rebuilds the merge result against ${t} and solves a conflict in its own release commit itself. If the branch's own content conflicts, it names the files \u2014 then merge ${t} into the branch, resolve, push (a pushed commit needs a new approval).`]}a(fO,"conflictLines");import{spawn as hX}from"node:child_process";var gX=a((e,t)=>{try{let n=hX(e,t,{stdio:"ignore"});return{kill:a(()=>void n.kill(),"kill"),unref:a(()=>n.unref(),"unref"),on:a((r,o)=>void n.on(r,o),"on")}}catch{return null}},"realSpawn");function yX(e,t){return e==="darwin"?{cmd:"caffeinate",args:["-i","-w",String(t)]}:e==="linux"?{cmd:"systemd-inhibit",args:["--what=idle:sleep","--who=maind","--why=a gate or merge run is in progress","tail",`--pid=${t}`,"-f","/dev/null"]}:null}a(yX,"awakeCommand");var Od=0,Id=null;function Nd(e=process.platform,t=process.pid,n=gX){let r=!1;if(Od===0){let o=yX(e,t),i=o?n(o.cmd,o.args):null;i&&(i.on("error",()=>{}),i.unref(),Id=a(()=>i.kill(),"stop"))}return Od+=1,()=>{r||(r=!0,Od-=1,Od===0&&Id&&(Id(),Id=null))}}a(Nd,"keepAwake");import{randomUUID as bX}from"node:crypto";var kX=45*6e4,_X=3e4,wX=6e4;function pO(e){if(e.kind==="unknown_tool")return{kind:"unavailable",reason:"this MAIND server has no merge lane yet"};if(e.kind==="invalid_params")return{kind:"unavailable",reason:e.reason};if(e.kind==="failed")return{kind:"unavailable",reason:e.reason};let t=e.body;if(t.ok!==!0)return{kind:"unavailable",reason:typeof t.hint=="string"?t.hint:String(t.error??"the server refused")};let n=t.requeued===!0;if(t.granted===!0)return{kind:"granted",requeued:n};let r=typeof t.position=="number"?t.position:0,o=Array.isArray(t.ahead)?t.ahead.map(i=>{let s=i??{};return{ref:typeof s.ref=="string"?s.ref:null,label:typeof s.label=="string"?s.label:null,own:s.own===!0,inLaneSeconds:typeof s.in_lane_seconds=="number"?s.in_lane_seconds:0}}):[];return r<2?{kind:"unavailable",reason:"the server's answer named no place in the lane"}:{kind:"waiting",position:r,ahead:o,requeued:n}}a(pO,"readLane");function mO(e){let t=Math.floor(e/60);return t<1?"less than a minute":t===1?"1 minute":`${t} minutes`}a(mO,"minutesText");function vX(e,t){let n=e.ahead[0],r=n?`${n.own&&n.label?`your run of ${n.label}`:n.own?"another run of yours":"a teammate's run"}${n.ref?` (${n.ref})`:""}, in the lane for ${mO(n.inLaneSeconds)}`:"another promote run",o=e.position>2?` \u2014 ${e.position-1} runs ahead`:"";return`waiting in the merge lane of ${t} for ${r}${o}. promote builds and gates once it is this run's turn, so the base does not move under it.`}a(vX,"waitingLine");var Md=class{constructor(t,n=bX()){this.deps=t;this.runId=n}static{a(this,"MergeLane")}runId;stopHeartbeat=null;entered=!1;lostSaid=!1;async enter(t){if(this.stopHeartbeat)return{kind:"held",waitedMs:0};let n=this.deps,r=n.now(),o=n.maxWaitMs??kX,i="";for(;;){let s=pO(await n.call({action:"enter",runId:this.runId,...t}));if(s.kind==="unavailable")return this.entered&&await this.leave(),n.note(`the merge lane could not be used (${s.reason}) \u2014 promote runs without it, as before.`),{kind:"without",reason:s.reason};if(this.entered=!0,s.kind==="granted"){let c=n.now()-r;return c>0&&i&&n.note(`this run's turn in the merge lane of ${t.base} \u2014 building the merge result now.`),this.stopHeartbeat=n.every(n.heartbeatMs??wX,()=>{this.beat(t)}),{kind:"held",waitedMs:c}}let l=vX(s,t.base);if(l!==i&&(n.note(l),i=l),n.now()-r>=o){await this.leave();let c=`still not this run's turn after ${mO(Math.round(o/1e3))}`;return n.note(`${c} in the merge lane \u2014 promote goes ahead without it; the base may move while it gates.`),{kind:"without",reason:c}}await n.pause(n.pollMs??_X)}}async beat(t){pO(await this.deps.call({action:"enter",runId:this.runId,base:t.base})).kind==="waiting"&&!this.lostSaid&&(this.lostSaid=!0,this.deps.note("this run lost its turn in the merge lane (it was silent for three minutes) \u2014 it goes on; if the base moves, promote starts again as before."))}async leave(){if(this.stopHeartbeat&&(this.stopHeartbeat(),this.stopHeartbeat=null),!!this.entered){this.entered=!1;try{await this.deps.call({action:"leave",runId:this.runId})}catch{}}}};import{execFileSync as BN,spawnSync as KJ}from"node:child_process";import{existsSync as WJ,readFileSync as qJ}from"node:fs";import{join as Qd}from"node:path";var xX={"migration-first":"push the migration before the code goes live","code-first":"release and deploy the code before you push the migration","any-order":"either order works"};function hO(e){return e.verdict==="declared"&&e.declared!==null?[`note rollout \u2014 ${e.declared.order}: ${xX[e.declared.order]} (${e.declared.reason})`]:e.verdict==="undeclared"?e.findings.map(t=>`note rollout \u2014 ${t.title}`):[]}a(hO,"rolloutRows");function SX(e,t){return t===void 0||t.length===0?!0:e===void 0||e.length===0?!1:e.every(n=>t.some(r=>n===r||n.startsWith(r)))}a(SX,"scopeCovers");function RX(e,t){if(t===null)return[{kind:"manifest-removed",subject:""}];let n=[],r=new Map(t.gates.map(i=>[i.id,i]));for(let i of e.gates){let s=r.get(i.id);if(s===void 0){n.push({kind:"gate-removed",subject:i.id});continue}i.blocking&&!s.blocking&&n.push({kind:"gate-non-blocking",subject:i.id}),SX(i.paths,s.paths)||n.push({kind:"gate-narrowed",subject:i.id}),i.run!==s.run&&n.push({kind:"gate-command",subject:i.id})}let o=new Set(t.versionedDirs);for(let i of e.versionedDirs)o.has(i)||n.push({kind:"versioned-removed",subject:i});return e.requireWorkObject&&!t.requireWorkObject&&n.push({kind:"work-object-off",subject:""}),e.review&&!t.review&&n.push({kind:"review-off",subject:""}),e.tests!==void 0&&t.tests!==void 0&&n.push(...kO(e.tests,t.tests)),e.detectors!==void 0&&t.detectors!==void 0&&n.push(...bO(e.detectors,t.detectors)),n}a(RX,"weakenings");var gO={off:0,note:1,warn:1,block:2};function yO(e,t){return t[e]??(ro(e)?ar[e].default_action:"warn")}a(yO,"effectiveSetting");function bO(e,t){let n=[];for(let r of[...new Set([...Object.keys(e),...Object.keys(t)])].sort()){let o=yO(r,e),i=yO(r,t);(gO[i]??1)<(gO[o]??1)&&n.push({kind:"detector-lowered",subject:`${r} (${o} \u2192 ${i})`})}return n}a(bO,"detectorWeakenings");function kO(e,t){let n=[];if(e===null)return n;if(t===null)return[{kind:"tests-off",subject:""}];let r=new Set(e.skip);for(let o of t.skip)r.has(o)||n.push({kind:"tests-skipped",subject:o});for(let[o,i]of Object.entries(t.commands))e.commands[o]!==i&&n.push({kind:"tests-command",subject:o});for(let o of Object.keys(e.commands))t.commands[o]===void 0&&n.push({kind:"tests-command",subject:o});for(let[o,i]of Object.entries(e.inputs??{})){let s=t.inputs?.[o]??[];i.every(l=>s.some(c=>l===c||l.startsWith(c)))||n.push({kind:"tests-inputs",subject:o})}for(let[o,i]of Object.entries(e.databases??{}))t.databases?.[o]?.supabase!==i.supabase&&n.push({kind:"tests-database",subject:o});return n}a(kO,"testsWeakenings");function EX(e){if(e===null)return!1;let t=e.trim();return t.length<4?!1:!["1","true","yes","on","skip"].includes(t.toLowerCase())}a(EX,"isManifestReason");function _O(e){if(e.base===null||!e.baseRefResolvable)return{kind:"no-base"};if(e.baseUnparsable)return{kind:"base-unparsable"};let t=e.headManifest,n=e.baseManifest===null?t===null?[]:[...t.tests===void 0?[]:kO(e.testsWithoutManifest??null,t.tests),...t.detectors===void 0?[]:bO({},t.detectors)]:RX(e.baseManifest,t);return e.baseManifest===null&&n.length===0?{kind:"base-absent"}:n.length===0?{kind:"intact"}:EX(e.overrideReason)?{kind:"overridden",weakenings:n,reason:e.overrideReason.trim()}:{kind:"weakened",weakenings:n}}a(_O,"classifyManifestDrift");var AX={"manifest-removed":a(()=>"the whole manifest is gone \u2014 every declared gate with it","manifest-removed"),"gate-removed":a(e=>`gate "${e}" is gone`,"gate-removed"),"gate-non-blocking":a(e=>`gate "${e}" no longer blocks`,"gate-non-blocking"),"gate-narrowed":a(e=>`gate "${e}" now applies to less than it did`,"gate-narrowed"),"gate-command":a(e=>`the command of gate "${e}" changed (run)`,"gate-command"),"versioned-removed":a(e=>`"${e}" no longer claims a hand-assigned version`,"versioned-removed"),"work-object-off":a(()=>"a branch no longer needs a work object","work-object-off"),"review-off":a(()=>"the review gate is switched off","review-off"),"tests-off":a(()=>"the built-in test gate is switched off","tests-off"),"tests-skipped":a(e=>`the test suite of "${e}" is skipped now`,"tests-skipped"),"tests-command":a(e=>`the test command of "${e}" changed`,"tests-command"),"tests-inputs":a(e=>`the test suite of "${e}" now runs for less than it did (tests.inputs)`,"tests-inputs"),"tests-database":a(e=>`the test suite of "${e}" no longer gets the clean database it had (tests.databases)`,"tests-database"),"detector-lowered":a(e=>`built-in detector ${e} is milder now (detectors)`,"detector-lowered")};function xb(e){return AX[e.kind](e.subject)}a(xb,"weakeningLine");function wO(e,t,n=null){if(e.branch===null)return{kind:"no-branch"};if(e.remoteSha===null)return{kind:"not-shipped",branch:e.branch};if(e.upstream!==null){let r=`${t}/${e.branch}`;if(e.upstream!==r)return{kind:"upstream-mismatch",branch:e.branch,upstream:e.upstream}}return e.localSha===null?{kind:"unknown",reason:"the local HEAD could not be resolved"}:e.localSha===e.remoteSha?{kind:"match",sha:e.localSha}:n!==null&&e.remoteSha===n&&e.behind===0?{kind:"push-pending",branch:e.branch,local:e.localSha,remote:e.remoteSha,ahead:e.ahead}:{kind:"diverged",branch:e.branch,local:e.localSha,remote:e.remoteSha,ahead:e.ahead,behind:e.behind}}a(wO,"classifyParity");function vO(e){return e.kind==="diverged"||e.kind==="upstream-mismatch"||e.kind==="unknown"}a(vO,"parityBlocks");function Sb(e,t,n=!1){let r=["the working tree has uncommitted changes \u2014 the gates below also judge files that are"," NOT in the commit that gets merged. Commit or discard them before relying on this verdict."];if(n&&e.kind==="match")return[`HEAD == ${t}/HEAD (${e.sha.slice(0,9)}), but ${r[0]}`,r[1]];if(n)return[...Sb(e,t,!1),...r];switch(e.kind){case"match":return[`checked state == ${t}/HEAD (${e.sha.slice(0,9)}).`];case"push-pending":return[`checked state == ${t}/${e.branch} (${e.remote.slice(0,9)}) + ${e.ahead??"?"} commit(s) of promote, not pushed yet (${e.local.slice(0,9)}).`," promote pushes exactly this state, and only if every gate below passes."];case"not-shipped":return[`branch ${e.branch}: no remote yet \u2014 the gate checks the local state.`];case"no-branch":return["detached HEAD \u2014 no remote counterpart to compare against."];case"upstream-mismatch":return[`branch ${e.branch} tracks ${e.upstream}, not ${t}/${e.branch}.`,` A merge takes ${t}/${e.branch}. Every verdict below would describe a different tree.`,` Fix: git branch --set-upstream-to=${t}/${e.branch} ${e.branch}`];case"diverged":{let o=["the gate would NOT check the state that gets merged:",` local HEAD ${e.local.slice(0,9)}${e.ahead!==null?` (${e.ahead} commit(s) ahead)`:""}`,` remote ${t}/${e.branch} ${e.remote.slice(0,9)}${e.behind!==null?` (${e.behind} commit(s) ahead)`:""}`," A merge takes the REMOTE state. Align first:"];return e.ahead!==0&&e.behind!==0?(o.push(" (history was rewritten \u2014 a plain push is rejected and a pull would bring the"," replaced commit back. On your OWN feature branch:)",` git push --force-with-lease ${t} ${e.branch}`),o):(e.ahead!==0&&o.push(` git push ${t} ${e.branch}`),e.behind!==0&&o.push(` git pull --ff-only ${t} ${e.branch}`),o)}case"unknown":return[`could not determine whether the checked state matches ${t}: ${e.reason}.`," This is not a pass \u2014 a verdict about the wrong tree is worse than none."]}}a(Sb,"parityLines");import{execFileSync as Z6}from"node:child_process";import{readFileSync as Q6}from"node:fs";import{join as HI}from"node:path";var Ui=".";function Dd(e){let t=e.lastIndexOf("/");return t<0?Ui:e.slice(0,t)}a(Dd,"dirOf");function Rb(e,t){return e===Ui?t:`${e}/${t}`}a(Rb,"joinDir");function Hi(e,t){return t===Ui||e===t||e.startsWith(`${t}/`)}a(Hi,"isUnder");function $X(e,t){return t===Ui?e:e===t?"":e.slice(t.length+1)}a($X,"relativeTo");function Eb(e){if(typeof e!="string")return!1;let t=e.trim();return t.length===0?!1:!/no test specified/i.test(t)}a(Eb,"isRealTestScript");function TX(e){let t=e.split(`
423
423
  `),n=a(r=>r.trim().replace(/^(['"])(.*)\1$/,"$2"),"unquote");for(let r=0;r<t.length;r+=1){let o=/^packages\s*:\s*(.*)$/.exec(t[r]);if(!o)continue;let i=o[1].replace(/\s+#.*$/,"").trim();if(i.startsWith("["))return i.replace(/^\[/,"").replace(/\]\s*$/,"").split(",").map(n).filter(c=>c.length>0);if(i.length>0)return null;let s=[];for(let l=r+1;l<t.length;l+=1){let c=t[l];if(c.trim().length===0||/^\s*#/.test(c))continue;let u=/^\s*-\s+(.*)$/.exec(c);if(!u){if(/^\S/.test(c))break;continue}let d=n(u[1].replace(/\s+#.*$/,""));d.length>0&&s.push(d)}return s}return null}a(TX,"parsePnpmWorkspace");function CX(e){let t=e.workspaces,n=Array.isArray(t)?t:t!==null&&typeof t=="object"&&Array.isArray(t.packages)?t.packages:null;return n===null?null:n.filter(r=>typeof r=="string"&&r.trim().length>0)}a(CX,"workspacesField");function xO(e,t){let n=e.trim().replace(/^\.\//,"").replace(/\/+$/,"");if(n.length===0)return!1;let r="";for(let o=0;o<n.length;o+=1){let i=n[o];if(i==="*")n[o+1]==="*"?n[o+2]==="/"?(r+="(?:.*/)?",o+=2):(r+=".*",o+=1):r+="[^/]*";else if(i==="?")r+="[^/]";else if(i==="{"){let s=n.indexOf("}",o);if(s<0)r+="\\{";else{let l=n.slice(o+1,s).split(",").map(c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));r+=`(?:${l.join("|")})`,o=s}}else r+=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${r}$`).test(t)}a(xO,"matchesWorkspacePattern");function OX(e,t){let n=!1;for(let r of e)r.startsWith("!")?xO(r.slice(1),t)&&(n=!1):xO(r,t)&&(n=!0);return n}a(OX,"isMember");var RO=[["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["bun.lockb","bun"],["bun.lock","bun"],["package-lock.json","npm"],["npm-shrinkwrap.json","npm"]];function IX(e){let t=e.packageManager;if(typeof t!="string")return null;let n=/^(pnpm|npm|yarn|bun)@/.exec(t.trim());return n?n[1]:null}a(IX,"managerField");function jd(e){return e==="package.json"||e==="pnpm-workspace.yaml"||RO.some(([t])=>t===e)||[".npmrc",".pnpmfile.cjs",".yarnrc",".yarnrc.yml","bunfig.toml"].includes(e)?!0:/^tsconfig(\..+)?\.json$/.test(e)}a(jd,"isWorkspaceGlobalFile");function NX(e){if(e===null)return null;try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}a(NX,"parseJsonObject");function SO(e){return e===Ui?0:e.split("/").length}a(SO,"depth");function EO(e){let t=new Set(e.tracked),n=[];for(let m of e.tracked){if(m!=="package.json"&&!m.endsWith("/package.json")||m.split("/").includes("node_modules"))continue;let h=NX(e.read(m));h!==null&&n.push({dir:Dd(m),pkg:h})}let r=new Map;for(let m of n){let h=Rb(m.dir,"pnpm-workspace.yaml"),g=(t.has(h)?TX(e.read(h)??""):null)??CX(m.pkg);g!==null&&g.length>0&&r.set(m.dir,g)}let o=[...r.keys()].sort((m,h)=>SO(h)-SO(m)),i=new Map;for(let m of n){let h=m.dir;for(let b of o)if(!(b===m.dir||!Hi(m.dir,b))&&OX(r.get(b),$X(m.dir,b))){h=b;break}i.set(m.dir,h)}let s=new Set;for(let[m,h]of i)h!==m&&s.add(h);let l=new Map(n.map(m=>[m.dir,m])),c=new Map,u=a(m=>{let h=c.get(m);if(h)return h;let b=null,g=m;for(;g!==null&&b===null;){let _=l.get(g);if(b=_?IX(_.pkg):null,b===null){let w=RO.find(([v])=>t.has(Rb(g,v)));w?b=w[1]:t.has(Rb(g,"pnpm-workspace.yaml"))&&(b="pnpm")}g=g===Ui?null:Dd(g)}let k=b??"npm";return c.set(m,k),k},"managerOf"),d=new Map;for(let m of n){let h=typeof m.pkg.name=="string"&&m.pkg.name.trim().length>0?m.pkg.name.trim():null;if(h===null)continue;let b=i.get(m.dir),g=d.get(b)??new Map;g.has(h)||g.set(h,m.dir),d.set(b,g)}let f=["dependencies","devDependencies","peerDependencies","optionalDependencies"],p=n.map(m=>{let h=i.get(m.dir),b=d.get(h)??new Map,g=new Set;for(let w of f){let v=m.pkg[w];if(!(v===null||typeof v!="object"||Array.isArray(v)))for(let R of Object.keys(v)){let x=b.get(R);x!==void 0&&x!==m.dir&&g.add(x)}}let k=m.pkg.scripts,_=k!==null&&typeof k=="object"&&!Array.isArray(k)?k.test:void 0;return{dir:m.dir,name:typeof m.pkg.name=="string"&&m.pkg.name.trim().length>0?m.pkg.name.trim():null,root:h,manager:u(h),testScript:Eb(_)?_.trim():null,deps:[...g].sort(),isWorkspaceRoot:s.has(m.dir)}});return p.sort((m,h)=>m.dir<h.dir?-1:m.dir>h.dir?1:0),{packages:p}}a(EO,"discoverWorkspace");function AO(e){return`${e} run test`}a(AO,"testCommandFor");function Pd(e){return e.packages.filter(t=>t.testScript===null?!1:t.isWorkspaceRoot?!e.packages.some(n=>n.root===t.dir&&n.dir!==t.dir&&n.testScript!==null):!0)}a(Pd,"suiteUnits");function MX(e,t){let n=null;for(let r of t)Hi(e,r.dir)&&(n===null||r.dir.length>n.dir.length||n.dir===".")&&(n=r);return n}a(MX,"ownerOf");function $O(e,t){let n=new Set([e.dir]),r=[e];for(;r.length>0;){let o=r.pop();for(let i of o.deps){if(n.has(i))continue;n.add(i);let s=t.get(i);s&&r.push(s)}}return[...n].sort()}a($O,"closureOf");function TO(e,t){return!t||t.length===0?e:[...new Set([...e,...t.map(n=>n.replace(/\/+$/,"")).filter(n=>n.length>0)])].sort()}a(TO,"withInputs");function CO(e,t,n){let r=new Map(e.packages.map(m=>[m.dir,m])),o=new Map;for(let m of t){let h=Dd(m),b=r.get(h);if(b?.isWorkspaceRoot&&jd(m.slice(m.lastIndexOf("/")+1)))for(let k of e.packages)k.root===b.dir&&!o.has(k.dir)&&o.set(k.dir,`${m} changed`);let g=MX(m,e.packages);g&&o.set(g.dir,"changed in this diff")}let i=[...o.keys()];for(;i.length>0;){let m=i.pop();for(let h of e.packages)o.has(h.dir)||!h.deps.includes(m)||(o.set(h.dir,`depends on ${m}`),i.push(h.dir))}for(let[m,h]of Object.entries(n.inputs??{})){if(o.has(m))continue;let b=t.find(g=>h.some(k=>g===k||g.startsWith(k)));b!==void 0&&o.set(m,`${b} changed (a declared input)`)}let s=Pd(e),l=new Set(s.map(m=>m.dir)),c=[],u=[],d=new Set(n.skip),f=a(m=>{d.has(m.dir)?u.push(m.dir):c.push(m)},"take");for(let m of s){let h=o.get(m.dir);if(h===void 0&&m.isWorkspaceRoot){let b=e.packages.find(g=>g.root===m.dir&&g.dir!==m.dir&&o.has(g.dir));b&&(h=`${b.dir} changed`)}h!==void 0&&f({dir:m.dir,name:m.name,command:n.commands[m.dir]??AO(m.manager),why:h,closure:TO(m.isWorkspaceRoot?[m.dir]:$O(m,r),n.inputs?.[m.dir]),root:m.root,manager:m.manager,custom:n.commands[m.dir]!==void 0,...n.databases?.[m.dir]?{database:n.databases[m.dir]}:{}})}for(let[m,h]of Object.entries(n.commands)){if(l.has(m))continue;let b=r.get(m),g=b?o.get(m):t.some(k=>Hi(k,m))?"changed in this diff":o.get(m);g!==void 0&&f({dir:m,name:b?.name??null,command:h,why:g,closure:TO(b?$O(b,r):[m],n.inputs?.[m]),root:b?.root??null,manager:b?.manager??null,custom:!0,...n.databases?.[m]?{database:n.databases[m]}:{}})}c.sort((m,h)=>m.dir<h.dir?-1:m.dir>h.dir?1:0);let p=new Set([...l,...Object.keys(n.commands)]).size;return{suites:c,skipped:u.sort(),known:p}}a(CO,"affectedSuites");import{execFileSync as DX}from"node:child_process";import{createHash as jX}from"node:crypto";import{cpSync as PX,existsSync as Za,mkdirSync as DO,readFileSync as LX,writeFileSync as FX}from"node:fs";import{dirname as jO,isAbsolute as BX,join as No,resolve as Ab}from"node:path";function Gi(e){return`tests:${e}`}a(Gi,"testsId");function Xa(e,t){return e.timedOut?Ha(t):e.exit===null?"ended without an exit code":`exit ${e.exit}`}a(Xa,"runDetail");async function OO(e,t,n,r=null){let o=new Map,i=[],s=0;for(let l of e){if(r!==null&&s>=r){o.set(l.dir,{kind:"not-run"});continue}n.progress(Gi(l.dir));let c=await n.run(l,t);if(s+=c.ms,c.unavailable!==void 0){o.set(l.dir,{kind:"unavailable",ms:c.ms,reason:c.unavailable});continue}if(c.ok){o.set(l.dir,{kind:"green",ms:c.ms});continue}if(c.timedOut){i.push({suite:l,run:c,ms:c.ms});continue}let u=await n.run(l,t);if(u.unavailable!==void 0){i.push({suite:l,run:c,ms:c.ms+u.ms});continue}if(u.ok){o.set(l.dir,{kind:"flaky",ms:c.ms+u.ms,run:c});continue}i.push({suite:l,run:u,ms:c.ms+u.ms})}if(i.length>0){let l=await n.compareWithBase(i.map(c=>c.suite));for(let c of i)o.set(c.suite.dir,{kind:"red",ms:c.ms,run:c.run,base:l.get(c.suite.dir)??{kind:"unavailable",reason:"the base run gave no answer"}})}return o}a(OO,"runSuites");function IO(e,t,n,r,o=null){let i=Gi(e.dir),s=`\`${e.command}\` in ${e.dir}`;if(t.kind==="not-run")return{id:i,verdict:"not-checked",blocking:!1,note:`not run \u2014 the suites before it used the ${o??"?"} minutes the built-in test gate takes by default. Set "tests": true in .maind/gates.json to run every affected suite, or name what to skip under "tests.skip"`};if(t.kind==="unavailable")return{id:i,verdict:"not-checked",blocking:!1,durationMs:t.ms,note:`not run \u2014 ${s} needs a clean database, and ${t.reason}`};if(t.kind==="green")return{id:i,verdict:"pass",blocking:!0,durationMs:t.ms};if(t.kind==="flaky")return{id:i,verdict:"fail",blocking:!1,durationMs:t.ms,note:`flaky: ${s} failed once (${Xa(t.run,r)}) and passed on the second run`};let l=Xa(t.run,r),c=t.run.timedOut?{timedOut:!0}:{},u=t.base;return u.kind==="green"?{id:i,verdict:"fail",blocking:!0,durationMs:t.ms,...c,note:`${s} is red on this branch (${l}) and green on ${n} \u2014 this branch broke it`}:u.kind==="new"?{id:i,verdict:"fail",blocking:!0,durationMs:t.ms,...c,note:`${s} is red (${l}); the suite does not exist on ${n}, so it is this branch's own`}:u.kind==="red"?{id:i,verdict:"fail",blocking:!1,durationMs:t.ms,...c,note:`${s} is red here (${l}) and on ${n} as well`+(u.seen?` (seen ${u.seen.slice(0,16).replace("T"," ")} UTC)`:"")+" \u2014 not caused by this branch"}:{id:i,verdict:"fail",blocking:!1,durationMs:t.ms,...c,note:`${s} is red (${l}), and it could not be compared with ${n}: ${u.reason}`}}a(IO,"suiteResult");function NO(e){return e.kind==="green"||e.kind==="not-run"||e.kind==="unavailable"?!1:e.kind==="flaky"?!0:e.base.kind!=="red"}a(NO,"showsOutput");function Ja(e){return{id:"tests",verdict:"not-checked",blocking:!1,note:e}}a(Ja,"noSuitesResult");var UX=24*60*6e4,Ld=10*6e4,HX="maind/tests-base.json";function vn(e,t){try{return DX("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:12e4,maxBuffer:64*1024*1024}).trim()}catch{return null}}a(vn,"git");function GX(e,t){return t==="."?`${e}^{tree}`:`${e}:${t}`}a(GX,"treeish");function KX(e,t){return e==="pnpm"?"pnpm install --frozen-lockfile":e==="yarn"?t?"yarn install --immutable":"yarn install --frozen-lockfile":e==="bun"?"bun install --frozen-lockfile":"npm ci"}a(KX,"frozenInstall");function WX(e,t,n){if(!n(e.dir))return!1;if(e.custom)return!0;let r=t(e.dir==="."?"package.json":`${e.dir}/package.json`);if(r===null)return!1;try{let o=JSON.parse(r);return Eb(o.scripts?.test)}catch{return!1}}a(WX,"existsOnBase");function qX(e,t,n){let r=[n.dir,n.command];for(let o of n.closure){let i=vn(e,["rev-parse","--verify","--quiet",GX(t,o)]);if(i===null)return null;r.push(`${o}=${i}`)}if(n.root!==null){let o=vn(e,n.root==="."?["ls-tree",t]:["ls-tree",t,`${n.root}/`]);if(o===null)return null;for(let i of o.split(`
424
424
  `)){let s=/^\d+ blob ([0-9a-f]+)\t(.+)$/.exec(i);if(!s)continue;let l=s[2].slice(s[2].lastIndexOf("/")+1);jd(l)&&r.push(`${l}=${s[1]}`)}}return jX("sha256").update(r.join(`
425
425
  `)).digest("hex")}a(qX,"baseKey");function PO(e){let t=vn(e,["rev-parse","--git-common-dir"]);return t?No(BX(t)?t:Ab(e,t),HX):null}a(PO,"redLogPath");function VX(e,t){let n={v:1,red:{}},r=PO(e);if(!r)return n;try{let o=JSON.parse(LX(r,"utf8"));if(o.v!==1||o.red===null||typeof o.red!="object")return n;let i={};for(let[s,l]of Object.entries(o.red)){let c=Date.parse(l?.at??"");Number.isFinite(c)&&t-c<=UX&&t>=c&&(i[s]=l)}return{v:1,red:i}}catch{return n}}a(VX,"readRedLog");function YX(e,t){let n=PO(e);if(n)try{DO(jO(n),{recursive:!0}),FX(n,`${JSON.stringify(t,null,2)}