nemar-cli 0.10.36-PR2236.2007db0 → 0.10.36-PR2237.37bd199

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.
@@ -23,7 +23,7 @@ ${t}`,zM,GM,KM=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=VM.bind(null,n,
23
23
  `)}var Fl=!1;var{spawn:WF}=globalThis.Bun;function Vl(e,t=[]){let r=e.replace(YF,'("$1","<redacted>")');for(let n of t)if(n.length>=XF)r=r.split(n).join("<redacted>");return r}function QF(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],r=new Set;for(let n of[process.env,e??{}])for(let s of t){let o=n[s];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function hw(e,t){let r=e.getReader(),n=new TextDecoder,s="";while(!0){let{done:o,value:i}=await r.read();if(o)break;if(i.byteLength===0)continue;t(),s+=n.decode(i,{stream:!0})}return s+n.decode()}async function mw(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete r[y];let n=WF({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),s=!1,o,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??JF)};if(u(),t.timeout)o=setTimeout(()=>{s=!0,c(),n.kill()},t.timeout);let d=ic()?[...QF(r),...t.redact??[]]:[];if(ic()){let y=t.cwd?` (cwd=${t.cwd})`:"";qs(Nt.dim(Vl(`$ ${e.join(" ")}${y}`,d)))}let l=()=>{a=performance.now(),u()},p,f,h,m=n.exited.then((y)=>(c(),y));try{[p,f,h]=await Promise.all([hw(n.stdout,l),hw(n.stderr,l),m])}finally{if(c(),o)clearTimeout(o)}if(ic()){if(t.sensitiveOutput)qs(Nt.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())qs(Nt.dim(Vl(p.trimEnd(),d)));if(f.trim())qs(Nt.yellow(Vl(f.trimEnd(),d)))}qs(Nt.dim(`(exit ${h})`))}if(s)return{stdout:p,stderr:f||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:f,exitCode:h,timedOut:!1}}var YF,XF=8,JF=120000;var gw=F(()=>{Ul();YF=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function eV(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function _w(e,t=eV()){return e.installInstructions[t]}function tV(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function nV(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:rV}async function vw(e){try{let{exitCode:t,stdout:r,timedOut:n}=await mw(e.cmd,{timeout:nV()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:tV(r)}}catch(t){let r=t instanceof Error?t.message:String(t);if(!r.includes("ENOENT")&&!r.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${r}`);return{available:!1}}}async function zl(){let e=Object.entries(yw);return Promise.all(e.map(async([t,r])=>{let{available:n,version:s,timedOut:o}=await vw(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:s,timedOut:o,installInstruction:_w(r)}}))}async function Z3(){let t=(await zl()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
24
24
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let r of t)console.warn(` - ${r.name} (${r.purpose})`),console.warn(` Install: ${r.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function eB(e){let r=ZF[e].map((i)=>yw[i]).filter(Boolean),n=await Promise.all(r.map(async(i)=>{let a=await vw(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of n)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let s=n.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:_w(i.check)}));if(s.length===0)return;let o=[`
25
25
  Missing required tools:`];for(let i of s)o.push(` ${i.tool} not installed`),o.push(` Install: ${i.installInstruction}`);throw Error(o.join(`
26
- `))}var yw,ZF,rV=4000;var $w=F(()=>{gw();yw={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},ZF={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var bw;var Ew=F(()=>{bw={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.36-PR2236.2007db0",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Ew();ac=bw.version});import{mkdirSync as oV,readdirSync as iV,unlinkSync as aV,writeFileSync as cV}from"fs";import{join as Kl}from"path";function dB(){Ds=!0}function lc(){return Ds}function fB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function pB(e){Tw=e,pr(`Step: ${e}`)}function hB(){xw=!0}function mB(){return xw}function gB(){if(Rw)return;Bl=!0}function yB(){Bl=!1,Rw=!0}function _B(){return Bl}function pr(e){if(Ds)process.stderr.write(`[debug] ${e}
26
+ `))}var yw,ZF,rV=4000;var $w=F(()=>{gw();yw={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},ZF={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var bw;var Ew=F(()=>{bw={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.36-PR2237.37bd199",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Ew();ac=bw.version});import{mkdirSync as oV,readdirSync as iV,unlinkSync as aV,writeFileSync as cV}from"fs";import{join as Kl}from"path";function dB(){Ds=!0}function lc(){return Ds}function fB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function pB(e){Tw=e,pr(`Step: ${e}`)}function hB(){xw=!0}function mB(){return xw}function gB(){if(Rw)return;Bl=!0}function yB(){Bl=!1,Rw=!0}function _B(){return Bl}function pr(e){if(Ds)process.stderr.write(`[debug] ${e}
27
27
  `)}function fV(e){let t={};for(let[r,n]of Object.entries(e))t[r]=dV.has(r.toLowerCase())?"[REDACTED]":n;return t}function Ow(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Hl(e,t,r=0){if(r>hV)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>Hl(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[s,o]of Object.entries(t))n[s]=Hl(s,o,r+1);return n}if(typeof t==="string"){if(pV.test(e))return"[REDACTED]";return t.replace(kw,Ow)}return t}function Wl(e){return e.replace(mV,"Bearer [REDACTED]").replace(gV,"[REDACTED_AWS_KEY]").replace(yV,"$1[REDACTED]").replace(_V,"$1$2=[REDACTED]").replace(kw,Ow)}function vV(e){return Wl(e)}function ww(e,t=lV){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(Hl("",n))}catch{}if(r=Wl(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function dc(e){if(!Ds)return;let t=vV(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?fV(e.requestHeaders):void 0,requestBody:ww(e.requestBody),responseBody:ww(e.responseBody)};uc.push(r),pr(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=dr(r);uc.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),pr(`redaction failed for ${e.method} ${t}: ${n}`)}}async function $V(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${ac}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${dr(t)})`)}e.push(""),e.push("Active account:");try{let t=hn();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${dr(t)})`)}e.push(""),e.push("External tools:");try{let t=await zl();for(let r of t){let n=r.available?r.version??"installed":r.timedOut?"(timed out)":"not installed";e.push(` ${r.name}: ${n}`)}}catch(t){e.push(` (could not probe external tools: ${dr(t)})`)}return e}async function EV(){return(await $V()).join(`
28
28
  `)}async function vB(){if(!Ds||cc!==void 0)return;try{cc=await EV()}catch(e){let t=dr(e);cc=`(could not build environment report: ${t})`,pr(`environment snapshot failed: ${t}`)}}function Aw(e){if(Sw.has(e))return{flag:e};for(let t of Sw){if(!e.startsWith(t)||e.length<=t.length)continue;if(t.length===2)return{flag:t,kind:"short-attached"};if(e[t.length]==="=")return{flag:t,kind:"long-eq"}}return null}function bV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Aw(n);if(!s){t.push(n);continue}if(s.kind==="long-eq")t.push(`${s.flag}=[REDACTED]`);else if(s.kind==="short-attached")t.push(`${s.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function wV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Aw(n);if(!s){t.push(n);continue}if(!s.kind&&r+1<e.length)r++}return t}function SV(e){let t=[];for(let n of wV(e)){if(n.startsWith("-"))continue;if(t.push(n),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function xV(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${Wl(bV(e).join(" "))}`),r.push(""),r.push(cc??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),uc.length===0)r.push(" (none)");else uc.forEach((n,s)=>{if(r.push(` [${s+1}] ${n.method} ${n.url} -> ${n.status??"ERROR"} (${n.durationMs}ms)`),n.error)r.push(` Error: ${n.error}`);if(n.note)r.push(` Note: ${n.note}`);if(n.requestHeaders)r.push(` Request headers: ${JSON.stringify(n.requestHeaders)}`);if(n.requestBody)r.push(` Request body: ${n.requestBody}`);if(n.responseBody)r.push(` Response body: ${n.responseBody}`)});return r.push(""),r.push(`Failing step: ${Tw??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
29
29
  `)}
package/dist/index.js CHANGED
@@ -99,7 +99,7 @@ ${t}`,vQe,EQe,SQe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=xQe.bind(nul
99
99
  `)}var xM=!1;var{spawn:vwt}=globalThis.Bun;function bp(e,t=[]){let n=e.replace(Ewt,'("$1","<redacted>")');for(let r of t)if(r.length>=Swt)n=n.split(r).join("<redacted>");return n}function ZR(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],n=new Set;for(let r of[process.env,e??{}])for(let o of t){let s=r[o];if(typeof s==="string"&&s.length>0)n.add(s)}return[...n]}async function Ige(e,t){let n=e.getReader(),r=new TextDecoder,o="";while(!0){let{done:s,value:i}=await n.read();if(s)break;if(i.byteLength===0)continue;t(),o+=r.decode(i,{stream:!0})}return o+r.decode()}async function O(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=vwt({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:n}),o=!1,s,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},l=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??kwt)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=Gg()?[...ZR(n),...t.redact??[]]:[];if(Gg()){let y=t.cwd?` (cwd=${t.cwd})`:"";Gd(u.dim(bp(`$ ${e.join(" ")}${y}`,d)))}let f=()=>{a=performance.now(),l()},p,m,h,g=r.exited.then((y)=>(c(),y));try{[p,m,h]=await Promise.all([Ige(r.stdout,f),Ige(r.stderr,f),g])}finally{if(c(),s)clearTimeout(s)}if(Gg()){if(t.sensitiveOutput)Gd(u.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())Gd(u.dim(bp(p.trimEnd(),d)));if(m.trim())Gd(u.yellow(bp(m.trimEnd(),d)))}Gd(u.dim(`(exit ${h})`))}if(o)return{stdout:p,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:m,exitCode:h,timedOut:!1}}var Ewt,Swt=8,kwt=120000;var Gt=z(()=>{We();Ewt=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function $wt(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function Fge(e,t=$wt()){return e.installInstructions[t]}function Dwt(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function Awt(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Cwt}async function Mge(e){try{let{exitCode:t,stdout:n,timedOut:r}=await O(e.cmd,{timeout:Awt()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:Dwt(n)}}catch(t){let n=t instanceof Error?t.message:String(t);if(!n.includes("ENOENT")&&!n.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${n}`);return{available:!1}}}async function zw(){let e=Object.entries(Nge);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await Mge(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:Fge(n)}}))}async function jge(){let t=(await zw()).filter((n)=>n.required&&!n.available);if(t.length===0)return[];console.warn(`
100
100
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let n of t)console.warn(` - ${n.name} (${n.purpose})`),console.warn(` Install: ${n.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function wp(e){let n=Rwt[e].map((i)=>Nge[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await Mge(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of r)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let o=r.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:Fge(i.check)}));if(o.length===0)return;let s=[`
101
101
  Missing required tools:`];for(let i of o)s.push(` ${i.tool} not installed`),s.push(` Install: ${i.installInstruction}`);throw Error(s.join(`
102
- `))}var Nge,Rwt,Cwt=4000;var Vw=z(()=>{Gt();Nge={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},Rwt={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var qge;var Lge=z(()=>{qge={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.36-PR2236.2007db0",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Gs;var _p=z(()=>{Lge();Gs=qge.version});import{mkdirSync as Twt,readdirSync as Pwt,unlinkSync as Iwt,writeFileSync as Nwt}from"fs";import{join as vM}from"path";function Vge(){zg=!0}function jl(){return zg}function Wge(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Kw(e){zge=e,In(`Step: ${e}`)}function Yo(){Hge=!0}function Kge(){return Hge}function ue(){if(Gge)return;SM=!0}function Jw(){SM=!1,Gge=!0}function Jge(){return SM}function In(e){if(zg)process.stderr.write(`[debug] ${e}
102
+ `))}var Nge,Rwt,Cwt=4000;var Vw=z(()=>{Gt();Nge={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},Rwt={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var qge;var Lge=z(()=>{qge={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.36-PR2237.37bd199",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Gs;var _p=z(()=>{Lge();Gs=qge.version});import{mkdirSync as Twt,readdirSync as Pwt,unlinkSync as Iwt,writeFileSync as Nwt}from"fs";import{join as vM}from"path";function Vge(){zg=!0}function jl(){return zg}function Wge(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Kw(e){zge=e,In(`Step: ${e}`)}function Yo(){Hge=!0}function Kge(){return Hge}function ue(){if(Gge)return;SM=!0}function Jw(){SM=!1,Gge=!0}function Jge(){return SM}function In(e){if(zg)process.stderr.write(`[debug] ${e}
103
103
  `)}function Lwt(e){let t={};for(let[n,r]of Object.entries(e))t[n]=jwt.has(n.toLowerCase())?"[REDACTED]":r;return t}function Xge(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function EM(e,t,n=0){if(n>Uwt)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>EM(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=EM(o,s,n+1);return r}if(typeof t==="string"){if(qwt.test(e))return"[REDACTED]";return t.replace(Yge,Xge)}return t}function kM(e){return e.replace(Bwt,"Bearer [REDACTED]").replace(Hwt,"[REDACTED_AWS_KEY]").replace(Gwt,"$1[REDACTED]").replace(zwt,"$1$2=[REDACTED]").replace(Yge,Xge)}function Vwt(e){return kM(e)}function Uge(e,t=Mwt){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(EM("",r))}catch{}if(n=kM(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function n$(e){if(!zg)return;let t=Vwt(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?Lwt(e.requestHeaders):void 0,requestBody:Uge(e.requestBody),responseBody:Uge(e.responseBody)};t$.push(n),In(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=W(n);t$.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),In(`redaction failed for ${e.method} ${t}: ${r}`)}}async function Wwt(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${Gs}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${W(t)})`)}e.push(""),e.push("Active account:");try{let t=Yt();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${W(t)})`)}e.push(""),e.push("External tools:");try{let t=await zw();for(let n of t){let r=n.available?n.version??"installed":n.timedOut?"(timed out)":"not installed";e.push(` ${n.name}: ${r}`)}}catch(t){e.push(` (could not probe external tools: ${W(t)})`)}return e}async function RM(){return(await Wwt()).join(`
104
104
  `)}async function Qge(){if(!zg||e$!==void 0)return;try{e$=await RM()}catch(e){let t=W(e);e$=`(could not build environment report: ${t})`,In(`environment snapshot failed: ${t}`)}}function Zge(e){if(Bge.has(e))return{flag:e};for(let t of Bge){if(!e.startsWith(t)||e.length<=t.length)continue;if(t.length===2)return{flag:t,kind:"short-attached"};if(e[t.length]==="=")return{flag:t,kind:"long-eq"}}return null}function Kwt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=Zge(r);if(!o){t.push(r);continue}if(o.kind==="long-eq")t.push(`${o.flag}=[REDACTED]`);else if(o.kind==="short-attached")t.push(`${o.flag}[REDACTED]`);else if(t.push(r),n+1<e.length)t.push("[REDACTED]"),n++}return t}function Jwt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=Zge(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function Ywt(e){let t=[];for(let r of Jwt(e)){if(r.startsWith("-"))continue;if(t.push(r),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function Xwt(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${kM(Kwt(e).join(" "))}`),n.push(""),n.push(e$??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),t$.length===0)n.push(" (none)");else t$.forEach((r,o)=>{if(n.push(` [${o+1}] ${r.method} ${r.url} -> ${r.status??"ERROR"} (${r.durationMs}ms)`),r.error)n.push(` Error: ${r.error}`);if(r.note)n.push(` Note: ${r.note}`);if(r.requestHeaders)n.push(` Request headers: ${JSON.stringify(r.requestHeaders)}`);if(r.requestBody)n.push(` Request body: ${r.requestBody}`);if(r.responseBody)n.push(` Response body: ${r.responseBody}`)});return n.push(""),n.push(`Failing step: ${zge??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
105
105
  `)}
@@ -994,7 +994,7 @@ ${b.message}`,r);if(x)return Zt("message",`The squash message would not carry th
994
994
  `)}async function wA(e,t,n,r){let o=Nn[r],s=r==="n0"?t.synth_sha:t[o.gates];if(!await Mn(e,n,1))return"tag-unread";let i=async()=>(await ne(e.dir,["cat-file","-e",`${s}^{commit}`],{ok:!0})).exitCode===0;if(!await i()){for(let l of[s,jn(t[o.version]),`refs/pull/${t[o.number]}/head`])if(await Mn(e,l,Lo)&&await i())break}if(!await i())return"commit-unread";let a=await PCe(e.dir,n),c=await PCe(e.dir,s);if(a===null||c===null)return"tag-unread";return a===c?"same":"differs"}async function TPt(e,t,n,r){let o=await wA(e,t,n,"n0");if(o==="same")return!0;return r(o==="tag-unread"?"The tagged commit could not be fetched, so its tree is not verified (lineage is not recorded).":o==="commit-unread"?"The re-pull's commit could not be fetched, so the tagged tree is not verified (lineage is not recorded).":"The tagged tree is not the re-pull's commit outside .nemar/ and .github/, so lineage is not recorded for it."),!1}async function PPt(e,t,n,r){let o=await wA(t,n,r,"n1");if(o==="same")return;let s=n.patch_gates_sha.slice(0,12);if(o==="differs"&&e.opts.acceptTagTree){e.opts.out(`The tag v${n.patch_version} is not N.0.1's gated head ${s} outside .nemar/ and .github/; its release is recorded on your reason: ${e.opts.acceptTagTree}`);return}let i=o==="differs"?tt("patch-tree-mismatch",`The tag v${n.patch_version} on NEMAR's main is not N.0.1's gated head outside .nemar/ and .github/, so its release is not recorded and the record stays ${n.status}. Read the difference (git diff ${s} v${n.patch_version} -- . ':!.nemar' ':!.github'), then record the release with nemar admin repull resume ${n.dataset_id} --accept-tag-tree "<reason>".`):tt("origin-unreadable",`The tag v${n.patch_version} or N.0.1's gated head could not be read from NEMAR's repository, so the tagged tree is not verified and its release is not recorded; run resume again.`);throw await eo(n,Os("release",i),e.opts.out),i}async function IPt(e,t){return(await kp(e)).versions.some((r)=>r.version===t||r.version===`v${t}`)}async function NPt(e,t,n,r,o){let s=n[Nn[r].mergeSha];if(e.mergeTrailersRead=!0,!await Mn(t,s,1))throw await o("merge-unreadable",`The merge commit ${s.slice(0,12)} could not be fetched from NEMAR's repository, so its trailers were not read; nothing was recorded past merged.`);let i=await ne(t.dir,["cat-file","commit",s],{ok:!0}),a=i.stdout.indexOf(`
995
995
 
996
996
  `);if(i.exitCode!==0||a<0)throw await o("merge-trailers",`The message of the merge commit ${s.slice(0,12)} could not be read, so its trailers were not read; nothing was recorded past ${n.status}.`);let c=await du(i.stdout.slice(a+2),n);if(c===null&&e.opts.acceptMergeTrailers)e.opts.out(`The merge commit ${s.slice(0,12)} carries the re-pull's trailers; --accept-merge-trailers changes nothing.`);return c}async function aq(e,t,n){let r=t[Nn[n].version],o=`refs/tags/v${r}`,s=t[Nn[n].mergeSha],i=await e.origin(),a=async(h,g)=>{let y=tt(h,g);return await eo(t,Os("release",y),e.opts.out),y},c=await NPt(e,i,t,n,a),l=!1;if(c!==null){if(l=await OCe(e,i,t,n,c),!l&&!e.opts.acceptMergeTrailers){let h=t.origin==="administrator"?`If it was merged outside NEMAR's gate (GitHub's merge button, say), read what it holds, then run nemar admin repull resume ${t.dataset_id} --accept-merge-trailers "<reason>", which accepts it only once it is shown to be this re-pull's own squash merge or GitHub's plain merge of its pull request, and only for the administrator who opened the re-pull.`:"The automatic path opened this re-pull, and the Worker merges its pull requests with the trailers, so a merge made another way is not accepted and no command moves this record on; tell the owner.";throw await a("merge-trailers",`The merge commit ${s.slice(0,12)} on main does not end with the re-pull commit's two trailers (${c}), so the privacy ledger's fresh-clone proof would not read it as the re-pull's commit. The record stays ${t.status}. ${h}`)}}let d;try{d=(await lu(i,[o,`${o}^{}`])).get(o)}catch(h){if(h instanceof j)h.resumable=!0;throw h}if(!d)return{kind:"wait",row:t,waitingFor:`the tag v${r} on NEMAR's repository`};let f;try{f=await IPt(e.datasetId,r)}catch(h){throw Zr(h,"The dataset's versions could not be read")}if(!f)return{kind:"wait",row:t,waitingFor:`the version row of v${r} (its DOI)`};if(c!==null&&!l)await TCe(e,i,t,n,c,e.opts.acceptMergeTrailers);if(n==="n1")await PPt(e,i,t,d);let p=n==="n0"?await TPt(i,t,d,e.opts.out):!1,m;try{m=await VEe(t.id,{pr:n,tag_sha:d,tree_verified:p})}catch(h){let g=xn(h);if(g==="not-released")return{kind:"wait",row:t,waitingFor:`the DOI of v${r}`};let y=tt(g??"release-failed",`The release of v${r} could not be recorded: ${h instanceof Error?h.message:String(h)}`);if(h instanceof U)await eo(t,Os("release",y),e.opts.out);throw y}return e.opts.out(`Re-pull #${t.id} is released: v${r} at ${d.slice(0,12)}${n==="n1"?"":m.lineage_rows?`, lineage recorded for v${r}`:p?"":", lineage not recorded"}; the dataset's sweeps read it again.`),{kind:"next",row:m.repull}}async function wx(e){let t=await e.origin();if(!await Mn(t,"refs/heads/git-annex",1))throw tt("origin-unreadable","NEMAR's git-annex branch could not be fetched.");let n=await ne(t.dir,["cat-file","blob","refs/remotes/origin/heads/git-annex:remote.log"],{ok:!0}),r=cm(n.exitCode===0?n.stdout:"",e.datasetId);if(r.problem!==null)throw tt("nemar-s3-invalid",r.problem);let o=r.record?.bucket;if(n.exitCode!==0||!r.uuid||!o)throw tt("no-nemar-s3","NEMAR's remote.log names no single nemar-s3 bucket.");let s={};for(let[a,c]of Object.entries(e.env))if(c!==void 0)s[a]=c;let i=yA({region:r.region,timeoutMs:hA,env:s,credentials:gA({commandEnv:s})});return{scratch:t,uuid:r.uuid,bucket:o,region:r.region,prefix:r.prefix,aws:i}}async function cq(e,t,n){let{scratch:r,bucket:o,aws:s}=n??await wx(e),i=OPt(r.dir,"staging-manifest.json"),a=!1;for(let f of new Set([t.to_tag,`v${t.to_tag}`]))try{await s.api("get-object",["--bucket",o,"--key",bA(e.datasetId,f),i]),a=!0;break}catch(p){if(!(p instanceof Vt))throw p;if(p.code!=="not-found")throw tt("staging-unreadable",`The staging manifest of re-pull #${t.id} could not be read (${vf(p)}); the ambient AWS credentials read it, as the copy wrote it.`)}if(!a)throw tt("staging-unreadable",`The staging manifest of re-pull #${t.id} is not in NEMAR's bucket, so which objects its copy wrote is not known.`);let c=APt(i);if(`sha256:${CPt("sha256").update(c).digest("hex")}`!==t.manifest_digest)throw tt("manifest-mismatch","The staging manifest in NEMAR's bucket is not the copy manifest recorded at prepared.");let l=JSON.parse(c.toString("utf8")),d=[...l.items??[],...l.local??[]].map((f)=>f.key);if(!d.every((f)=>typeof f==="string"))throw tt("manifest-mismatch","The staging manifest names an object without a key.");return[...new Set(d)].sort()}async function ICe(e,t){if(typeof t.counts.locked==="number")return{kind:"next",row:t};let n=async(c,l)=>{let d=tt(c,l);return await eo(t,Os("lock",d),e.opts.out),d},r;try{r=await cq(e,t)}catch(c){if(c instanceof j)throw await n(c.code,c.message);throw c}let o;try{o=r.length>0?await o0e(e.datasetId,r):{locked:0,failed:[],objects:[]}}catch(c){throw await n("lock-failed",`The objects of v${t.to_version} could not be locked (${c instanceof U?`HTTP ${c.statusCode}`:"no answer"}); run resume again.`)}let s=new Set(o.objects.map((c)=>c.key)),i=r.filter((c)=>!s.has(c)).length;if(o.failed.length>0||i>0)throw await n("lock-incomplete",`${i} of the ${r.length} object(s) N.0.0's copy and uploads wrote were not locked (${r.length-i} were); run resume again, which locks them again.`);let a;try{a=await ar(t.id,{from:"released",to:"released",fields:{counts:{locked:r.length}}})}catch(c){throw Zr(c,"The count of locked objects could not be recorded")}return e.opts.out(`Locked the ${r.length} object(s) N.0.0's copy and uploads wrote under the governance lock.`),{kind:"next",row:a}}async function lq(e,t,n,r){let o;try{o=await ar(t.id,{from:"released",to:"complete",...r?{fields:{counts:r}}:{}})}catch(s){throw Zr(s,"The record could not be completed")}return e.opts.out(`Re-pull #${t.id} of ${e.datasetId} is complete${n}.`),{kind:"done",result:{row:o,outcome:"complete"}}}async function FPt(e,t){let n=e.opts.plan??Ny(e.configDir,e.datasetId,t.to_tag,t.plan_digest),{file:r,body:o}=lm(n,{environment:zr(),env:e.env,openNeuroGraphqlUrl:ru(e.env)});if(r.digest!==t.plan_digest)throw new j("plan-not-the-record",`The plan file is not the plan re-pull #${t.id} was made from (its digest differs); pass the reviewed plan with --plan <file>.`);return o}function MPt(e,t,n,r=null){return[`NEMAR's corrections of re-pull #${e.id} (upstream ${e.upstream_ds} ${e.from_tag} to ${e.to_tag}), replayed onto v${e.to_version} as v${n} of ${e.dataset_id} (ADR 0111).`,"",`v${e.to_version} is upstream's snapshot ${e.upstream_ds}@${e.to_tag} with NEMAR's standard edits; this pull request puts back NEMAR's own side of what the plan listed as a correction, and of each conflict an administrator resolved to NEMAR's side. Nothing is scrubbed and nothing is copied: every replayed byte is in a version NEMAR already published.`,"",`- Re-pull record: #${e.id}`,`- Plan digest: ${e.plan_digest}`,`- Corrections the plan listed: ${t.corrections}; conflicts resolved to NEMAR's side: ${t.resolutions}`,`- Paths replayed: ${t.paths.length}; description keys replayed: ${t.keys.length}`,...r===null?[]:[r.ok?`- iEEG geometry pipeline files regenerated from the new snapshot: ${r.files.write.size} written, ${r.files.remove.length} removed, ${r.files.kept} kept as they are`:`- iEEG geometry pipeline files: the regeneration failed (${r.code}), so this pull request carries none of the previous pipeline files`],"- Version DOIs this pull request mints when merged: 1","",`\`nemar admin repull resume ${e.dataset_id}\` takes this pull request through the identifier screen and the gates, and \`nemar admin repull merge ${e.dataset_id}\` (or \`nemar admin pr-reviews\`, through the same gate) squash-merges it under the daily merge cap; a merge mints a version DOI that cannot be withdrawn.`,"","The squash commit message must end with the re-pull's trailers, as its last paragraph; the merge path writes that message itself and refuses one that does not:","","```",...pa(e),$_(t.corrections),"```","","Do not merge this from GitHub's page."].join(`
997
- `)}async function LCe(e,t){let n=t.counts.corrections,r=t.counts.conflicts,o=t.counts.pipeline_owned??0,s=e.opts.takeOurs??[];if(typeof n!=="number"||typeof r!=="number")return e.opts.out(`Re-pull #${t.id}'s record does not say how many corrections and conflicts its plan has, so it is not completed; it stays released, and it blocks ${t.dataset_id}'s next re-pull until it is ended. nemar admin repull abandon ${t.dataset_id} ends it as patch_declined (v${t.to_version} stays released and N.0.1 is not made).`),{kind:"done",result:{row:t,outcome:"released"}};if(n===0&&r===0&&s.length===0&&o===0)return lq(e,t,"");if(r>0&&s.length===0&&!e.opts.keepUpstream)return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`an administrator's decision on the ${r} conflict(s) the plan lists, before N.0.1 is made: resolve one to NEMAR's side with --take-ours <path> (or --take-ours dataset_description.json#<Key>), or leave every one on upstream's side with --keep-upstream (the reviewed plan file names them, under conflicts and description.keys)`}};let i=OD(t.to_version);try{let a=await FPt(e,t);oCe(a);let c=sCe(a,s);if(c.corrections!==n)throw new j("patch-plan-mismatch",`The plan lists ${c.corrections} correction(s) and re-pull #${t.id} records ${n}; they are the same plan only when they agree.`);if(c.unresolved>0&&!e.opts.keepUpstream)return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`an administrator's decision on the ${c.unresolved} conflict(s) the plan lists that no --take-ours names, before N.0.1 is made: name each to take NEMAR's side, or add --keep-upstream to leave them on upstream's side`}};if(o!==NCe(a))throw new j("patch-plan-mismatch",`The plan lists ${NCe(a)} pipeline-owned path(s) and re-pull #${t.id} records ${o}; they are the same plan only when they agree.`);if(!Q4(c)&&o===0)return lq(e,t,": the plan has no correction, and every conflict stays on upstream's side");return await HPt(e,t,c,i,{owned:jPt(a),upstreamWins:LPt(a),unowned:FCe(a,"unowned"),edited:FCe(a,"edited")})}catch(a){if(a instanceof j&&!qPt.has(a.code))a.resumable=!0,await eo(t,Os("patch",a),e.opts.out);throw a}}function NCe(e){let t=e.counts?.pipeline_owned;return typeof t==="number"?t:0}function qCe(e){let n=e.pipeline_owned?.paths;if(n===void 0)return[];if(!Array.isArray(n)||!n.every((r)=>r&&typeof r==="object"&&typeof r.path==="string"&&typeof r.upstream_wins==="boolean"))throw new j("plan-schema","The plan's pipeline-owned section does not have the planner's shape.");return n}var jPt=(e)=>new Set(qCe(e).map((t)=>t.path)),LPt=(e)=>new Set(qCe(e).filter((t)=>t.upstream_wins).map((t)=>t.path));function FCe(e,t){let n=e.pipeline_owned?.[t];if(n===void 0)return new Set;if(!Array.isArray(n)||!n.every((r)=>typeof r==="string"))throw new j("plan-schema","The plan's pipeline-owned section does not have the planner's shape.");return new Set(n)}var qPt=new Set(["pipeline-regeneration-failed","take-ours-invalid","declined","plan-unreadable","plan-schema","plan-environment","plan-sources","planner-version","plan-tampered","plan-not-the-record"]),MCe=new Set(["pipeline-run-failed","pipeline-unavailable","pipeline-snapshot"]),jCe=3;async function UPt(e,t,n){return(await ne(e,["diff","--name-only","-z",n,t],{ok:!0})).stdout.split("\x00").some((o)=>o===os||Yy(o))}async function BPt(e,t,n,r,o){if(!await ab(t.dir,r)&&!await Mn(t,r,1))throw tt("origin-unreadable","The new main could not be fetched from NEMAR's repository.");let s=new Map;if(o.edited.size>0&&!await ab(t.dir,n.base_sha))await Mn(t,n.base_sha,1);for(let i of o.edited){let a=await fu(t.dir,n.base_sha,i);if(a!==null)s.set(i,a)}return kCe({unowned:o.unowned,preserve:s,datasetId:e.datasetId,version:n.to_version,commit:r,repo:t.dir,owned:o.owned,upstreamWins:o.upstreamWins,env:e.env})}async function HPt(e,t,n,r,o){let s=await wx(e),{scratch:i}=s;if(s.prefix!==`${e.datasetId}/objects/`)throw new j("destination-prefix",`NEMAR's nemar-s3 is not at ${e.datasetId}/objects/, where the keys N.0.1 replays are read.`);let a=await uu({work:i.dir,baseSha:t.merge_sha,env:i.env,acceptances:!0}),c=jn(r),l=(await lu(i,[c])).get(c),d=()=>new j("branch-foreign",`release/v${r} exists on NEMAR's repository and is not this re-pull's N.0.1 commit with these resolutions${o.owned.size>0?" and this regeneration of the iEEG geometry pipeline's files":""}; run resume with the resolutions the earlier run was given, or decline N.0.1 with nemar admin repull abandon ${e.datasetId}.`),f=()=>tt("pipeline-unavailable-on-resume",`release/v${r} was pushed with iEEG geometry pipeline files that this run did not reproduce (or with other resolutions); resume again with the resolutions the earlier run was given, where the pipeline runs as it did then (its pinned environment), or decline N.0.1 with nemar admin repull abandon ${e.datasetId}.`),p=null;if(l){if(!await Mn(i,c,Lo))throw tt("origin-unreadable",`release/v${r} could not be fetched.`);if(p=await db({dir:i.dir,row:t,head:l}),!p)throw d()}let m=p?p.parent:a,h=o.owned.size>0?await BPt(e,i,t,m,o):null,g=h?.ok&&!SCe(h.files)?h.files:void 0,y=(t.counts.pipeline_attempts??0)+1;if(h&&!h.ok&&MCe.has(h.code)&&y<jCe){let T=`[patch:pipeline-regeneration-failed] The iEEG geometry pipeline could not be run (${h.code}), attempt ${y} of ${jCe}; N.0.1 is not made yet, resume again where the pipeline runs.`;try{await ar(t.id,{from:"released",to:"released",fields:{counts:{pipeline_attempts:y}},error:T})}catch(L){throw Zr(L,"The pipeline attempt could not be recorded")}throw tt("pipeline-regeneration-failed",T.slice(37))}if(p&&o.owned.size>0&&(h===null||!h.ok||!g)){if(await UPt(i.dir,p.commit,m))throw f()}let b=h&&!h.ok?{pipeline_failed:1,...MCe.has(h.code)?{pipeline_attempts:y}:{}}:void 0;if(h&&!h.ok)await eo(t,`[patch:${h.code}] ${h.message} N.0.1 carries none of the previous iEEG geometry pipeline files.`,e.opts.out),e.opts.out(`The iEEG geometry pipeline's files were not regenerated (${h.code}); N.0.1 carries none of the previous ones.`);else if(g)e.opts.out(`Regenerated the iEEG geometry pipeline's files: ${g.write.size} written, ${g.remove.length} removed.`);if(!p&&!Q4(n)&&g===void 0)return lq(e,t,h&&!h.ok?": nothing else is replayed, and the pipeline's files were not regenerated":": nothing is replayed, and the pipeline's files are as the new snapshot leaves them",b);let x=await cCe({scratch:i,row:t,selection:n,parent:m,pipeline:g});if(p&&x.sha!==p.commit)throw o.owned.size>0?f():d();let v=p?p.commit:x.sha,S=x.keys,E;try{E=S.length>0?await Ef(s.aws,s.bucket,s.prefix):new Map}catch(T){if(!(T instanceof Vt))throw T;throw new j("s3-failed",`NEMAR's bucket could not be listed for the keys N.0.1 replays (${vf(T)}); the ambient AWS credentials list it.`)}if(await lCe({dir:i.dir,annexRef:"refs/remotes/origin/heads/git-annex",keys:S,nemarUuid:s.uuid,listing:E}),!l&&e.opts.confirm&&!await e.opts.confirm(`Make v${r} of ${e.datasetId}: replay ${n.paths.length} path(s) and ${n.keys.length} description key(s) onto main (${n.corrections} correction(s), ${n.resolutions} conflict(s) resolved to NEMAR's side, ${n.unresolved} left on upstream's side${g?`; ${g.write.size} iEEG geometry pipeline file(s) written, ${g.remove.length} removed`:""}), push release/v${r} and open its pull request? Its merge will mint one more version DOI, which cannot be withdrawn.`))throw new j("declined","Not confirmed; nothing was pushed.");let A=await iA({work:i.dir,synthSha:v,version:r,push:{versions:[r]},env:i.env});e.opts.out(A.pushed?`Pushed release/v${r} (${v.slice(0,12)}).`:`release/v${r} is already this re-pull's N.0.1 commit${A.head===v?"":" (moved by enrichment)"}.`);let I=await aA({token:e.token,base:e.base,datasetId:e.datasetId,version:r,body:MPt(t,n,r,h),acceptHead:(T)=>ei({work:i.dir,from:v,head:T,ref:c,env:i.env})}),H;try{H=await ar(t.id,{from:"released",to:"patch_synthesized",fields:{patch_version:r,patch_branch:`release/v${r}`,patch_pr_number:I.number,patch_head_sha:I.head,patch_base_sha:m,counts:{resolutions:n.resolutions,...b??{}}}})}catch(T){throw Zr(T,"N.0.1's pull request could not be recorded")}return e.opts.out(`${I.reused?"Found":"Opened"} N.0.1's pull request #${I.number} of release/v${r} (${n.resolutions} conflict(s) resolved to NEMAR's side, ${n.unresolved} left on upstream's side); re-pull #${t.id} is patch_synthesized. Resume never merges.`),{kind:"next",row:H}}async function VPt(e){try{return(await Zo({dataset:e,open:!0,limit:1})).repulls[0]??null}catch(t){throw Zr(t,"The NEMAR API could not list the re-pulls")}}async function _A(e){return _f(()=>WPt(e))}async function WPt(e){let t=e.env??process.env,n=kn(t),r=await Ti(t);if(!r.ok)throw new j("no-github-token",`No GitHub token (${r.reason}): resume reads the pull request with the administrator's own (GH_TOKEN, or gh auth login).`);ou(await Mc(e.datasetId));let o=await VPt(e.datasetId);if(!o){let d=(await Zo({dataset:e.datasetId,limit:1})).repulls[0]??null,f=e.automaticFinish;if(f&&!(d?.id===f.repullId&&d.status==="complete"))throw new j("finish-not-merged",`Re-pull #${f.repullId} is not open: a finish takes up only a merged re-pull.`);return{row:d,outcome:f?"complete":"nothing"}}if(e.automaticFinish)KPt(o,e.automaticFinish.repullId);let s=sr(),i=Jc(s,e.datasetId,o.plan_digest);jo(GPt(i.lock),zPt(s,"repull"));let a=au(i.lock),c=null,l={datasetId:e.datasetId,token:r.token,base:n,env:t,configDir:s,opts:e,origin:async()=>(c??=await cu({configDir:s,datasetId:e.datasetId,digest:o.plan_digest,purpose:"resume",env:t,token:r.token}),c),replaced:new Set,sleep:(d)=>new Promise((f)=>setTimeout(f,d))};if(((e.takeOurs?.length??0)>0||e.keepUpstream)&&o.status.startsWith("patch_"))e.out(`Re-pull #${o.id} is ${o.status}: N.0.1 is already made, so --take-ours and --keep-upstream change nothing now.`);try{return await JPt(l,o)}finally{if(e.acceptMergeTrailers&&!l.mergeTrailersRead)e.out(`--accept-merge-trailers changed nothing: re-pull #${o.id} did not reach a merge's release in this run, where a merge's trailers are read.`);c?.close(),a()}}function KPt(e,t){if(e.id!==t||e.origin!=="automatic")throw new j("repull-mismatch",`The dataset's open re-pull is #${e.id} (origin ${e.origin}); the finish takes up only #${t}, an automatic re-pull.`);if(e.status!=="merged"&&e.status!=="released")throw new j("finish-not-merged",`Re-pull #${e.id} is ${e.status}: a finish takes up only a merged re-pull.`)}async function JPt(e,t){let n=Date.now()+Math.max(0,e.opts.waitMinutes)*60000,r=Math.max(100,e.opts.pollMs??15000),o=t;for(let s=0;;){if(s>20)throw tt("resume-looped",`Re-pull #${o.id} did not settle; run resume again.`);let i=await YPt(e,o);if(i.kind==="done")return i.result;if(i.kind==="next"){o=i.row,s++;continue}if(s=0,Date.now()+r>n)return{row:i.row,outcome:"waiting",waitingFor:i.waitingFor};e.opts.out(`Waiting for ${i.waitingFor}.`),await e.sleep(r);try{o=await PD(i.row.id)}catch(a){throw Zr(a,"The NEMAR API could not read the re-pull")}}}async function YPt(e,t){switch(t.status){case"planned":case"prepared":case"copied":case"registered":throw new j("use-execute",`Re-pull #${t.id} is ${t.status}: it is taken up by nemar admin repull execute <plan-file>, with the plan it was made from.`);case"pr_open":return UCe(e,t,"n0");case"patch_synthesized":return UCe(e,t,"n1");case"gates_clear":return BCe(e,t,"n0");case"patch_gates_clear":return BCe(e,t,"n1");case"merged":return aq(e,t,"n0");case"patch_merged":return aq(e,t,"n1");case"released":{let n=await ICe(e,t);return n.kind==="next"?LCe(e,n.row):n}case"patch_released":return nIt(e,t);default:throw new j("not-built",`Re-pull #${t.id} is ${t.status}, which resume does not take on.`)}}function HCe(e,t){let n=Nn[t];return{pr:t,number:e[n.number],branch:e[n.branch],head:e[n.head],gates:e[n.gates],claimSha:e[n.claimSha],claimedAt:e[n.claimedAt],version:e[n.version],base:t==="n0"?e.base_sha:e.patch_base_sha,anchor:t==="n0"?e.synth_sha:e.patch_head_sha,closedTo:t==="n0"?"abandoned":"patch_declined"}}async function GCe(e,t){let n=await Ks(e.token,e.datasetId,t.number,e.base);if(!n.ok)throw tt("github-unreadable",`Pull request #${t.number} could not be read on GitHub (${n.reason})`);return n.value}async function zCe(e,t,n){let r;try{r=await ND(t.id,n.pr)}catch(s){throw Zr(s,`The merge of pull request #${n.number} could not be recorded`)}let o=[r.merged_outside_tool?"no NEMAR tool held a claim for it":null,r.merged_unscreened_head?"at a head other than the screened one":null].filter(Boolean);return e.opts.out(`Pull request #${n.number} is merged; re-pull #${t.id} records it${o.length>0?` (${o.join(", ")})`:""}.`),{kind:"next",row:r.repull}}async function fb(e,t,n,r){try{return await ar(e.id,{from:e.status,to:t,fields:n})}catch(o){throw Zr(o,r)}}function _x(e,t,n,r){let o={...sq(e)};if(t.pr==="n0"){if(o.head_sha=n,r)o.synth_sha=r.synthSha,o.synth_tree=r.synthTree,o.base_sha=r.baseSha}else if(o.patch_head_sha=n,r)o.patch_base_sha=r.baseSha;return o}async function VCe(e,t,n){let r=await fb(t,n.closedTo,{},"The record could not be ended");return e.opts.out(n.pr==="n0"?`Pull request #${n.number} was closed without being merged: re-pull #${t.id} is abandoned. Plan the dataset again to re-pull it.`:`N.0.1's pull request #${n.number} was closed without being merged: re-pull #${t.id} is patch_declined, and v${t.to_version} stays released; its corrections remain corrections in the next plan.`),{kind:"done",result:{row:r,outcome:"ended"}}}async function WCe(e,t,n){return ei({work:e.dir,from:t.anchor,head:n,ref:jn(t.version),env:e.env})}async function XPt(e,t,n,r){if(n.pr==="n0")return rCe({scratch:e,row:t,head:r});let o=await KCe(e,t,n);if(!o)return null;let s=await uCe({dir:e.dir,row:t,recorded:o,head:r});return s?{synthSha:s.sha,synthTree:s.tree,baseSha:s.baseSha}:null}async function KCe(e,t,n){if(!await Mn(e,n.anchor,Lo))return null;return await Mn(e,t.merge_sha,Lo),(await db({dir:e.dir,row:t,head:n.anchor}))?.commit??null}async function UCe(e,t,n){let r=HCe(t,n),o=await GCe(e,r);if(o.state==="merged")return zCe(e,t,r);if(o.state==="closed")return VCe(e,t,r);if(o.baseRef!=="main"||o.headRef!==r.branch){let g=tt("pr-foreign",`Pull request #${r.number} is not ${r.branch} into main.`);throw await eo(t,Os("gates",g),e.opts.out),g}if(!fa(o.headRepo,t.dataset_id)||!fa(o.baseRepo,t.dataset_id)){let g=tt("pr-foreign",`Pull request #${r.number} is not from and into ${S_}/${t.dataset_id} itself (its head is ${o.headRepo??"a repository GitHub no longer names"}, its base ${o.baseRepo??"a repository GitHub no longer names"}): a fork's pull request is never merged as a re-pull's.`);throw await eo(t,Os("gates",g),e.opts.out),g}if(o.headSha!==r.head){if(e.replaced.has(o.headSha))return{kind:"wait",row:t,waitingFor:"GitHub to show the re-synthesized head"};let g=await e.origin(),y=await WCe(g,r,o.headSha);if(y!=="ok"){let x=await XPt(g,t,r,o.headSha);if(x){let S=await fb(t,t.status,_x(t,r,o.headSha,x),"The re-synthesized commit could not be recorded");return e.opts.out(`${r.branch} holds this re-pull's commit made again on a moved main (${x.synthSha.slice(0,12)}), pushed by an earlier run; re-pull #${t.id} records it.`),{kind:"next",row:S}}let v=y==="unreadable"?tt("branch-unreadable",`Whether the head of ${r.branch} is this re-pull's commit and enrichment's could not be read.`):tt("head-foreign",`${r.branch} holds a commit enrichment does not make: this pull request cannot be merged as it is; end the record with nemar admin repull abandon ${e.datasetId}.`);throw await eo(t,Os("gates",v),e.opts.out),v}let b=await fb(t,t.status,_x(t,r,o.headSha),"The moved head could not be recorded");return e.opts.out(`${r.branch} moved by enrichment to ${o.headSha.slice(0,12)}; re-pull #${t.id} records it.`),{kind:"next",row:b}}let s=await e.origin(),i;try{i=await uu({work:s.dir,baseSha:r.base,env:s.env})}catch(g){if(g instanceof j)g.resumable=!0,await eo(t,Os("gates",g),e.opts.out);throw g}let a=await Fp(e.token,e.datasetId,r.number,{headSha:o.headSha,mergeableState:o.mergeableState},{base:e.base,sleep:e.sleep});if(!a.ok){if(a.kind==="unreadable")throw tt("github-unreadable",`GitHub could not say whether #${r.number} can be merged.`);return{kind:"wait",row:t,waitingFor:`pull request #${r.number} to settle on GitHub`}}let c=a.state,l=i===r.base?[]:await px(s.dir,r.base,i);if(l===null)throw tt("main-unreadable","Whether NEMAR's main moved outside .nemar/ and .github/ could not be read; run resume again.");if(i!==r.base&&(c==="dirty"||c==="behind"||l.length>0))return eIt(e,t,r,i,o.headSha,l.length>0?`enrichment changed ${l.length} path(s) outside .nemar/ and .github/ on it`:`GitHub reports its pull request '${c}'`);let d=await QPt(e,t,r),f=[];if(d!==null)f.push(d);let p=c==="unstable"&&t.origin==="administrator"?await Hj({token:e.token,base:e.base,datasetId:e.datasetId,sha:r.head,origin:t.origin,mergeableState:c,prNumber:r.number}):null;if(c!=="clean"&&p?.kind!=="bids-only")f.push(`GitHub to report pull request #${r.number} clean (it reports '${c}'${p?`: ${p.why}`:""})`);if(f.length>0)return{kind:"wait",row:t,waitingFor:f.join(", and ")};let m=Nn[n],h;try{h=await ar(t.id,{from:m.open,to:m.gatesClear,fields:{[m.gates]:r.head}})}catch(g){let y=xn(g);if(y==="head-moved"||y==="screen-changed")return{kind:"next",row:t};if(y==="screen-not-clear")return{kind:"wait",row:t,waitingFor:"the identifier screen to pass for this head"};throw Zr(g,"The gates could not be recorded")}if(c==="clean")return e.opts.out(`The identifier screen and GitHub pass for ${r.head.slice(0,12)}: re-pull #${t.id} is ${m.gatesClear}.`),{kind:"done",result:{row:h,outcome:"ready"}};return e.opts.out(`The identifier screen passes for ${r.head.slice(0,12)}, and GitHub reports its pull request unstable only because BIDS validation failed: re-pull #${t.id} is ${m.gatesClear}. It merges over the failed validation with a reason, once you have read it, or without one once the validation passes.`),{kind:"done",result:{row:h,outcome:"ready",bidsFailure:!0}}}async function QPt(e,t,n){let r=n.head,o;try{o=await $y(t.id)}catch(i){throw Zr(i,"The identifier screens could not be read")}if(o.exempt)return null;let s=o.screens.find((i)=>i.pr===n.pr&&i.sha===r)??null;if(s===null||s.gate==="rerun"){try{let i=await BEe(t.id,{pr:n.pr,sha:r});if(i.exempt)return null;e.opts.out(`Dispatched the identifier screen of ${r.slice(0,12)}.`),s=i.screen}catch(i){if(xn(i)!=="screen-exists")throw Zr(i,"The identifier screen could not be dispatched");s=i.rawBody?.screen??null}if(s===null||s.gate==="rerun"||s.gate==="wait")return`the identifier screen of ${r.slice(0,12)}`}switch(s.gate){case"clear":return null;case"wait":return`the identifier screen of ${r.slice(0,12)} (running)`;case"blocks":{let i=tt("screen-blocks",`${s.headline}. A direct identifier cannot be acknowledged: this commit is not merged.`);throw await eo(t,Os("gates",i),e.opts.out),i}case"acknowledge":{if(s.acknowledged_at!==null)return null;if(!e.opts.acknowledgment)return`an administrator's reason for the identifier screen (${s.headline}); read it with nemar admin repull status ${e.datasetId}, then run nemar admin repull resume ${e.datasetId} --acknowledge-identifier-screen "<reason>"`;try{await HEe(t.id,{pr:n.pr,sha:r,reason:e.opts.acknowledgment})}catch(i){throw Zr(i,"The acknowledgment could not be recorded")}return e.opts.out(`Recorded your acknowledgment of the identifier screen of ${r.slice(0,12)}.`),null}default:return`the identifier screen of ${r.slice(0,12)}`}}async function ZPt(e,t,n,r,o){let s=await KCe(e,t,n);if(!s)throw new j("origin-unreadable","N.0.1's commit could not be found beneath its recorded head on NEMAR's repository.");let i=await eq({dir:e.dir,commit:s,newMain:r}),a=jn(n.version),c=await Yc(e.dir,[`${i.sha}:${a}`],{versions:[n.version]},e.env,[`--force-with-lease=${a}:${o}`]);if(c.outcome==="rejected")throw new j("branch-moved",`release/v${n.version} moved while it was re-synthesized; nothing was replaced. Run resume again.`);if(c.outcome==="remote-rejected"||c.outcome==="failed")throw new j("push-failed",`The re-synthesized release/v${n.version} could not be pushed (${Li(c.cause)}).`);return{synthSha:i.sha,synthTree:i.tree}}async function eIt(e,t,n,r,o,s){if(e.opts.confirm&&!await e.opts.confirm(`NEMAR's main moved by enrichment since re-pull #${t.id}'s ${n.pr==="n0"?"commit":"N.0.1 commit"} was made, and ${s}. Make the commit again on the new main and push ${n.branch} with a lease (nothing enrichment wrote is undone)?`))throw new j("declined","Not confirmed; nothing was pushed.");let i=await e.origin(),a;try{a=n.pr==="n0"?await nCe({scratch:i,row:t,newMain:r,liveHead:o}):await ZPt(i,t,n,r,o)}catch(l){if(l instanceof j)l.resumable=!0,await eo(t,Os("gates",l),e.opts.out);throw l}e.replaced.add(o);let c=await fb(t,t.status,_x(t,n,a.synthSha,{...a,baseSha:r}),"The re-synthesized commit could not be recorded");return e.opts.out(`Made re-pull #${t.id}'s commit again on the new main (${a.synthSha.slice(0,12)}) and pushed ${n.branch}; its identifier screen runs again for the new head.`),{kind:"next",row:c}}async function BCe(e,t,n){let r=HCe(t,n),o=await GCe(e,r);if(o.state==="merged")return zCe(e,t,r);if(r.claimSha!==null)try{let l=await GEe(t.id,{pr:n,sha:r.claimSha,outcome:"expired"});return e.opts.out(`The claim to merge made at ${r.claimedAt} expired: GitHub says pull request #${r.number} did not merge, and its unit of today's merge cap is free.`),{kind:"next",row:l}}catch(l){let d=xn(l);if(d==="pull-request-merged")return{kind:"next",row:t};if(d==="claim-too-recent")return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`the claim to merge made at ${r.claimedAt} to be resolved: run nemar admin repull merge ${e.datasetId} to send the merge again under it, or resume later to expire it`}};throw Zr(l,"The claim to merge could not be resolved")}if(o.state==="closed")return VCe(e,t,r);if(o.headSha!==r.gates){let l=await e.origin(),d=await WCe(l,r,o.headSha);if(d!=="ok")throw tt(d==="unreadable"?"branch-unreadable":"head-foreign",`${r.branch} moved since its gates were recorded, ${d==="unreadable"?"and whether by enrichment only could not be read":"by a commit enrichment does not make"}.`);let f=await fb(t,Nn[n].open,_x({...t,status:Nn[n].open},r,o.headSha),"The moved head could not be recorded");return e.opts.out(`${r.branch} moved by enrichment since its gates were recorded; re-pull #${t.id} is ${Nn[n].open} again, and its screen runs for the new head.`),{kind:"next",row:f}}let s=await e.origin(),i;try{i=await uu({work:s.dir,baseSha:r.base,env:s.env})}catch(l){if(l instanceof j)l.resumable=!0;throw l}let a=i===r.base?[]:await px(s.dir,r.base,i);if(a===null)throw tt("main-unreadable","Whether NEMAR's main moved outside .nemar/ and .github/ since the gates could not be read; run resume again.");if(a.length>0){let l=Nn[n].open,d=await fb(t,l,_x({...t,status:l},r,o.headSha),"The return to the open pull request could not be recorded");return e.opts.out(`NEMAR's main moved by enrichment since the gates, on ${a.length} path(s) outside .nemar/ and .github/: re-pull #${t.id} is ${l} again, and its commit is made again on the new main.`),{kind:"next",row:d}}let c=await tIt(e,t,r,o);return{kind:"done",result:{row:t,outcome:"ready",...c?{bidsFailure:!0}:{}}}}async function tIt(e,t,n,r){if(t.origin!=="administrator")return!1;let o=await Fp(e.token,e.datasetId,n.number,{headSha:r.headSha,mergeableState:r.mergeableState},{base:e.base,sleep:e.sleep});if(!o.ok||o.state!=="unstable")return!1;return(await Hj({token:e.token,base:e.base,datasetId:e.datasetId,sha:r.headSha,origin:t.origin,mergeableState:o.state,prNumber:n.number})).kind==="bids-only"}async function nIt(e,t){let n;try{n=await ar(t.id,{from:"patch_released",to:"complete"})}catch(r){throw Zr(r,"The record could not be completed")}return e.opts.out(`Re-pull #${t.id} of ${e.datasetId} is complete: v${t.to_version} and v${t.patch_version} are released.`),{kind:"done",result:{row:n,outcome:"complete"}}}wo();var as=(e)=>e?e.slice(0,12):"none";function rIt(e){let t=e.dataset_id;switch(e.status){case"planned":case"prepared":case"copied":case"registered":return"nemar admin repull execute <plan-file> (the reviewed plan this record was made from)";case"pr_open":return`nemar admin repull resume ${t} (the identifier screen and the gates)`;case"gates_clear":return e.merge_claim_sha?`nemar admin repull merge ${t} (sends the merge again under the held claim), or resume ${t} once the claim is old enough to expire`:`nemar admin repull merge ${t} (mints one version DOI, v${e.to_version})`;case"merged":return`nemar admin repull resume ${t} (the release, the lock, then N.0.1 or the end)`;case"released":return typeof e.counts.conflicts==="number"&&e.counts.conflicts>0?`nemar admin repull resume ${t} --take-ours <path> or --keep-upstream (the lock, then N.0.1 or the end; the plan's ${e.counts.conflicts} conflict(s) wait for your decision), or nemar admin repull abandon ${t} (declines N.0.1)`:`nemar admin repull resume ${t} (the lock, then N.0.1 or the end)`;case"patch_synthesized":return`nemar admin repull resume ${t} (N.0.1's identifier screen and gates)`;case"patch_gates_clear":return e.patch_merge_claim_sha?`nemar admin repull merge ${t} (sends N.0.1's merge again under the held claim), or resume ${t} once the claim is old enough to expire`:`nemar admin repull merge ${t} (mints one version DOI, v${e.patch_version})`;case"patch_merged":case"patch_released":return`nemar admin repull resume ${t} (N.0.1's release and the end)`;default:return Aj(e.status)?null:`nemar admin repull resume ${t}`}}function JCe(e,t){let n=[`Re-pull #${e.id} of ${e.dataset_id}: ${e.status} (attempt ${e.attempt}, ${e.origin})`,` Upstream ${e.upstream_ds}: ${e.from_tag} -> ${e.to_tag}, as v${e.to_version} (from v${e.from_version})`,` Plan: ${e.plan_digest} (planner ${e.planner})`,` Base: ${as(e.base_sha)} Commit: ${as(e.synth_sha)} Tree: ${as(e.synth_tree)}`];if(e.pr_number!==null)n.push(` Pull request: #${e.pr_number} of ${e.branch}, head ${as(e.head_sha)}`);if(e.gates_sha)n.push(` Gates clear at: ${as(e.gates_sha)}`);if(e.merge_claim_sha)n.push(` Claim to merge: ${as(e.merge_claim_sha)}, made ${e.merge_claimed_at} UTC`);if(e.merge_sha)n.push(` Merge: ${as(e.merge_sha)}`);if(e.tag_sha)n.push(` Tag v${e.to_version}: ${as(e.tag_sha)}`);if(e.patch_pr_number!==null)n.push(` N.0.1 pull request: #${e.patch_pr_number} of ${e.patch_branch}, head ${as(e.patch_head_sha)}, base ${as(e.patch_base_sha)}`);if(e.patch_gates_sha)n.push(` N.0.1 gates clear at: ${as(e.patch_gates_sha)}`);if(e.patch_merge_claim_sha)n.push(` N.0.1 claim to merge: ${as(e.patch_merge_claim_sha)}, made ${e.patch_merge_claimed_at} UTC`);if(e.patch_merge_sha)n.push(` N.0.1 merge: ${as(e.patch_merge_sha)}`);if(e.patch_tag_sha)n.push(` Tag v${e.patch_version}: ${as(e.patch_tag_sha)}`);if(e.status==="released")n.push(typeof e.counts.locked==="number"?` Objects locked: ${e.counts.locked}`:" Objects locked: not yet (resume applies the lock)");let r=Object.entries(e.counts).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${s}=${i}`);if(r.length>0)n.push(` Counts: ${r.join(", ")}`);if(e.last_error)n.push(` Last error: ${e.last_error}`);if(n.push(` Created ${e.created_at} UTC, updated ${e.updated_at} UTC`),t===null)n.push(" Identifier screens: an xx dataset is not screened");else for(let s of t){let i=s.acknowledged_at!==null?`; acknowledged by administrator #${s.acknowledged_by} at ${s.acknowledged_at} UTC`:"";n.push(` Identifier screen of ${as(s.sha)} (${s.pr}): ${s.headline} (gate: ${s.gate}${s.waiting?", running":""}${i})`);for(let a of s.lines)n.push(` ${a}`)}let o=rIt(e);if(o)n.push(` Next: ${o}`);return n}function YCe(e){return` #${e.id}: ${e.from_tag} -> ${e.to_tag}, attempt ${e.attempt}, ${e.status}${e.terminal_at?` (${e.terminal_at} UTC)`:""}`}ta();wo();wr();Ve();Pr();_n();import{mkdirSync as jFt,mkdtempSync as LFt,readFileSync as qFt,rmSync as x1e}from"fs";import{dirname as UFt,join as _1e}from"path";ta();wo();wr();_n();ya();import{existsSync as uq,mkdirSync as oIt,readFileSync as dq,readdirSync as sIt,renameSync as iIt,rmSync as aIt,statSync as cIt,writeFileSync as fq}from"fs";import{join as Sf}from"path";_p();var XCe="--automatic-dispatch",lIt="run-upstream-repull",QCe=["mode","dataset_id","upstream_ds","from_tag","to_tag","dispatch_id","dispatch_token","cli_version","repull_id"],uIt=new Set(["repull_id"]);function pq(e){return TD.test(e)?Number(e):null}function Cr(e){return new j("dispatch-invalid",`The dispatch's ${e} is not what the Worker sends, so the run does not act on it.`)}function dIt(e){if(e===null||typeof e!=="object"||Array.isArray(e))throw Cr("payload");let t=e,n=QCe;for(let m of Object.keys(t))if(!n.includes(m))throw Cr("set of keys");for(let m of QCe){if(!(m in t)){if(!uIt.has(m))throw Cr("set of keys");continue}if(typeof t[m]!=="string")throw Cr(m)}let r=t,o=r.mode;if(o!=="open"&&o!=="finish")throw Cr("mode");let s=r.dataset_id;if(!/^on\d{6}$/.test(s))throw Cr("dataset_id");let i=r.upstream_ds;if(!/^ds\d{6}$/.test(i))throw Cr("upstream_ds");let{from_tag:a,to_tag:c}=r;if(!qr(a))throw Cr("from_tag");if(!qr(c))throw Cr("to_tag");if(Ur(a,c))throw Cr("tag pair");let l=pq(r.dispatch_id);if(l===null)throw Cr("dispatch_id");let d=null;if(r.repull_id!==void 0){if(d=pq(r.repull_id),d===null)throw Cr("repull_id")}if(o==="finish"&&d===null)throw Cr("repull_id");let f=r.dispatch_token;if(!MEe.test(f))throw Cr("dispatch_token");let p=r.cli_version;if(!Ry.test(p))throw Cr("cli_version");return{mode:o,datasetId:s,upstreamDs:i,fromTag:a,toTag:c,dispatchId:l,repullId:d,token:f,cliVersion:p}}var fIt=1048576;function pIt(e){let t=e.GITHUB_EVENT_PATH,n=()=>new j("runner-failed","No dispatch event file: the automatic mode runs only inside the run-upstream-repull workflow.");if(!t)throw n();let r;try{if(cIt(t).size>fIt)throw Cr("event");r=JSON.parse(dq(t,"utf8"))}catch(s){if(s instanceof j)throw s;if(s.code==="ENOENT")throw n();throw Cr("event")}if(r===null||typeof r!=="object"||Array.isArray(r))throw Cr("event");let o=r;if(o.action!==lIt)throw Cr("event type");return dIt(o.client_payload)}var mIt=/^[a-z][a-z0-9-]{0,31}$/,hIt=/^[a-z][a-z0-9_]{0,31}$/,gIt=/^[a-z0-9_.-]{1,64}$/;function xx(e,t={}){if(!mIt.test(e))return"repull-auto: unprintable-line";let n=[`repull-auto: ${e}`];for(let[r,o]of Object.entries(t)){let s=typeof o==="boolean"?o?"yes":"no":typeof o==="number"?Number.isSafeInteger(o)&&o>=0?String(o):"invalid":o;if(!hIt.test(r)||!gIt.test(s))return"repull-auto: unprintable-line";n.push(`${r}=${s}`)}return n.join(" ")}var xA=null;function vA(){if(xA)return xA;let e=process.stdout.write.bind(process.stdout),t=0,n=(...d)=>{t++;let f=d[d.length-1];if(typeof f==="function")queueMicrotask(()=>f(null));return!0},r=()=>{t++};for(let d of["log","info","warn","error","debug","trace","dir","table"])console[d]=r;process.stdout.write=n,process.stderr.write=n;let o=null,s=null,i=new Map,a=()=>{let d={suppressed:t};for(let[f,p]of i)d[`${f}_s`]=p;return d},c=()=>{let d=s;if(o=d?d.phase:"failed",e(`${xx("quiet",a())}
997
+ `)}async function LCe(e,t){let n=t.counts.corrections,r=t.counts.conflicts,o=t.counts.pipeline_owned??0,s=e.opts.takeOurs??[];if(typeof n!=="number"||typeof r!=="number")return e.opts.out(`Re-pull #${t.id}'s record does not say how many corrections and conflicts its plan has, so it is not completed; it stays released, and it blocks ${t.dataset_id}'s next re-pull until it is ended. nemar admin repull abandon ${t.dataset_id} ends it as patch_declined (v${t.to_version} stays released and N.0.1 is not made).`),{kind:"done",result:{row:t,outcome:"released"}};if(n===0&&r===0&&s.length===0&&o===0)return lq(e,t,"");if(r>0&&s.length===0&&!e.opts.keepUpstream)return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`an administrator's decision on the ${r} conflict(s) the plan lists, before N.0.1 is made: resolve one to NEMAR's side with --take-ours <path> (or --take-ours dataset_description.json#<Key>), or leave every one on upstream's side with --keep-upstream (the reviewed plan file names them, under conflicts and description.keys)`}};let i=OD(t.to_version);try{let a=await FPt(e,t);oCe(a);let c=sCe(a,s);if(c.corrections!==n)throw new j("patch-plan-mismatch",`The plan lists ${c.corrections} correction(s) and re-pull #${t.id} records ${n}; they are the same plan only when they agree.`);if(c.unresolved>0&&!e.opts.keepUpstream)return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`an administrator's decision on the ${c.unresolved} conflict(s) the plan lists that no --take-ours names, before N.0.1 is made: name each to take NEMAR's side, or add --keep-upstream to leave them on upstream's side`}};if(o!==NCe(a))throw new j("patch-plan-mismatch",`The plan lists ${NCe(a)} pipeline-owned path(s) and re-pull #${t.id} records ${o}; they are the same plan only when they agree.`);if(!Q4(c)&&o===0)return lq(e,t,": the plan has no correction, and every conflict stays on upstream's side");return await HPt(e,t,c,i,{owned:jPt(a),upstreamWins:LPt(a),unowned:FCe(a,"unowned"),edited:FCe(a,"edited")})}catch(a){if(a instanceof j&&!qPt.has(a.code))a.resumable=!0,await eo(t,Os("patch",a),e.opts.out);throw a}}function NCe(e){let t=e.counts?.pipeline_owned;return typeof t==="number"?t:0}function qCe(e){let n=e.pipeline_owned?.paths;if(n===void 0)return[];if(!Array.isArray(n)||!n.every((r)=>r&&typeof r==="object"&&typeof r.path==="string"&&typeof r.upstream_wins==="boolean"))throw new j("plan-schema","The plan's pipeline-owned section does not have the planner's shape.");return n}var jPt=(e)=>new Set(qCe(e).map((t)=>t.path)),LPt=(e)=>new Set(qCe(e).filter((t)=>t.upstream_wins).map((t)=>t.path));function FCe(e,t){let n=e.pipeline_owned?.[t];if(n===void 0)return new Set;if(!Array.isArray(n)||!n.every((r)=>typeof r==="string"))throw new j("plan-schema","The plan's pipeline-owned section does not have the planner's shape.");return new Set(n)}var qPt=new Set(["pipeline-regeneration-failed","take-ours-invalid","declined","plan-unreadable","plan-schema","plan-environment","plan-sources","planner-version","plan-tampered","plan-not-the-record"]),MCe=new Set(["pipeline-run-failed","pipeline-unavailable","pipeline-snapshot"]),jCe=3;async function UPt(e,t,n){return(await ne(e,["diff","--name-only","-z",n,t],{ok:!0})).stdout.split("\x00").some((o)=>o===os||Yy(o))}async function BPt(e,t,n,r,o){if(!await ab(t.dir,r)&&!await Mn(t,r,1))throw tt("origin-unreadable","The new main could not be fetched from NEMAR's repository.");let s=new Map;if(o.edited.size>0&&!await ab(t.dir,n.base_sha))await Mn(t,n.base_sha,1);for(let i of o.edited){let a=await fu(t.dir,n.base_sha,i);if(a!==null)s.set(i,a)}return kCe({unowned:o.unowned,preserve:s,datasetId:e.datasetId,version:n.to_version,commit:r,repo:t.dir,owned:o.owned,upstreamWins:o.upstreamWins,env:e.env})}async function HPt(e,t,n,r,o){let s=await wx(e),{scratch:i}=s;if(s.prefix!==`${e.datasetId}/objects/`)throw new j("destination-prefix",`NEMAR's nemar-s3 is not at ${e.datasetId}/objects/, where the keys N.0.1 replays are read.`);let a=await uu({work:i.dir,baseSha:t.merge_sha,env:i.env,acceptances:!0}),c=jn(r),l=(await lu(i,[c])).get(c),d=()=>new j("branch-foreign",`release/v${r} exists on NEMAR's repository and is not this re-pull's N.0.1 commit with these resolutions${o.owned.size>0?" and this regeneration of the iEEG geometry pipeline's files":""}; run resume with the resolutions the earlier run was given, or decline N.0.1 with nemar admin repull abandon ${e.datasetId}.`),f=()=>tt("pipeline-unavailable-on-resume",`release/v${r} was pushed with iEEG geometry pipeline files that this run did not reproduce (or with other resolutions); resume again with the resolutions the earlier run was given, where the pipeline runs as it did then (its pinned environment), or decline N.0.1 with nemar admin repull abandon ${e.datasetId}.`),p=null;if(l){if(!await Mn(i,c,Lo))throw tt("origin-unreadable",`release/v${r} could not be fetched.`);if(p=await db({dir:i.dir,row:t,head:l}),!p)throw d()}let m=p?p.parent:a,h=o.owned.size>0?await BPt(e,i,t,m,o):null,g=h?.ok&&!SCe(h.files)?h.files:void 0,y=(t.counts.pipeline_attempts??0)+1;if(h&&!h.ok&&MCe.has(h.code)&&y<jCe){let T=`[patch:pipeline-regeneration-failed] The iEEG geometry pipeline could not be run (${h.code}), attempt ${y} of ${jCe}; N.0.1 is not made yet, resume again where the pipeline runs.`;try{await ar(t.id,{from:"released",to:"released",fields:{counts:{pipeline_attempts:y}},error:T})}catch(L){throw Zr(L,"The pipeline attempt could not be recorded")}throw tt("pipeline-regeneration-failed",T.slice(37))}if(p&&o.owned.size>0&&(h===null||!h.ok||!g)){if(await UPt(i.dir,p.commit,m))throw f()}let b=h&&!h.ok?{pipeline_failed:1,...MCe.has(h.code)?{pipeline_attempts:y}:{}}:void 0;if(h&&!h.ok)await eo(t,`[patch:${h.code}] ${h.message} N.0.1 carries none of the previous iEEG geometry pipeline files.`,e.opts.out),e.opts.out(`The iEEG geometry pipeline's files were not regenerated (${h.code}); N.0.1 carries none of the previous ones.`);else if(g)e.opts.out(`Regenerated the iEEG geometry pipeline's files: ${g.write.size} written, ${g.remove.length} removed.`);if(!p&&!Q4(n)&&g===void 0)return lq(e,t,h&&!h.ok?": nothing else is replayed, and the pipeline's files were not regenerated":": nothing is replayed, and the pipeline's files are as the new snapshot leaves them",b);let x=await cCe({scratch:i,row:t,selection:n,parent:m,pipeline:g});if(p&&x.sha!==p.commit)throw o.owned.size>0?f():d();let v=p?p.commit:x.sha,S=x.keys,E;try{E=S.length>0?await Ef(s.aws,s.bucket,s.prefix):new Map}catch(T){if(!(T instanceof Vt))throw T;throw new j("s3-failed",`NEMAR's bucket could not be listed for the keys N.0.1 replays (${vf(T)}); the ambient AWS credentials list it.`)}if(await lCe({dir:i.dir,annexRef:"refs/remotes/origin/heads/git-annex",keys:S,nemarUuid:s.uuid,listing:E}),!l&&e.opts.confirm&&!await e.opts.confirm(`Make v${r} of ${e.datasetId}: replay ${n.paths.length} path(s) and ${n.keys.length} description key(s) onto main (${n.corrections} correction(s), ${n.resolutions} conflict(s) resolved to NEMAR's side, ${n.unresolved} left on upstream's side${g?`; ${g.write.size} iEEG geometry pipeline file(s) written, ${g.remove.length} removed`:""}), push release/v${r} and open its pull request? Its merge will mint one more version DOI, which cannot be withdrawn.`))throw new j("declined","Not confirmed; nothing was pushed.");let A=await iA({work:i.dir,synthSha:v,version:r,push:{versions:[r]},env:i.env});e.opts.out(A.pushed?`Pushed release/v${r} (${v.slice(0,12)}).`:`release/v${r} is already this re-pull's N.0.1 commit${A.head===v?"":" (moved by enrichment)"}.`);let I=await aA({token:e.token,base:e.base,datasetId:e.datasetId,version:r,body:MPt(t,n,r,h),acceptHead:(T)=>ei({work:i.dir,from:v,head:T,ref:c,env:i.env})}),H;try{H=await ar(t.id,{from:"released",to:"patch_synthesized",fields:{patch_version:r,patch_branch:`release/v${r}`,patch_pr_number:I.number,patch_head_sha:I.head,patch_base_sha:m,counts:{resolutions:n.resolutions,...b??{}}}})}catch(T){throw Zr(T,"N.0.1's pull request could not be recorded")}return e.opts.out(`${I.reused?"Found":"Opened"} N.0.1's pull request #${I.number} of release/v${r} (${n.resolutions} conflict(s) resolved to NEMAR's side, ${n.unresolved} left on upstream's side); re-pull #${t.id} is patch_synthesized. Resume never merges.`),{kind:"next",row:H}}async function VPt(e){try{return(await Zo({dataset:e,open:!0,limit:1})).repulls[0]??null}catch(t){throw Zr(t,"The NEMAR API could not list the re-pulls")}}async function _A(e){return _f(()=>WPt(e))}async function WPt(e){let t=e.env??process.env,n=kn(t),r=await Ti(t);if(!r.ok)throw new j("no-github-token",`No GitHub token (${r.reason}): resume reads the pull request with the administrator's own (GH_TOKEN, or gh auth login).`);ou(await Mc(e.datasetId));let o=await VPt(e.datasetId);if(!o){let d=(await Zo({dataset:e.datasetId,limit:1})).repulls[0]??null,f=e.automaticFinish;if(f&&!(d?.id===f.repullId&&d.status==="complete"))throw new j("finish-not-merged",`Re-pull #${f.repullId} is not open: a finish takes up only a merged re-pull.`);return{row:d,outcome:f?"complete":"nothing"}}if(e.automaticFinish)KPt(o,e.automaticFinish.repullId);let s=sr(),i=Jc(s,e.datasetId,o.plan_digest);jo(GPt(i.lock),zPt(s,"repull"));let a=au(i.lock),c=null,l={datasetId:e.datasetId,token:r.token,base:n,env:t,configDir:s,opts:e,origin:async()=>(c??=await cu({configDir:s,datasetId:e.datasetId,digest:o.plan_digest,purpose:"resume",env:t,token:r.token}),c),replaced:new Set,sleep:(d)=>new Promise((f)=>setTimeout(f,d))};if(((e.takeOurs?.length??0)>0||e.keepUpstream)&&o.status.startsWith("patch_"))e.out(`Re-pull #${o.id} is ${o.status}: N.0.1 is already made, so --take-ours and --keep-upstream change nothing now.`);try{return await JPt(l,o)}finally{if(e.acceptMergeTrailers&&!l.mergeTrailersRead)e.out(`--accept-merge-trailers changed nothing: re-pull #${o.id} did not reach a merge's release in this run, where a merge's trailers are read.`);c?.close(),a()}}function KPt(e,t){if(e.id!==t||e.origin!=="automatic")throw new j("repull-mismatch",`The dataset's open re-pull is #${e.id} (origin ${e.origin}); the finish takes up only #${t}, an automatic re-pull.`);if(e.status!=="merged"&&e.status!=="released")throw new j("finish-not-merged",`Re-pull #${e.id} is ${e.status}: a finish takes up only a merged re-pull.`)}async function JPt(e,t){let n=Date.now()+Math.max(0,e.opts.waitMinutes)*60000,r=Math.max(100,e.opts.pollMs??15000),o=t;for(let s=0;;){if(s>20)throw tt("resume-looped",`Re-pull #${o.id} did not settle; run resume again.`);let i=await YPt(e,o);if(i.kind==="done")return i.result;if(i.kind==="next"){o=i.row,s++;continue}if(s=0,Date.now()+r>n)return{row:i.row,outcome:"waiting",waitingFor:i.waitingFor};e.opts.out(`Waiting for ${i.waitingFor}.`),await e.sleep(r);try{o=await PD(i.row.id)}catch(a){throw Zr(a,"The NEMAR API could not read the re-pull")}}}async function YPt(e,t){switch(t.status){case"planned":case"prepared":case"copied":case"registered":throw new j("use-execute",`Re-pull #${t.id} is ${t.status}: it is taken up by nemar admin repull execute <plan-file>, with the plan it was made from.`);case"pr_open":return UCe(e,t,"n0");case"patch_synthesized":return UCe(e,t,"n1");case"gates_clear":return BCe(e,t,"n0");case"patch_gates_clear":return BCe(e,t,"n1");case"merged":return aq(e,t,"n0");case"patch_merged":return aq(e,t,"n1");case"released":{let n=await ICe(e,t);return n.kind==="next"?LCe(e,n.row):n}case"patch_released":return nIt(e,t);default:throw new j("not-built",`Re-pull #${t.id} is ${t.status}, which resume does not take on.`)}}function HCe(e,t){let n=Nn[t];return{pr:t,number:e[n.number],branch:e[n.branch],head:e[n.head],gates:e[n.gates],claimSha:e[n.claimSha],claimedAt:e[n.claimedAt],version:e[n.version],base:t==="n0"?e.base_sha:e.patch_base_sha,anchor:t==="n0"?e.synth_sha:e.patch_head_sha,closedTo:t==="n0"?"abandoned":"patch_declined"}}async function GCe(e,t){let n=await Ks(e.token,e.datasetId,t.number,e.base);if(!n.ok)throw tt("github-unreadable",`Pull request #${t.number} could not be read on GitHub (${n.reason})`);return n.value}async function zCe(e,t,n){let r;try{r=await ND(t.id,n.pr)}catch(s){throw Zr(s,`The merge of pull request #${n.number} could not be recorded`)}let o=[r.merged_outside_tool?"no NEMAR tool held a claim for it":null,r.merged_unscreened_head?"at a head other than the screened one":null].filter(Boolean);return e.opts.out(`Pull request #${n.number} is merged; re-pull #${t.id} records it${o.length>0?` (${o.join(", ")})`:""}.`),{kind:"next",row:r.repull}}async function fb(e,t,n,r){try{return await ar(e.id,{from:e.status,to:t,fields:n})}catch(o){throw Zr(o,r)}}function _x(e,t,n,r){let o={...sq(e)};if(t.pr==="n0"){if(o.head_sha=n,r)o.synth_sha=r.synthSha,o.synth_tree=r.synthTree,o.base_sha=r.baseSha}else if(o.patch_head_sha=n,r)o.patch_base_sha=r.baseSha;return o}async function VCe(e,t,n){let r=await fb(t,n.closedTo,{},"The record could not be ended");return e.opts.out(n.pr==="n0"?`Pull request #${n.number} was closed without being merged: re-pull #${t.id} is abandoned. Plan the dataset again to re-pull it.`:`N.0.1's pull request #${n.number} was closed without being merged: re-pull #${t.id} is patch_declined, and v${t.to_version} stays released; its corrections remain corrections in the next plan.`),{kind:"done",result:{row:r,outcome:"ended"}}}async function WCe(e,t,n){return ei({work:e.dir,from:t.anchor,head:n,ref:jn(t.version),env:e.env})}async function XPt(e,t,n,r){if(n.pr==="n0")return rCe({scratch:e,row:t,head:r});let o=await KCe(e,t,n);if(!o)return null;let s=await uCe({dir:e.dir,row:t,recorded:o,head:r});return s?{synthSha:s.sha,synthTree:s.tree,baseSha:s.baseSha}:null}async function KCe(e,t,n){if(!await Mn(e,n.anchor,Lo))return null;return await Mn(e,t.merge_sha,Lo),(await db({dir:e.dir,row:t,head:n.anchor}))?.commit??null}async function UCe(e,t,n){let r=HCe(t,n),o=await GCe(e,r);if(o.state==="merged")return zCe(e,t,r);if(o.state==="closed")return VCe(e,t,r);if(o.baseRef!=="main"||o.headRef!==r.branch){let g=tt("pr-foreign",`Pull request #${r.number} is not ${r.branch} into main.`);throw await eo(t,Os("gates",g),e.opts.out),g}if(!fa(o.headRepo,t.dataset_id)||!fa(o.baseRepo,t.dataset_id)){let g=tt("pr-foreign",`Pull request #${r.number} is not from and into ${S_}/${t.dataset_id} itself (its head is ${o.headRepo??"a repository GitHub no longer names"}, its base ${o.baseRepo??"a repository GitHub no longer names"}): a fork's pull request is never merged as a re-pull's.`);throw await eo(t,Os("gates",g),e.opts.out),g}if(o.headSha!==r.head){if(e.replaced.has(o.headSha))return{kind:"wait",row:t,waitingFor:"GitHub to show the re-synthesized head"};let g=await e.origin(),y=await WCe(g,r,o.headSha);if(y!=="ok"){let x=await XPt(g,t,r,o.headSha);if(x){let S=await fb(t,t.status,_x(t,r,o.headSha,x),"The re-synthesized commit could not be recorded");return e.opts.out(`${r.branch} holds this re-pull's commit made again on a moved main (${x.synthSha.slice(0,12)}), pushed by an earlier run; re-pull #${t.id} records it.`),{kind:"next",row:S}}let v=y==="unreadable"?tt("branch-unreadable",`Whether the head of ${r.branch} is this re-pull's commit and enrichment's could not be read.`):tt("head-foreign",`${r.branch} holds a commit enrichment does not make: this pull request cannot be merged as it is; end the record with nemar admin repull abandon ${e.datasetId}.`);throw await eo(t,Os("gates",v),e.opts.out),v}let b=await fb(t,t.status,_x(t,r,o.headSha),"The moved head could not be recorded");return e.opts.out(`${r.branch} moved by enrichment to ${o.headSha.slice(0,12)}; re-pull #${t.id} records it.`),{kind:"next",row:b}}let s=await e.origin(),i;try{i=await uu({work:s.dir,baseSha:r.base,env:s.env})}catch(g){if(g instanceof j)g.resumable=!0,await eo(t,Os("gates",g),e.opts.out);throw g}let a=await Fp(e.token,e.datasetId,r.number,{headSha:o.headSha,mergeableState:o.mergeableState},{base:e.base,sleep:e.sleep});if(!a.ok){if(a.kind==="unreadable")throw tt("github-unreadable",`GitHub could not say whether #${r.number} can be merged.`);return{kind:"wait",row:t,waitingFor:`pull request #${r.number} to settle on GitHub`}}let c=a.state,l=i===r.base?[]:await px(s.dir,r.base,i);if(l===null)throw tt("main-unreadable","Whether NEMAR's main moved outside .nemar/ and .github/ could not be read; run resume again.");if(i!==r.base&&(c==="dirty"||c==="behind"||l.length>0))return eIt(e,t,r,i,o.headSha,l.length>0?`enrichment changed ${l.length} path(s) outside .nemar/ and .github/ on it`:`GitHub reports its pull request '${c}'`);let d=await QPt(e,t,r),f=[];if(d!==null)f.push(d);let p=c==="unstable"&&t.origin==="administrator"?await Hj({token:e.token,base:e.base,datasetId:e.datasetId,sha:r.head,origin:t.origin,mergeableState:c,prNumber:r.number}):null;if(c!=="clean"&&p?.kind!=="bids-only")f.push(`GitHub to report pull request #${r.number} clean (it reports '${c}'${p?`: ${p.why}`:""})`);if(f.length>0)return{kind:"wait",row:t,waitingFor:f.join(", and ")};let m=Nn[n],h;try{h=await ar(t.id,{from:m.open,to:m.gatesClear,fields:{[m.gates]:r.head}})}catch(g){let y=xn(g);if(y==="head-moved"||y==="screen-changed")return{kind:"next",row:t};if(y==="screen-not-clear")return{kind:"wait",row:t,waitingFor:"the identifier screen to pass for this head"};throw Zr(g,"The gates could not be recorded")}if(c==="clean")return e.opts.out(`The identifier screen and GitHub pass for ${r.head.slice(0,12)}: re-pull #${t.id} is ${m.gatesClear}.`),{kind:"done",result:{row:h,outcome:"ready"}};return e.opts.out(`The identifier screen passes for ${r.head.slice(0,12)}, and GitHub reports its pull request unstable only because BIDS validation failed: re-pull #${t.id} is ${m.gatesClear}. It merges over the failed validation with a reason, once you have read it, or without one once the validation passes.`),{kind:"done",result:{row:h,outcome:"ready",bidsFailure:!0}}}async function QPt(e,t,n){let r=n.head,o;try{o=await $y(t.id)}catch(i){throw Zr(i,"The identifier screens could not be read")}if(o.exempt)return null;let s=o.screens.find((i)=>i.pr===n.pr&&i.sha===r)??null;if(s===null||s.gate==="rerun"){try{let i=await BEe(t.id,{pr:n.pr,sha:r});if(i.exempt)return null;e.opts.out(`Dispatched the identifier screen of ${r.slice(0,12)}.`),s=i.screen}catch(i){if(xn(i)!=="screen-exists")throw Zr(i,"The identifier screen could not be dispatched");s=i.rawBody?.screen??null}if(s===null||s.gate==="rerun"||s.gate==="wait")return`the identifier screen of ${r.slice(0,12)}`}switch(s.gate){case"clear":return null;case"wait":return`the identifier screen of ${r.slice(0,12)} (running)`;case"blocks":{let i=tt("screen-blocks",`${s.headline}. A direct identifier cannot be acknowledged: this commit is not merged.`);throw await eo(t,Os("gates",i),e.opts.out),i}case"acknowledge":{if(s.acknowledged_at!==null)return null;if(!e.opts.acknowledgment)return`an administrator's reason for the identifier screen (${s.headline}); read it with nemar admin repull status ${e.datasetId}, then run nemar admin repull resume ${e.datasetId} --acknowledge-identifier-screen "<reason>"`;try{await HEe(t.id,{pr:n.pr,sha:r,reason:e.opts.acknowledgment})}catch(i){throw Zr(i,"The acknowledgment could not be recorded")}return e.opts.out(`Recorded your acknowledgment of the identifier screen of ${r.slice(0,12)}.`),null}default:return`the identifier screen of ${r.slice(0,12)}`}}async function ZPt(e,t,n,r,o){let s=await KCe(e,t,n);if(!s)throw new j("origin-unreadable","N.0.1's commit could not be found beneath its recorded head on NEMAR's repository.");let i=await eq({dir:e.dir,commit:s,newMain:r}),a=jn(n.version),c=await Yc(e.dir,[`${i.sha}:${a}`],{versions:[n.version]},e.env,[`--force-with-lease=${a}:${o}`]);if(c.outcome==="rejected")throw new j("branch-moved",`release/v${n.version} moved while it was re-synthesized; nothing was replaced. Run resume again.`);if(c.outcome==="remote-rejected"||c.outcome==="failed")throw new j("push-failed",`The re-synthesized release/v${n.version} could not be pushed (${Li(c.cause)}).`);return{synthSha:i.sha,synthTree:i.tree}}async function eIt(e,t,n,r,o,s){if(e.opts.confirm&&!await e.opts.confirm(`NEMAR's main moved by enrichment since re-pull #${t.id}'s ${n.pr==="n0"?"commit":"N.0.1 commit"} was made, and ${s}. Make the commit again on the new main and push ${n.branch} with a lease (nothing enrichment wrote is undone)?`))throw new j("declined","Not confirmed; nothing was pushed.");let i=await e.origin(),a;try{a=n.pr==="n0"?await nCe({scratch:i,row:t,newMain:r,liveHead:o}):await ZPt(i,t,n,r,o)}catch(l){if(l instanceof j)l.resumable=!0,await eo(t,Os("gates",l),e.opts.out);throw l}e.replaced.add(o);let c=await fb(t,t.status,_x(t,n,a.synthSha,{...a,baseSha:r}),"The re-synthesized commit could not be recorded");return e.opts.out(`Made re-pull #${t.id}'s commit again on the new main (${a.synthSha.slice(0,12)}) and pushed ${n.branch}; its identifier screen runs again for the new head.`),{kind:"next",row:c}}async function BCe(e,t,n){let r=HCe(t,n),o=await GCe(e,r);if(o.state==="merged")return zCe(e,t,r);if(r.claimSha!==null)try{let l=await GEe(t.id,{pr:n,sha:r.claimSha,outcome:"expired"});return e.opts.out(`The claim to merge made at ${r.claimedAt} expired: GitHub says pull request #${r.number} did not merge, and its unit of today's merge cap is free.`),{kind:"next",row:l}}catch(l){let d=xn(l);if(d==="pull-request-merged")return{kind:"next",row:t};if(d==="claim-too-recent")return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`the claim to merge made at ${r.claimedAt} to be resolved: run nemar admin repull merge ${e.datasetId} to send the merge again under it, or resume later to expire it`}};throw Zr(l,"The claim to merge could not be resolved")}if(o.state==="closed")return VCe(e,t,r);if(o.headSha!==r.gates){let l=await e.origin(),d=await WCe(l,r,o.headSha);if(d!=="ok")throw tt(d==="unreadable"?"branch-unreadable":"head-foreign",`${r.branch} moved since its gates were recorded, ${d==="unreadable"?"and whether by enrichment only could not be read":"by a commit enrichment does not make"}.`);let f=await fb(t,Nn[n].open,_x({...t,status:Nn[n].open},r,o.headSha),"The moved head could not be recorded");return e.opts.out(`${r.branch} moved by enrichment since its gates were recorded; re-pull #${t.id} is ${Nn[n].open} again, and its screen runs for the new head.`),{kind:"next",row:f}}let s=await e.origin(),i;try{i=await uu({work:s.dir,baseSha:r.base,env:s.env})}catch(l){if(l instanceof j)l.resumable=!0;throw l}let a=i===r.base?[]:await px(s.dir,r.base,i);if(a===null)throw tt("main-unreadable","Whether NEMAR's main moved outside .nemar/ and .github/ since the gates could not be read; run resume again.");if(a.length>0){let l=Nn[n].open,d=await fb(t,l,_x({...t,status:l},r,o.headSha),"The return to the open pull request could not be recorded");return e.opts.out(`NEMAR's main moved by enrichment since the gates, on ${a.length} path(s) outside .nemar/ and .github/: re-pull #${t.id} is ${l} again, and its commit is made again on the new main.`),{kind:"next",row:d}}let c=await tIt(e,t,r,o);return{kind:"done",result:{row:t,outcome:"ready",...c?{bidsFailure:!0}:{}}}}async function tIt(e,t,n,r){if(t.origin!=="administrator")return!1;let o=await Fp(e.token,e.datasetId,n.number,{headSha:r.headSha,mergeableState:r.mergeableState},{base:e.base,sleep:e.sleep});if(!o.ok||o.state!=="unstable")return!1;return(await Hj({token:e.token,base:e.base,datasetId:e.datasetId,sha:r.headSha,origin:t.origin,mergeableState:o.state,prNumber:n.number})).kind==="bids-only"}async function nIt(e,t){let n;try{n=await ar(t.id,{from:"patch_released",to:"complete"})}catch(r){throw Zr(r,"The record could not be completed")}return e.opts.out(`Re-pull #${t.id} of ${e.datasetId} is complete: v${t.to_version} and v${t.patch_version} are released.`),{kind:"done",result:{row:n,outcome:"complete"}}}wo();var as=(e)=>e?e.slice(0,12):"none";function rIt(e){let t=e.dataset_id;switch(e.status){case"planned":case"prepared":case"copied":case"registered":return"nemar admin repull execute <plan-file> (the reviewed plan this record was made from)";case"pr_open":return`nemar admin repull resume ${t} (the identifier screen and the gates)`;case"gates_clear":return e.merge_claim_sha?`nemar admin repull merge ${t} (sends the merge again under the held claim), or resume ${t} once the claim is old enough to expire`:`nemar admin repull merge ${t} (mints one version DOI, v${e.to_version})`;case"merged":return`nemar admin repull resume ${t} (the release, the lock, then N.0.1 or the end)`;case"released":return typeof e.counts.conflicts==="number"&&e.counts.conflicts>0?`nemar admin repull resume ${t} --take-ours <path> or --keep-upstream (the lock, then N.0.1 or the end; the plan's ${e.counts.conflicts} conflict(s) wait for your decision), or nemar admin repull abandon ${t} (declines N.0.1)`:`nemar admin repull resume ${t} (the lock, then N.0.1 or the end)`;case"patch_synthesized":return`nemar admin repull resume ${t} (N.0.1's identifier screen and gates)`;case"patch_gates_clear":return e.patch_merge_claim_sha?`nemar admin repull merge ${t} (sends N.0.1's merge again under the held claim), or resume ${t} once the claim is old enough to expire`:`nemar admin repull merge ${t} (mints one version DOI, v${e.patch_version})`;case"patch_merged":case"patch_released":return`nemar admin repull resume ${t} (N.0.1's release and the end)`;default:return Aj(e.status)?null:`nemar admin repull resume ${t}`}}function JCe(e,t){let n=[`Re-pull #${e.id} of ${e.dataset_id}: ${e.status} (attempt ${e.attempt}, ${e.origin})`,` Upstream ${e.upstream_ds}: ${e.from_tag} -> ${e.to_tag}, as v${e.to_version} (from v${e.from_version})`,` Plan: ${e.plan_digest} (planner ${e.planner})`,` Base: ${as(e.base_sha)} Commit: ${as(e.synth_sha)} Tree: ${as(e.synth_tree)}`];if(e.pr_number!==null)n.push(` Pull request: #${e.pr_number} of ${e.branch}, head ${as(e.head_sha)}`);if(e.gates_sha)n.push(` Gates clear at: ${as(e.gates_sha)}`);if(e.merge_claim_sha)n.push(` Claim to merge: ${as(e.merge_claim_sha)}, made ${e.merge_claimed_at} UTC`);if(e.merge_sha)n.push(` Merge: ${as(e.merge_sha)}`);if(e.tag_sha)n.push(` Tag v${e.to_version}: ${as(e.tag_sha)}`);if(e.patch_pr_number!==null)n.push(` N.0.1 pull request: #${e.patch_pr_number} of ${e.patch_branch}, head ${as(e.patch_head_sha)}, base ${as(e.patch_base_sha)}`);if(e.patch_gates_sha)n.push(` N.0.1 gates clear at: ${as(e.patch_gates_sha)}`);if(e.patch_merge_claim_sha)n.push(` N.0.1 claim to merge: ${as(e.patch_merge_claim_sha)}, made ${e.patch_merge_claimed_at} UTC`);if(e.patch_merge_sha)n.push(` N.0.1 merge: ${as(e.patch_merge_sha)}`);if(e.patch_tag_sha)n.push(` Tag v${e.patch_version}: ${as(e.patch_tag_sha)}`);if(e.status==="released")n.push(typeof e.counts.locked==="number"?` Objects locked: ${e.counts.locked}`:" Objects locked: not yet (resume applies the lock)");let r=Object.entries(e.counts).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${s}=${i}`);if(r.length>0)n.push(` Counts: ${r.join(", ")}`);if(typeof e.counts.pipeline_failed==="number"&&e.counts.pipeline_failed>0)n.push(` Pipeline: regeneration failed; N.0.1 has no pipeline files (attempts ${e.counts.pipeline_attempts??"unknown"})`);if(e.last_error)n.push(` Last error: ${e.last_error}`);if(n.push(` Created ${e.created_at} UTC, updated ${e.updated_at} UTC`),t===null)n.push(" Identifier screens: an xx dataset is not screened");else for(let s of t){let i=s.acknowledged_at!==null?`; acknowledged by administrator #${s.acknowledged_by} at ${s.acknowledged_at} UTC`:"";n.push(` Identifier screen of ${as(s.sha)} (${s.pr}): ${s.headline} (gate: ${s.gate}${s.waiting?", running":""}${i})`);for(let a of s.lines)n.push(` ${a}`)}let o=rIt(e);if(o)n.push(` Next: ${o}`);return n}function YCe(e){return` #${e.id}: ${e.from_tag} -> ${e.to_tag}, attempt ${e.attempt}, ${e.status}${e.terminal_at?` (${e.terminal_at} UTC)`:""}`}ta();wo();wr();Ve();Pr();_n();import{mkdirSync as jFt,mkdtempSync as LFt,readFileSync as qFt,rmSync as x1e}from"fs";import{dirname as UFt,join as _1e}from"path";ta();wo();wr();_n();ya();import{existsSync as uq,mkdirSync as oIt,readFileSync as dq,readdirSync as sIt,renameSync as iIt,rmSync as aIt,statSync as cIt,writeFileSync as fq}from"fs";import{join as Sf}from"path";_p();var XCe="--automatic-dispatch",lIt="run-upstream-repull",QCe=["mode","dataset_id","upstream_ds","from_tag","to_tag","dispatch_id","dispatch_token","cli_version","repull_id"],uIt=new Set(["repull_id"]);function pq(e){return TD.test(e)?Number(e):null}function Cr(e){return new j("dispatch-invalid",`The dispatch's ${e} is not what the Worker sends, so the run does not act on it.`)}function dIt(e){if(e===null||typeof e!=="object"||Array.isArray(e))throw Cr("payload");let t=e,n=QCe;for(let m of Object.keys(t))if(!n.includes(m))throw Cr("set of keys");for(let m of QCe){if(!(m in t)){if(!uIt.has(m))throw Cr("set of keys");continue}if(typeof t[m]!=="string")throw Cr(m)}let r=t,o=r.mode;if(o!=="open"&&o!=="finish")throw Cr("mode");let s=r.dataset_id;if(!/^on\d{6}$/.test(s))throw Cr("dataset_id");let i=r.upstream_ds;if(!/^ds\d{6}$/.test(i))throw Cr("upstream_ds");let{from_tag:a,to_tag:c}=r;if(!qr(a))throw Cr("from_tag");if(!qr(c))throw Cr("to_tag");if(Ur(a,c))throw Cr("tag pair");let l=pq(r.dispatch_id);if(l===null)throw Cr("dispatch_id");let d=null;if(r.repull_id!==void 0){if(d=pq(r.repull_id),d===null)throw Cr("repull_id")}if(o==="finish"&&d===null)throw Cr("repull_id");let f=r.dispatch_token;if(!MEe.test(f))throw Cr("dispatch_token");let p=r.cli_version;if(!Ry.test(p))throw Cr("cli_version");return{mode:o,datasetId:s,upstreamDs:i,fromTag:a,toTag:c,dispatchId:l,repullId:d,token:f,cliVersion:p}}var fIt=1048576;function pIt(e){let t=e.GITHUB_EVENT_PATH,n=()=>new j("runner-failed","No dispatch event file: the automatic mode runs only inside the run-upstream-repull workflow.");if(!t)throw n();let r;try{if(cIt(t).size>fIt)throw Cr("event");r=JSON.parse(dq(t,"utf8"))}catch(s){if(s instanceof j)throw s;if(s.code==="ENOENT")throw n();throw Cr("event")}if(r===null||typeof r!=="object"||Array.isArray(r))throw Cr("event");let o=r;if(o.action!==lIt)throw Cr("event type");return dIt(o.client_payload)}var mIt=/^[a-z][a-z0-9-]{0,31}$/,hIt=/^[a-z][a-z0-9_]{0,31}$/,gIt=/^[a-z0-9_.-]{1,64}$/;function xx(e,t={}){if(!mIt.test(e))return"repull-auto: unprintable-line";let n=[`repull-auto: ${e}`];for(let[r,o]of Object.entries(t)){let s=typeof o==="boolean"?o?"yes":"no":typeof o==="number"?Number.isSafeInteger(o)&&o>=0?String(o):"invalid":o;if(!hIt.test(r)||!gIt.test(s))return"repull-auto: unprintable-line";n.push(`${r}=${s}`)}return n.join(" ")}var xA=null;function vA(){if(xA)return xA;let e=process.stdout.write.bind(process.stdout),t=0,n=(...d)=>{t++;let f=d[d.length-1];if(typeof f==="function")queueMicrotask(()=>f(null));return!0},r=()=>{t++};for(let d of["log","info","warn","error","debug","trace","dir","table"])console[d]=r;process.stdout.write=n,process.stderr.write=n;let o=null,s=null,i=new Map,a=()=>{let d={suppressed:t};for(let[f,p]of i)d[`${f}_s`]=p;return d},c=()=>{let d=s;if(o=d?d.phase:"failed",e(`${xx("quiet",a())}
998
998
  `),d){e(`${xx("report-stands",{phase:d.phase})}
999
999
  `);let{phase:f,code:p}=d;e(`${xx("result",p===void 0?{phase:f}:{phase:f,code:p})}
1000
1000
  `);return}e(`${xx("result",{phase:"failed",code:"runner-failed"})}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nemar-cli",
3
3
  "packageManager": "bun@1.4.3",
4
- "version": "0.10.36-PR2236.2007db0",
4
+ "version": "0.10.36-PR2237.37bd199",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",