nemar-cli 0.10.29-PR2104.e70fa53 → 0.10.30-PR2105.5c13a80

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 hb(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 mb(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([hb(n.stdout,l),hb(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 gb=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 _b(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 vb(e){try{let{exitCode:t,stdout:r,timedOut:n}=await mb(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(yb);return Promise.all(e.map(async([t,r])=>{let{available:n,version:s,timedOut:o}=await vb(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:s,timedOut:o,installInstruction:_b(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)=>yb[i]).filter(Boolean),n=await Promise.all(r.map(async(i)=>{let a=await vb(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:_b(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 yb,ZF,rV=4000;var $b=F(()=>{gb();yb={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 wb;var Eb=F(()=>{wb={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.29-PR2104.e70fa53",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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Eb();ac=wb.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){Tb=e,pr(`Step: ${e}`)}function hB(){xb=!0}function mB(){return xb}function gB(){if(Rb)return;Bl=!0}function yB(){Bl=!1,Rb=!0}function _B(){return Bl}function pr(e){if(Ds)process.stderr.write(`[debug] ${e}
26
+ `))}var yb,ZF,rV=4000;var $b=F(()=>{gb();yb={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 wb;var Eb=F(()=>{wb={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.30-PR2105.5c13a80",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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Eb();ac=wb.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){Tb=e,pr(`Step: ${e}`)}function hB(){xb=!0}function mB(){return xb}function gB(){if(Rb)return;Bl=!0}function yB(){Bl=!1,Rb=!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 Ob(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(kb,Ob)}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(kb,Ob)}function vV(e){return Wl(e)}function bb(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:bb(e.requestBody),responseBody:bb(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 Ab(e){if(Sb.has(e))return{flag:e};for(let t of Sb){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 wV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Ab(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 bV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Ab(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 bV(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(wV(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: ${Tb??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
29
29
  `)}
package/dist/index.js CHANGED
@@ -99,7 +99,7 @@ ${t}`,FGe,MGe,jGe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=NGe.bind(nul
99
99
  `)}var nN=!1;var{spawn:vpt}=globalThis.Bun;function Bf(e,t=[]){let n=e.replace(kpt,'("$1","<redacted>")');for(let r of t)if(r.length>=Ept)n=n.split(r).join("<redacted>");return n}function CS(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 Bfe(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 D(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=vpt({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??Spt)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=ig()?[...CS(n),...t.redact??[]]:[];if(ig()){let y=t.cwd?` (cwd=${t.cwd})`:"";hd(u.dim(Bf(`$ ${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([Bfe(r.stdout,f),Bfe(r.stderr,f),g])}finally{if(c(),s)clearTimeout(s)}if(ig()){if(t.sensitiveOutput)hd(u.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())hd(u.dim(Bf(p.trimEnd(),d)));if(m.trim())hd(u.yellow(Bf(m.trimEnd(),d)))}hd(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 kpt,Ept=8,Spt=120000;var qt=z(()=>{He();kpt=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function Rpt(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function Hfe(e,t=Rpt()){return e.installInstructions[t]}function Dpt(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function Apt(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Cpt}async function Vfe(e){try{let{exitCode:t,stdout:n,timedOut:r}=await D(e.cmd,{timeout:Apt()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:Dpt(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 jb(){let e=Object.entries(Ufe);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await Vfe(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:Hfe(n)}}))}async function zfe(){let t=(await jb()).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 Uf(e){let n=$pt[e].map((i)=>Ufe[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await Vfe(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:Hfe(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 Ufe,$pt,Cpt=4000;var Lb=z(()=>{qt();Ufe={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)"}}},$pt={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 Wfe;var Gfe=z(()=>{Wfe={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.29-PR2104.e70fa53",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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Rs;var Hf=z(()=>{Gfe();Rs=Wfe.version});import{mkdirSync as Tpt,readdirSync as Ppt,unlinkSync as Ipt,writeFileSync as Npt}from"fs";import{join as rN}from"path";function Zfe(){ag=!0}function ul(){return ag}function epe(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Bb(e){Qfe=e,$n(`Step: ${e}`)}function Io(){Yfe=!0}function tpe(){return Yfe}function ce(){if(Xfe)return;sN=!0}function Ub(){sN=!1,Xfe=!0}function npe(){return sN}function $n(e){if(ag)process.stderr.write(`[debug] ${e}
102
+ `))}var Ufe,$pt,Cpt=4000;var Lb=z(()=>{qt();Ufe={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)"}}},$pt={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 Wfe;var Gfe=z(()=>{Wfe={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.30-PR2105.5c13a80",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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Rs;var Hf=z(()=>{Gfe();Rs=Wfe.version});import{mkdirSync as Tpt,readdirSync as Ppt,unlinkSync as Ipt,writeFileSync as Npt}from"fs";import{join as rN}from"path";function Zfe(){ag=!0}function ul(){return ag}function epe(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Bb(e){Qfe=e,$n(`Step: ${e}`)}function Io(){Yfe=!0}function tpe(){return Yfe}function ce(){if(Xfe)return;sN=!0}function Ub(){sN=!1,Xfe=!0}function npe(){return sN}function $n(e){if(ag)process.stderr.write(`[debug] ${e}
103
103
  `)}function Lpt(e){let t={};for(let[n,r]of Object.entries(e))t[n]=jpt.has(n.toLowerCase())?"[REDACTED]":r;return t}function ope(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function oN(e,t,n=0){if(n>Bpt)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>oN(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=oN(o,s,n+1);return r}if(typeof t==="string"){if(qpt.test(e))return"[REDACTED]";return t.replace(rpe,ope)}return t}function iN(e){return e.replace(Upt,"Bearer [REDACTED]").replace(Hpt,"[REDACTED_AWS_KEY]").replace(Vpt,"$1[REDACTED]").replace(zpt,"$1$2=[REDACTED]").replace(rpe,ope)}function Gpt(e){return iN(e)}function Kfe(e,t=Mpt){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(oN("",r))}catch{}if(n=iN(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function TS(e){if(!ag)return;let t=Gpt(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?Lpt(e.requestHeaders):void 0,requestBody:Kfe(e.requestBody),responseBody:Kfe(e.responseBody)};OS.push(n),$n(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=G(n);OS.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),$n(`redaction failed for ${e.method} ${t}: ${r}`)}}async function Wpt(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${Rs}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${G(t)})`)}e.push(""),e.push("Active account:");try{let t=zt();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: ${G(t)})`)}e.push(""),e.push("External tools:");try{let t=await jb();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: ${G(t)})`)}return e}async function aN(){return(await Wpt()).join(`
104
104
  `)}async function spe(){if(!ag||AS!==void 0)return;try{AS=await aN()}catch(e){let t=G(e);AS=`(could not build environment report: ${t})`,$n(`environment snapshot failed: ${t}`)}}function ipe(e){if(Jfe.has(e))return{flag:e};for(let t of Jfe){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 Kpt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=ipe(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 Jpt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=ipe(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function Ypt(e){let t=[];for(let r of Jpt(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 Xpt(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${iN(Kpt(e).join(" "))}`),n.push(""),n.push(AS??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),OS.length===0)n.push(" (none)");else OS.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: ${Qfe??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
105
105
  `)}
@@ -414,7 +414,7 @@ ${s}
414
414
  ${b.message}`,r);if(_)return Wt("message",`The squash message would not carry the re-pull's trailers: ${_}.`);return{ok:!0,check:{row:r,pr:s,version:r[i.version],prNumber:a,head:c,squash:b,heldClaim:r[i.claimSha]===c,warnings:h}}}async function l$t(e,t,n,r,o){let s=await op(e.token,e.datasetId,n,{headSha:r,mergeableState:o},{base:e.base,...e.sleep?{sleep:e.sleep}:{}});if(!s.ok){if(s.kind==="unreadable")return Wt("github",`Pull request #${n} could not be read: ${s.reason} Nothing was claimed or merged.`);return Wt("not-ready",s.kind==="moved"?`Pull request #${n} changed since it was read; run the merge again. Nothing was claimed or merged.`:`Pull request #${n} is no longer open; nothing was claimed or merged.`)}if(s.state==="unstable")return Fke(e,t,n,r);if(s.state==="blocked")return Wt("bids","GitHub reports the pull request blocked: this dataset's rules require BIDS validation, and merging would be a bypass, which a re-pull never uses. Nothing was claimed or merged.");if(s.state==="clean")return Wt("bids","GitHub reports the pull request clean, so no check fails: merge it without --bids-failure-reason. Nothing was claimed or merged.");let i=Ag(s.state);return Wt("github",`${i.ok?"GitHub's state is not unstable.":i.why} Nothing was claimed or merged.`)}async function Fke(e,t,n,r){let o=await $be({token:e.token,base:e.base,datasetId:e.datasetId,sha:r,origin:t.origin,mergeableState:"unstable",prNumber:n});if(o.kind==="bids-only")return null;return o.kind==="unreadable"?Wt("github",`Whether BIDS validation is the one check of #${n} that fails could not be read: ${o.why}. Nothing was claimed or merged.`):Wt("bids",`A merge over a failed BIDS validation is made only while that validation is the one check that fails, and ${o.why}. Nothing was claimed or merged.`)}function Np(e){return e instanceof L?`HTTP ${e.statusCode}`:e instanceof Error?e.message:String(e)}function RD(e,t="n0"){return`This merge mints one irreversible version DOI, v${e[Rn[t].version]}, and takes one unit of today's re-pull merge cap.`}async function l_(e,t,n){let{row:r,prNumber:o}=t,s=await Nke(e.datasetId,o,t.head);if("ok"in s)return{merged:!1,stage:s.stage,reason:s.reason};if(s.kind==="needs_force"&&!e.force)return{merged:!1,stage:"review",reason:s.reason};if(n.confirm){let c=[RD(r,t.pr),...t.warnings];if(!await n.confirm(`${c.join(" ")} Merge pull request #${o} of ${e.datasetId}?`))return{merged:!1,stage:"declined",reason:"Not confirmed; nothing was claimed or merged."}}let i=Ec(e.configDir,e.datasetId,r.plan_digest);vo(o$t(i.lock),s$t(e.configDir,"repull"));let a;try{a=Tl(i.lock)}catch(c){if(!(c instanceof I))throw c;return{merged:!1,stage:"not-ready",reason:`${c.message} A resume or an execution of re-pull #${r.id} runs now; nothing was claimed or merged.`}}try{return await p$t(e,t,n)}finally{a()}}function u$t(e,t){let n=pn(e);if(!(e instanceof L)||e.statusCode===0||e.statusCode>=500)return{merged:!1,stage:"github",claimHeld:!0,reason:`The claim to merge got no usable answer (${Np(e)}), so a claim may be held. Nothing was merged. nemar admin repull resume ${t} reads the record, and expires a claim nothing merged under once it is 30 minutes old.`};let r=`The claim to merge was refused (${n??Np(e)}): ${e.message} Nothing was merged.`;if(n==="merge-cap"||n==="merge-cap-unreadable")return{merged:!1,stage:"cap",reason:r};if(n==="screen-not-clear"||n==="screen-changed")return{merged:!1,stage:"screen",reason:r};if(n?.startsWith("bids-override-"))return{merged:!1,stage:"bids",reason:r};return{merged:!1,stage:"not-ready",reason:r}}function d$t(e,t){let n=pn(e),r=e instanceof Error?e.message:String(e);return{merged:!1,stage:n==="screen-not-clear"?"screen":!(e instanceof L)||e.statusCode===0||e.statusCode>=500||n==="github-unreadable"?"github":"not-ready",claimHeld:!0,reason:`The claim to merge already held was not used (${n??Np(e)}): ${r} Nothing was merged. nemar admin repull resume ${t} reads GitHub, records a merge that happened, and expires the claim once it is 30 minutes old.`}}function f$t(e){if(e.outcome==="refused")return`GitHub refused the merge: ${e.reason}`;if(e.merge)return e.merge.why;return e.status===409?"The pull request changed after the gate read it (its head moved, or it was closed), so the merge was not sent.":`GitHub could not be read at the last look before the merge (${e.status===0?"no answer":`HTTP ${e.status}`}), so the merge was not sent.`}async function p$t(e,t,n){let{row:r,prNumber:o,head:s,pr:i}=t,a=Rn[i],c=e.bidsFailureReason;if(c!==void 0&&t.heldClaim)return{merged:!1,stage:"bids",claimHeld:!0,reason:`A claim to merge ${s.slice(0,12)} is already held, and a merge over a failed BIDS validation is sent only under a claim of its own, which records its reason. Nothing was merged. nemar admin repull resume ${e.datasetId} records a merge that happened, or expires the claim once it is 30 minutes old; then run this again.`};if(c!==void 0){let d=await Fke(e,r,o,s);if(d)return{merged:!1,stage:d.stage,reason:d.reason}}if(!t.heldClaim){try{await rr(r.id,{from:a.gatesClear,to:a.gatesClear,fields:{[a.claimSha]:s},...c!==void 0?{override:{kind:"bids-failure",reason:c}}:{}})}catch(d){return u$t(d,e.datasetId)}if(n.out(`Claimed one unit of today's re-pull merge cap for ${s.slice(0,12)}.`),c!==void 0)n.out("Recorded with the claim: the merge is over a failed BIDS validation, and why.")}else{try{await bbe(r.id,{pr:i,sha:s})}catch(d){return d$t(d,e.datasetId)}n.out(`A claim to merge ${s.slice(0,12)} is already held; the merge is sent again under it.`)}let l=await pw(e.token,e.datasetId,o,s,"squash",{base:e.base,commit:t.squash,...c!==void 0?{state:"unstable"}:{},...e.sleep?{sleep:e.sleep}:{},...n.tries!==void 0?{tries:n.tries}:{}});if(l.ok)try{let d=await Y$(r.id,i);return{merged:!0,row:d.repull,mergeSha:d.repull[a.mergeSha],recorded:!0}}catch(d){return n.out(`GitHub merged pull request #${o}, and the merge could not be recorded yet (${pn(d)??Np(d)}); nemar admin repull resume ${e.datasetId} records it.`),{merged:!0,row:r,mergeSha:null,recorded:!1}}if(l.outcome==="unknown"||l.outcome==="different")return{merged:!1,stage:"github",outcome:l.outcome,claimHeld:!0,reason:`${l.reason} GitHub may have merged it: the claim is kept, and nemar admin repull resume ${e.datasetId} reads GitHub and records the merge.`};return{merged:!1,stage:"github",outcome:l.outcome,claimHeld:!0,reason:`${f$t(l)} The claim to merge is kept: run nemar admin repull merge ${e.datasetId} again within 25 minutes of the claim to send the merge under it, once GitHub reports the pull request clean at the same head; if the head moved, nemar admin repull resume ${e.datasetId} expires the claim once it is 30 minutes old and then records the new head.`}}ze();fn();import{dirname as J$t,join as Y$t}from"path";no();xr();_l();var{spawn:Mke}=globalThis.Bun;var CD=1048576,m$t=1024*CD,zrn=5*CD,Grn=8*CD,Wrn=5*CD,jke=4*m$t,Lke=1e4;var h$t={failed:1,usage:2,refused:3,unreadable:4,remainder:5};class qke extends Error{word;exitCode;constructor(e,t=h$t.failed){super(e);this.word=e;this.exitCode=t;this.name="StageError"}}class Bt extends Error{code;op;constructor(e,t){super(`${t}:${e}`);this.code=e;this.op=t;this.name="AwsCliError"}}var g$t={AccessDenied:"access-denied","403":"access-denied",NoSuchKey:"not-found",NoSuchVersion:"not-found",NoSuchObjectLockConfiguration:"not-found",NotFound:"not-found","404":"not-found",NoSuchUpload:"no-such-upload",PreconditionFailed:"precondition-failed","412":"precondition-failed",ConditionalRequestConflict:"precondition-failed",InvalidRange:"invalid-range","416":"invalid-range",SlowDown:"throttled",Throttling:"throttled",ThrottlingException:"throttled",RequestLimitExceeded:"throttled","503":"throttled",ExpiredToken:"credentials",InvalidAccessKeyId:"credentials",InvalidToken:"credentials",SignatureDoesNotMatch:"credentials","401":"credentials"};function y$t(e,t){return new Bt(g$t[e]??"failed",t)}function b$t(e,t){let n=/An error occurred \(([A-Za-z0-9]+)\) when calling the (\w+) operation/.exec(e);if(n)return y$t(n[1],n[2]);if(/Could not connect to the endpoint URL|Connection was closed|Read timeout/.test(e))return new Bt("unreachable",t);if(/Unable to locate credentials|SSO session|token has expired/i.test(e))return new Bt("credentials",t);return new Bt("failed",t)}function Gd(e){if(e instanceof qke)return e.word;if(e instanceof Bt)return`${e.op}:${e.code}`;return"unexpected"}var DD=new Set;var AD=120000,w$t=5;function OD(e={}){let t=e.command??["aws","configure","export-credentials","--format","process"],n=e.skewMs??120000,r=e.now??Date.now,o=e.timeoutMs??60000,s,i;async function a(){let c;try{c=Mke({cmd:t,...e.commandEnv?{env:e.commandEnv}:{},stdout:"pipe",stderr:"ignore"})}catch{throw new Bt("credentials","ExportCredentials")}DD.add(c);let l=setTimeout(()=>c.kill("SIGKILL"),o),d,f;try{[d,f]=await Promise.all([new Response(c.stdout).text(),c.exited])}finally{clearTimeout(l),DD.delete(c)}if(f!==0)throw new Bt("credentials","ExportCredentials");let p;try{p=JSON.parse(d)}catch{throw new Bt("bad-output","ExportCredentials")}let m=typeof p.AccessKeyId==="string"?p.AccessKeyId:"",h=typeof p.SecretAccessKey==="string"?p.SecretAccessKey:"",g=typeof p.SessionToken==="string"?p.SessionToken:"";if(!m||!h)throw new Bt("bad-output","ExportCredentials");if(!m.startsWith("ASIA")||!g)throw new Bt("long-lived-credentials","ExportCredentials");let y=typeof p.Expiration==="string"?Date.parse(p.Expiration):Number.NaN,b={AWS_ACCESS_KEY_ID:m,AWS_SECRET_ACCESS_KEY:h,AWS_SESSION_TOKEN:g};return s={env:b,expiresAt:Number.isFinite(y)?y:r()+n*2},b}return{async env(){if(s&&s.expiresAt-n>r())return s.env;return i??=a().finally(()=>{i=void 0}),i}}}var _$t="when_supported";function TD(e){let t={};for(let[n,r]of Object.entries(e.env??process.env))if(r!==void 0)t[n]=r;if(t.AWS_PAGER="",t.AWS_REQUEST_CHECKSUM_CALCULATION=_$t,e.endpointUrl)t.AWS_ENDPOINT_URL_S3=e.endpointUrl;return{async api(n,r,o={}){let s=n.split("-").map((p)=>p.charAt(0).toUpperCase()+p.slice(1)).join(""),i=["aws","s3api",n,...r,"--region",e.region,"--output","json"],a=e.credentials?await e.credentials.env():{},c;try{c=Mke({cmd:i,env:{...t,...a},stdout:"pipe",stderr:"pipe"})}catch{throw new Bt("spawn-failed",s)}DD.add(c);let l=e.timeoutMs*(o.slow?w$t:1),d=!1,f=setTimeout(()=>{d=!0,c.kill("SIGKILL")},l);try{let[p,m,h]=await Promise.all([new Response(c.stdout).text(),new Response(c.stderr).text(),c.exited]);if(d)throw new Bt("timeout",s);if(h!==0)throw b$t(m,s);let g=p.trim();if(g==="")return{};try{let y=JSON.parse(g);if(typeof y!=="object"||y===null||Array.isArray(y))throw new Bt("bad-output",s);return y}catch(y){if(y instanceof Bt)throw y;throw new Bt("bad-output",s)}}finally{clearTimeout(f),DD.delete(c)}}}}async function Bke(e,t,n,r=()=>!1){let o=Array(e.length).fill(void 0),s=0,i=async()=>{while(s<e.length&&!r()){let a=s++;o[a]=await n(e[a],a)}};return await Promise.all(Array.from({length:Math.max(1,t)},i)),o}no();yo();import{chmodSync as x$t,rmSync as v$t,writeFileSync as k$t}from"fs";import{join as E$t}from"path";ps();var S$t=5368709120,Hke="us-east-1",$$t=8;function PD(e,t){return`${e}/staging/repull-${t}.json`}var Ml=(e)=>typeof e==="string"?e:void 0;async function Wd(e,t,n){let r=new Map,o=new Set,s=null;for(;;){let i=await e.api("list-objects-v2",["--bucket",t,"--prefix",n,"--max-keys","1000","--no-paginate",...s?["--continuation-token",s]:[]]),a=i.Contents;if(a!==void 0&&!Array.isArray(a))throw new Bt("bad-output","ListObjectsV2");for(let c of a??[]){let l=Ml(c.Key);if(l===void 0||typeof c.Size!=="number")throw new Bt("bad-output","ListObjectsV2");if(l.startsWith(n)&&l.length>n.length)r.set(l.slice(n.length),c.Size)}if(i.IsTruncated!==!0)return r;if(s=Ml(i.NextContinuationToken)??null,!s||o.has(s))throw new Bt("bad-output","ListObjectsV2");o.add(s)}}async function Vke(e){let t=E$t(e.dir,"staging-manifest.json");k$t(t,hc(e.manifest),{mode:384}),x$t(t,384);try{await e.aws.api("put-object",["--bucket",e.bucket,"--key",e.key,"--body",t,"--content-type","application/json"])}finally{v$t(t,{force:!0})}}async function Uke(e,t,n,r){let o;try{o=await e.api("head-object",["--bucket",t,"--key",n,...r?["--version-id",r]:[]])}catch(i){if(i instanceof Bt&&i.code==="not-found")return null;throw i}let s=Ml(o.ETag);if(typeof o.ContentLength!=="number"||s===void 0)throw new Bt("bad-output","HeadObject");return{size:o.ContentLength,etag:s,versionId:Ml(o.VersionId)}}function R$t(e){return`${e.bucket}/${e.object}?versionId=${e.version}`}function D$t(e,t){return Math.max(t,Math.ceil(e/Lke))}async function C$t(e){let{aws:t,bucket:n,key:r}=e,o=await t.api("create-multipart-upload",["--bucket",n,"--key",r]),s=Ml(o.UploadId);if(!s)throw new Bt("bad-output","CreateMultipartUpload");try{let i=D$t(e.size,e.partBytes),a=[];for(let c=0,l=1;c<e.size;c+=i,l++){let d=Math.min(c+i,e.size)-1,f=await t.api("upload-part-copy",["--bucket",n,"--key",r,"--upload-id",s,"--part-number",String(l),"--copy-source",e.source,"--copy-source-range",`bytes=${c}-${d}`,"--copy-source-if-match",e.etag],{slow:!0}),p=f.CopyPartResult,m=p?Ml(p.ETag):void 0;if(!m)throw new Bt("bad-output","UploadPartCopy");if(Ml(f.CopySourceVersionId)!==e.version)throw new I("pin-version-mismatch",`S3 copied part ${l} of a multipart copy from another version than the pinned one`);a.push({ETag:m,PartNumber:l})}await t.api("complete-multipart-upload",["--bucket",n,"--key",r,"--upload-id",s,"--multipart-upload",JSON.stringify({Parts:a})],{slow:!0})}catch(i){try{await t.api("abort-multipart-upload",["--bucket",n,"--key",r,"--upload-id",s])}catch{e.open.push({key:r,uploadId:s})}throw i}}async function A$t(e,t,n,r){let o=Ml(r.VersionId);if(o===void 0)return!1;try{return await e.api("delete-object",["--bucket",t,"--key",n,"--version-id",o]),!0}catch{return!1}}function O$t(e){if(e instanceof I)return e;if(e instanceof Ke)return new I("write-refused",e.message);if(e instanceof Bt){if(e.op==="CopyObject"||e.op==="UploadPartCopy"){if(e.code==="not-found")return new I("pin-absent","a pinned upstream version is no longer served");if(e.code==="precondition-failed")return new I("pin-changed","a pinned upstream version changed its ETag")}return new I("copy-failed",`an S3 call failed (${Gd(e)})`)}return new I("copy-failed",`a copy failed (${e instanceof Error?e.name:"error"})`)}async function zke(e){let t=e.singleCopyMax??S$t,n=e.partBytes??jke,r=0,o=0,s=0,i=[],a=[],c=e.manifest.items;if(await Bke(c,e.concurrency??$$t,async(l)=>{try{let d=qo(l.key),f=e.existing.get(l.key);if(d!==null&&f===d){o++;return}let p=await Uke(e.aws.source,l.bucket,l.object,l.version);if(!p)throw new I("pin-absent","a pinned upstream version is not served");if(p.versionId!==l.version)throw new I("pin-version-mismatch","upstream answered for another version than the pinned one, or for none");if(d!==null&&p.size!==d)throw new I("pin-size-mismatch","a pinned upstream version is not the size its key declares");if(d===null&&f===p.size){o++;return}let m=`${e.prefix}${l.key}`,h=R$t(l);if(p.size<=t){let y=await e.aws.dest.api("copy-object",["--bucket",e.destBucket,"--key",m,"--copy-source",h,"--copy-source-if-match",p.etag,"--tagging-directive","REPLACE"],{slow:!0});if(Ml(y.CopySourceVersionId)!==l.version){let b=await A$t(e.aws.dest,e.destBucket,m,y);throw new I("pin-version-mismatch",b?"S3 copied from another version than the pinned one; the copy was removed":"S3 copied from another version than the pinned one and the copy could not be removed: delete it by hand before a rerun")}}else await C$t({aws:e.aws.dest,source:h,version:l.version,etag:p.etag,size:p.size,bucket:e.destBucket,key:m,partBytes:n,open:a});let g=await Uke(e.aws.dest,e.destBucket,m);if(!g||g.size!==p.size)throw new I("copy-size-mismatch","a copied object is not the size of the version it was copied from");r++,s+=p.size}catch(d){i.push(O$t(d))}},()=>i.length>0),i.length>0){let l=i[0],d=a.length>0?` ${a.length} multipart upload(s) could not be aborted and stay open (abort them with abort-multipart-upload): ${a.map((f)=>f.uploadId).join(", ")}.`:"";throw new I(l.code,`The copy stopped: ${l.message}; ${i.length} of ${c.length} item(s) refused, ${r} copied and ${o} already present this run. Nothing is registered for a partial copy, and a rerun skips what landed.${d}`)}return{copied:r,skipped:o,bytes:s}}import{createHash as j$t}from"crypto";import{readFileSync as L$t}from"fs";import{join as q$t}from"path";no();oc();sc();ze();Ng();no();ze();ze();function gs(e,t){if(t instanceof I)return`[${e}:${t.code}] ${t.message}`.slice(0,2000);let n=t instanceof Error?t.name:"unknown";return`[${e}:${e}-failed] The step failed (${n}).`}function ot(e,t){let n=new I(e,t);return n.resumable=!0,n}function so(e,t){let n=pn(e)??(e instanceof L?"record-refused":"github-failed"),r=e instanceof Error?e.message:String(e);return ot(n,`${t}: ${r}`)}function hj(e){if(e.status==="pr_open")return{branch:e.branch,pr_number:e.pr_number,head_sha:e.head_sha};if(e.status==="patch_synthesized")return{patch_version:e.patch_version,patch_branch:e.patch_branch,patch_pr_number:e.patch_pr_number,patch_head_sha:e.patch_head_sha,patch_base_sha:e.patch_base_sha};return{}}async function io(e,t,n){let r=hj(e);try{await rr(e.id,{from:e.status,to:e.status,fields:r,error:t})}catch(o){n(`The failure could not be recorded on re-pull #${e.id} (${pn(o)??(o instanceof L?`HTTP ${o.statusCode}`:"no answer")}); its record keeps the last error it had.`)}}function jl(e,t){return new I(e,`${t} Nothing was accepted or written.`)}var T$t=new Set(["github-unreadable","attestation-unwritten"]),P$t=new Set([0,408,429]);function Wke(e,t){let n=pn(e);if(n===void 0&&e instanceof L&&[404,405].includes(e.statusCode)){let i=new I("accept-route-missing",`${t}: this Worker has no acceptance route (it is older than the CLI), so nothing was sent that acts.`);return i.resumable=!1,i}let r=e instanceof Error?e.message:String(e),o=n===void 0?!(e instanceof L)||P$t.has(e.statusCode)||e.statusCode>=500:T$t.has(n),s=new I(n??(e instanceof L?"record-refused":"api-unreadable"),`${t}: ${r}`);return s.resumable=o,s}var an=(e)=>e.slice(0,12);async function gj(e,t){let n=await ee(e.dir,["cat-file","blob",`${t}:${In}`],{ok:!0});return n.exitCode===0?n.stdout:null}async function I$t(e,t){let n=await ee(e.dir,["rev-list","--parents","-n","1",t],{ok:!0});if(n.exitCode!==0)return null;return n.stdout.trim().split(" ").slice(1)}async function Gke(e,t,n){for(let r of[t,...n])if(await Qn(e,r,ko+1)){if((await ee(e.dir,["cat-file","-e",`${t}^{commit}`],{ok:!0})).exitCode===0)return!0}return!1}async function N$t(e,t,n,r){let o=Rn[r],s=n[o.mergeSha],i=n[o.number],a=n[o.branch];if(n.origin!=="administrator")throw jl("accept-automatic",`Re-pull #${n.id} was opened by the automatic path, whose merges the Worker sends with the trailers; its merge is not accepted without them.`);let c=await Cs(e.token,e.datasetId,i,e.base);if(!c.ok)throw ot("github-unreadable",`Pull request #${i} could not be read on GitHub (${c.reason}); nothing was accepted.`);let l=c.value;if(l.baseRef!=="main"||l.headRef!==a||!Gi(l.headRepo,n.dataset_id)||!Gi(l.baseRepo,n.dataset_id))throw jl("pr-foreign",`Pull request #${i} is not ${a} into main of ${mw}/${n.dataset_id} itself.`);if(l.state!=="merged"||l.mergeCommitSha!==s)throw jl("merge-mismatch",l.state==="merged"?`GitHub says pull request #${i} merged as ${l.mergeCommitSha?an(l.mergeCommitSha):"no commit it names"}, not the recorded ${an(s)}.`:`GitHub says pull request #${i} is not merged.`);if(!await Gke(t,s,["refs/heads/main"]))throw ot("merge-unreadable",`The merge commit ${an(s)} could not be fetched from NEMAR's repository; nothing was accepted.`);let d=await I$t(t,s);if(d===null)throw ot("merge-unreadable",`The merge commit ${an(s)} could not be read.`);if(d.length!==1)throw jl("merge-not-squash",`The merge commit ${an(s)} has ${d.length} parents; a squash merge has one.`);let f=d[0],p=r==="n0"?n.base_sha:n.patch_base_sha;if(f!==p){let b=await Is(t.dir,p,f);if(!b.ok){if(b.code==="unreadable")throw ot("main-unreadable",`Whether the merge commit's parent ${an(f)} moved from the record's base ${an(p)} by enrichment only could not be read; nothing was accepted.`);throw jl("merge-parent-foreign",`The merge commit's parent ${an(f)} is not the record's base ${an(p)} or a commit enrichment moved it to.`)}}let m=n[o.head];if(l.headSha!==m){let _=await Gke(t,l.headSha,[Cn(n[o.version]),`refs/pull/${i}/head`])?await Is(t.dir,m,l.headSha):{ok:!1,code:"unreadable"};if(!_.ok){if(_.code==="unreadable")throw ot("branch-unreadable",`Whether the merged head ${an(l.headSha)} is the recorded head ${an(m)} moved by enrichment could not be read; nothing was accepted.`);throw jl("merge-head-foreign",`Pull request #${i} merged at ${an(l.headSha)}, which is not the recorded head ${an(m)} or a commit enrichment moved it to.`)}}let h=r==="n0"?n.synth_sha:n.patch_gates_sha;if(h===null)throw jl("tree-anchor-missing",`Re-pull #${n.id} records no gated head of its N.0.1 pull request, so the merged tree has nothing to be compared with.`);let g=await ID(t,n,s,r);if(g!=="same"){if(g==="differs")throw jl("merge-tree-mismatch",`The merge commit's tree is not the re-pull's ${r==="n0"?"commit":"gated N.0.1 head"} ${an(h)} outside .nemar/ and .github/.`);throw ot("origin-unreadable","The merge commit or the re-pull's commit could not be read from NEMAR's repository, so the trees were not compared; nothing was accepted.")}let y=i6(await gj(t,f),await gj(t,s));if(y.kind==="other")throw jl("merge-ledger-foreign","The merge commit changes the privacy ledger other than by appending a scrub's lines, which the fresh-clone proof refuses whatever is accepted.");return{number:i,branch:a,mergedHead:l.headSha,headMoved:l.headSha!==m,parent:f,parentMoved:f!==p,anchor:h,ledger:Obe(y)}}function F$t(e,t,n){let r=Rn[t],o=e[r.head],s=t==="n0"?e.base_sha:e.patch_base_sha;return["Verified by this run, with your GitHub token and NEMAR's repository:",` - it is GitHub's squash merge of pull request #${n.number} (${n.branch} into main of ${mw}/${e.dataset_id}), merged at ${an(n.mergedHead)}, ${n.headMoved?`which enrichment moved the recorded head ${an(o)} to`:"the recorded head"};`,` - its one parent ${an(n.parent)} is ${n.parentMoved?`the record's base ${an(s)} moved by enrichment only`:"the record's base"};`,` - its tree is the re-pull's ${t==="n0"?"commit":"gated N.0.1 head"} ${an(n.anchor)} outside .nemar/ and .github/;`,` - it ${Kke(n.ledger)};`," - the re-pull is one an administrator opened.","Asking the Worker to read it again on GitHub and to record your acceptance."]}function Kke(e){return e==="untouched"?"does not touch the privacy ledger":e==="scrub-lines"?"appends only a scrub's lines to the privacy ledger":"appends the delta scrub's repull-scrubbed line to the privacy ledger and edits no line before it"}function M$t(e){return`The Worker read on GitHub with its own credential: pull request #${e.pull_request} merged at ${an(e.merged_head)}${e.head_moved_by_enrichment?" (moved by enrichment)":""}, parent ${an(e.parent)}${e.parent_moved_by_enrichment?" (moved by enrichment)":""}, tree ${an(e.tree)}, the re-pull's outside .nemar/ and .github/; the merge ${Kke(e.ledger)}; and the re-pull is yours.`}async function Jke(e,t,n){if(!await Qn(e,"refs/heads/main",1))throw ot("origin-unreadable","NEMAR's main could not be fetched to read the acceptance's ledger line back; run resume again.");let r=await gj(e,"refs/remotes/origin/heads/main");if(r===null||!a6(r).includes(t)||!ml(r).includes(n))throw ot("attestation-unseen",`The Worker answered that the ledger line naming ${an(t)} is on main, and NEMAR's repository does not show it; run resume again, which reads main again and writes the line once more if it is not there.`)}function Yke(e,t,n){return n===null?"The merge appends no repull-scrubbed line beside other files, so the privacy ledger's fresh-clone proof needs no line for it, and none was written.":`The line that names ${an(e)} is on main in ${In}${t.attestation_sha?` (commit ${an(t.attestation_sha)})`:""}, so the privacy ledger's fresh-clone proof reads the merge as the re-pull's own.`}async function Xke(e,t,n,r,o){let s=n[Rn[r].mergeSha],i;try{i=await ZF(n.id,{pr:r,merge_sha:s})}catch(c){if(pn(c)==="merge-trailers-not-accepted")return!1;throw Wke(c,`The merge commit ${an(s)} carries no trailers (${o}); asked for an acceptance recorded earlier, the Worker answered`)}let a=i.acceptance;if(i.attestation_line!==null)await Jke(t,s,i.attestation_line);if(e.opts.out(`The merge commit ${an(s)} on main carries no trailers (${o}); it was accepted earlier, by administrator #${a.accepted_by} at ${a.accepted_at}, on the reason: ${a.reason}`),e.opts.out(Yke(s,a,i.attestation_line)),e.opts.acceptMergeTrailers)e.opts.out("It is accepted once; --accept-merge-trailers changes nothing now.");return!0}async function Qke(e,t,n,r,o,s){let i=n[Rn[r].mergeSha],a=e.opts.out;a(`The merge commit ${an(i)} on main does not end with the re-pull commit's two trailers (${o}).`);let c=await N$t(e,t,n,r);for(let d of F$t(n,r,c))a(d);let l;try{l=await ZF(n.id,{pr:r,merge_sha:i,reason:s})}catch(d){throw Wke(d,"The Worker answered")}if(l.evidence)a(M$t(l.evidence));if(a(`Accepted on your reason, and recorded on re-pull #${n.id}: ${l.acceptance.reason}`),l.attestation_line!==null)await Jke(t,i,l.attestation_line);a(Yke(i,l.acceptance,l.attestation_line))}async function Zke(e,t){let n=await ee(e,["ls-tree","-r","-z","--full-tree",t],{ok:!0});if(n.exitCode!==0)return null;return n.stdout.split("\x00").filter(Boolean).map((r)=>/^(\d{6}) [a-z]+ ([0-9a-f]{40})\t(.+)$/s.exec(r)).filter((r)=>r!==null).filter((r)=>!r[3].startsWith(".nemar/")&&!r[3].startsWith(".github/")).map((r)=>`${r[1]} ${r[2]} ${r[3]}`).sort().join(`
415
415
  `)}async function ID(e,t,n,r){let o=Rn[r],s=r==="n0"?t.synth_sha:t[o.gates];if(!await Qn(e,n,1))return"tag-unread";let i=async()=>(await ee(e.dir,["cat-file","-e",`${s}^{commit}`],{ok:!0})).exitCode===0;if(!await i()){for(let l of[s,Cn(t[o.version]),`refs/pull/${t[o.number]}/head`])if(await Qn(e,l,ko)&&await i())break}if(!await i())return"commit-unread";let a=await Zke(e.dir,n),c=await Zke(e.dir,s);if(a===null||c===null)return"tag-unread";return a===c?"same":"differs"}async function B$t(e,t,n,r){let o=await ID(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 U$t(e,t,n,r){let o=await ID(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"?ot("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>".`):ot("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 io(n,gs("release",i),e.opts.out),i}async function H$t(e,t){return(await Kf(e)).versions.some((r)=>r.version===t||r.version===`v${t}`)}async function V$t(e,t,n,r,o){let s=n[Rn[r].mergeSha];if(e.mergeTrailersRead=!0,!await Qn(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 ee(t.dir,["cat-file","commit",s],{ok:!0}),a=i.stdout.indexOf(`
416
416
 
417
- `);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 Fl(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 yj(e,t,n){let r=t[Rn[n].version],o=`refs/tags/v${r}`,s=t[Rn[n].mergeSha],i=await e.origin(),a=async(h,g)=>{let y=ot(h,g);return await io(t,gs("release",y),e.opts.out),y},c=await V$t(e,i,t,n,a),l=!1;if(c!==null){if(l=await Xke(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, 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 Il(i,[o])).get(o)}catch(h){if(h instanceof I)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 H$t(e.datasetId,r)}catch(h){throw so(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 Qke(e,i,t,n,c,e.opts.acceptMergeTrailers);if(n==="n1")await U$t(e,i,t,d);let p=n==="n0"?await B$t(i,t,d,e.opts.out):!1,m;try{m=await wbe(t.id,{pr:n,tag_sha:d,tree_verified:p})}catch(h){let g=pn(h);if(g==="not-released")return{kind:"wait",row:t,waitingFor:`the DOI of v${r}`};let y=ot(g??"release-failed",`The release of v${r} could not be recorded: ${h instanceof Error?h.message:String(h)}`);if(h instanceof L)await io(t,gs("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 u_(e){let t=await e.origin();if(!await Qn(t,"refs/heads/git-annex",1))throw ot("origin-unreadable","NEMAR's git-annex branch could not be fetched.");let n=await ee(t.dir,["cat-file","blob","refs/remotes/origin/heads/git-annex:remote.log"],{ok:!0}),r=Ap(n.exitCode===0?n.stdout:"",e.datasetId);if(r.problem!==null)throw ot("nemar-s3-invalid",r.problem);let o=r.record?.bucket;if(n.exitCode!==0||!r.uuid||!o)throw ot("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=TD({region:r.region,timeoutMs:AD,env:s,credentials:OD({commandEnv:s})});return{scratch:t,uuid:r.uuid,bucket:o,region:r.region,prefix:r.prefix,aws:i}}async function bj(e,t,n){let{scratch:r,bucket:o,aws:s}=n??await u_(e),i=q$t(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",PD(e.datasetId,f),i]),a=!0;break}catch(p){if(!(p instanceof Bt))throw p;if(p.code!=="not-found")throw ot("staging-unreadable",`The staging manifest of re-pull #${t.id} could not be read (${Gd(p)}); the ambient AWS credentials read it, as the copy wrote it.`)}if(!a)throw ot("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=L$t(i);if(`sha256:${j$t("sha256").update(c).digest("hex")}`!==t.manifest_digest)throw ot("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 ot("manifest-mismatch","The staging manifest names an object without a key.");return[...new Set(d)].sort()}async function eEe(e,t){if(typeof t.counts.locked==="number")return{kind:"next",row:t};let n=async(c,l)=>{let d=ot(c,l);return await io(t,gs("lock",d),e.opts.out),d},r;try{r=await bj(e,t)}catch(c){if(c instanceof I)throw await n(c.code,c.message);throw c}let o;try{o=r.length>0?await uhe(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 L?`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 rr(t.id,{from:"released",to:"released",fields:{counts:{locked:r.length}}})}catch(c){throw so(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 tEe(e,t,n){let r;try{r=await rr(t.id,{from:"released",to:"complete"})}catch(o){throw so(o,"The record could not be completed")}return e.opts.out(`Re-pull #${t.id} of ${e.datasetId} is complete${n}.`),{kind:"done",result:{row:r,outcome:"complete"}}}async function z$t(e,t){let n=e.opts.plan??Ug(e.configDir,e.datasetId,t.to_tag,t.plan_digest),{file:r,body:o}=Op(n,{environment:Ir(),env:e.env,openNeuroGraphqlUrl:Cl(e.env)});if(r.digest!==t.plan_digest)throw new I("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 G$t(e,t,n){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}`,"- 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:","","```",...Wi(e),yw(t.corrections),"```","","Do not merge this from GitHub's page."].join(`
417
+ `);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 Fl(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 yj(e,t,n){let r=t[Rn[n].version],o=`refs/tags/v${r}`,s=t[Rn[n].mergeSha],i=await e.origin(),a=async(h,g)=>{let y=ot(h,g);return await io(t,gs("release",y),e.opts.out),y},c=await V$t(e,i,t,n,a),l=!1;if(c!==null){if(l=await Xke(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, 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 Il(i,[o,`${o}^{}`])).get(o)}catch(h){if(h instanceof I)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 H$t(e.datasetId,r)}catch(h){throw so(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 Qke(e,i,t,n,c,e.opts.acceptMergeTrailers);if(n==="n1")await U$t(e,i,t,d);let p=n==="n0"?await B$t(i,t,d,e.opts.out):!1,m;try{m=await wbe(t.id,{pr:n,tag_sha:d,tree_verified:p})}catch(h){let g=pn(h);if(g==="not-released")return{kind:"wait",row:t,waitingFor:`the DOI of v${r}`};let y=ot(g??"release-failed",`The release of v${r} could not be recorded: ${h instanceof Error?h.message:String(h)}`);if(h instanceof L)await io(t,gs("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 u_(e){let t=await e.origin();if(!await Qn(t,"refs/heads/git-annex",1))throw ot("origin-unreadable","NEMAR's git-annex branch could not be fetched.");let n=await ee(t.dir,["cat-file","blob","refs/remotes/origin/heads/git-annex:remote.log"],{ok:!0}),r=Ap(n.exitCode===0?n.stdout:"",e.datasetId);if(r.problem!==null)throw ot("nemar-s3-invalid",r.problem);let o=r.record?.bucket;if(n.exitCode!==0||!r.uuid||!o)throw ot("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=TD({region:r.region,timeoutMs:AD,env:s,credentials:OD({commandEnv:s})});return{scratch:t,uuid:r.uuid,bucket:o,region:r.region,prefix:r.prefix,aws:i}}async function bj(e,t,n){let{scratch:r,bucket:o,aws:s}=n??await u_(e),i=q$t(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",PD(e.datasetId,f),i]),a=!0;break}catch(p){if(!(p instanceof Bt))throw p;if(p.code!=="not-found")throw ot("staging-unreadable",`The staging manifest of re-pull #${t.id} could not be read (${Gd(p)}); the ambient AWS credentials read it, as the copy wrote it.`)}if(!a)throw ot("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=L$t(i);if(`sha256:${j$t("sha256").update(c).digest("hex")}`!==t.manifest_digest)throw ot("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 ot("manifest-mismatch","The staging manifest names an object without a key.");return[...new Set(d)].sort()}async function eEe(e,t){if(typeof t.counts.locked==="number")return{kind:"next",row:t};let n=async(c,l)=>{let d=ot(c,l);return await io(t,gs("lock",d),e.opts.out),d},r;try{r=await bj(e,t)}catch(c){if(c instanceof I)throw await n(c.code,c.message);throw c}let o;try{o=r.length>0?await uhe(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 L?`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 rr(t.id,{from:"released",to:"released",fields:{counts:{locked:r.length}}})}catch(c){throw so(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 tEe(e,t,n){let r;try{r=await rr(t.id,{from:"released",to:"complete"})}catch(o){throw so(o,"The record could not be completed")}return e.opts.out(`Re-pull #${t.id} of ${e.datasetId} is complete${n}.`),{kind:"done",result:{row:r,outcome:"complete"}}}async function z$t(e,t){let n=e.opts.plan??Ug(e.configDir,e.datasetId,t.to_tag,t.plan_digest),{file:r,body:o}=Op(n,{environment:Ir(),env:e.env,openNeuroGraphqlUrl:Cl(e.env)});if(r.digest!==t.plan_digest)throw new I("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 G$t(e,t,n){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}`,"- 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:","","```",...Wi(e),yw(t.corrections),"```","","Do not merge this from GitHub's page."].join(`
418
418
  `)}async function nEe(e,t){let n=t.counts.corrections,r=t.counts.conflicts,o=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&&o.length===0)return tEe(e,t,"");if(r>0&&o.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 s=G$(t.to_version);try{let i=await z$t(e,t);Dke(i);let a=Cke(i,o);if(a.corrections!==n)throw new I("patch-plan-mismatch",`The plan lists ${a.corrections} correction(s) and re-pull #${t.id} records ${n}; they are the same plan only when they agree.`);if(a.unresolved>0&&!e.opts.keepUpstream)return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`an administrator's decision on the ${a.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(!Ake(a))return tEe(e,t,": the plan has no correction, and every conflict stays on upstream's side");return await K$t(e,t,a,s)}catch(i){if(i instanceof I&&!W$t.has(i.code))i.resumable=!0,await io(t,gs("patch",i),e.opts.out);throw i}}var W$t=new Set(["take-ours-invalid","declined","plan-unreadable","plan-schema","plan-environment","plan-sources","planner-version","plan-tampered","plan-not-the-record"]);async function K$t(e,t,n,r){let o=await u_(e),{scratch:s}=o;if(o.prefix!==`${e.datasetId}/objects/`)throw new I("destination-prefix",`NEMAR's nemar-s3 is not at ${e.datasetId}/objects/, where the keys N.0.1 replays are read.`);let i=await Nl({work:s.dir,baseSha:t.merge_sha,env:s.env,acceptances:!0}),a=Cn(r),c=(await Il(s,[a])).get(a),l,d,f;if(c){if(!await Qn(s,a,ko))throw ot("origin-unreadable",`release/v${r} could not be fetched.`);let y=await hy({dir:s.dir,row:t,head:c}),b=y?await uj({scratch:s,row:t,selection:n,parent:y.parent}):null;if(!y||!b||b.sha!==y.commit)throw new I("branch-foreign",`release/v${r} exists on NEMAR's repository and is not this re-pull's N.0.1 commit with these resolutions; run resume with the resolutions the earlier run was given, or decline N.0.1 with nemar admin repull abandon ${e.datasetId}.`);l=y.commit,d=y.parent,f=b.keys}else{let y=await uj({scratch:s,row:t,selection:n,parent:i});l=y.sha,d=i,f=y.keys}let p;try{p=f.length>0?await Wd(o.aws,o.bucket,o.prefix):new Map}catch(y){if(!(y instanceof Bt))throw y;throw new I("s3-failed",`NEMAR's bucket could not be listed for the keys N.0.1 replays (${Gd(y)}); the ambient AWS credentials list it.`)}if(await Pke({dir:s.dir,annexRef:"refs/remotes/origin/heads/git-annex",keys:f,nemarUuid:o.uuid,listing:p}),!c&&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), push release/v${r} and open its pull request? Its merge will mint one more version DOI, which cannot be withdrawn.`))throw new I("declined","Not confirmed; nothing was pushed.");let m=await xD({work:s.dir,synthSha:l,version:r,push:{versions:[r]},env:s.env});e.opts.out(m.pushed?`Pushed release/v${r} (${l.slice(0,12)}).`:`release/v${r} is already this re-pull's N.0.1 commit${m.head===l?"":" (moved by enrichment)"}.`);let h=await vD({token:e.token,base:e.base,datasetId:e.datasetId,version:r,body:G$t(t,n,r),acceptHead:(y)=>Ns({work:s.dir,from:l,head:y,ref:a,env:s.env})}),g;try{g=await rr(t.id,{from:"released",to:"patch_synthesized",fields:{patch_version:r,patch_branch:`release/v${r}`,patch_pr_number:h.number,patch_head_sha:h.head,patch_base_sha:d,counts:{resolutions:n.resolutions}}})}catch(y){throw so(y,"N.0.1's pull request could not be recorded")}return e.opts.out(`${h.reused?"Found":"Opened"} N.0.1's pull request #${h.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:g}}async function X$t(e){try{return(await Lo({dataset:e,open:!0,limit:1})).repulls[0]??null}catch(t){throw so(t,"The NEMAR API could not list the re-pulls")}}async function ND(e){return Vd(()=>Q$t(e))}async function Q$t(e){let t=e.env??process.env,n=bn(t),r=await hi(t);if(!r.ok)throw new I("no-github-token",`No GitHub token (${r.reason}): resume reads the pull request with the administrator's own (GH_TOKEN, or gh auth login).`);Al(await fc(e.datasetId));let o=await X$t(e.datasetId);if(!o){let d=(await Lo({dataset:e.datasetId,limit:1})).repulls[0]??null,f=e.automaticFinish;if(f&&!(d?.id===f.repullId&&d.status==="complete"))throw new I("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)Z$t(o,e.automaticFinish.repullId);let s=Jn(),i=Ec(s,e.datasetId,o.plan_digest);vo(J$t(i.lock),Y$t(s,"repull"));let a=Tl(i.lock),c=null,l={datasetId:e.datasetId,token:r.token,base:n,env:t,configDir:s,opts:e,origin:async()=>(c??=await Pl({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 eRt(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 Z$t(e,t){if(e.id!==t||e.origin!=="automatic")throw new I("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 I("finish-not-merged",`Re-pull #${e.id} is ${e.status}: a finish takes up only a merged re-pull.`)}async function eRt(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 ot("resume-looped",`Re-pull #${o.id} did not settle; run resume again.`);let i=await tRt(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 K$(i.row.id)}catch(a){throw so(a,"The NEMAR API could not read the re-pull")}}}async function tRt(e,t){switch(t.status){case"planned":case"prepared":case"copied":case"registered":throw new I("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 rEe(e,t,"n0");case"patch_synthesized":return rEe(e,t,"n1");case"gates_clear":return oEe(e,t,"n0");case"patch_gates_clear":return oEe(e,t,"n1");case"merged":return yj(e,t,"n0");case"patch_merged":return yj(e,t,"n1");case"released":{let n=await eEe(e,t);return n.kind==="next"?nEe(e,n.row):n}case"patch_released":return aRt(e,t);default:throw new I("not-built",`Re-pull #${t.id} is ${t.status}, which resume does not take on.`)}}function sEe(e,t){let n=Rn[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 iEe(e,t){let n=await Cs(e.token,e.datasetId,t.number,e.base);if(!n.ok)throw ot("github-unreadable",`Pull request #${t.number} could not be read on GitHub (${n.reason})`);return n.value}async function aEe(e,t,n){let r;try{r=await Y$(t.id,n.pr)}catch(s){throw so(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 gy(e,t,n,r){try{return await rr(e.id,{from:e.status,to:t,fields:n})}catch(o){throw so(o,r)}}function d_(e,t,n,r){let o={...hj(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 cEe(e,t,n){let r=await gy(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 lEe(e,t,n){return Ns({work:e.dir,from:t.anchor,head:n,ref:Cn(t.version),env:e.env})}async function nRt(e,t,n,r){if(n.pr==="n0")return Rke({scratch:e,row:t,head:r});let o=await uEe(e,t,n);if(!o)return null;let s=await Ike({dir:e.dir,row:t,recorded:o,head:r});return s?{synthSha:s.sha,synthTree:s.tree,baseSha:s.baseSha}:null}async function uEe(e,t,n){if(!await Qn(e,n.anchor,ko))return null;return await Qn(e,t.merge_sha,ko),(await hy({dir:e.dir,row:t,head:n.anchor}))?.commit??null}async function rEe(e,t,n){let r=sEe(t,n),o=await iEe(e,r);if(o.state==="merged")return aEe(e,t,r);if(o.state==="closed")return cEe(e,t,r);if(o.baseRef!=="main"||o.headRef!==r.branch){let g=ot("pr-foreign",`Pull request #${r.number} is not ${r.branch} into main.`);throw await io(t,gs("gates",g),e.opts.out),g}if(!Gi(o.headRepo,t.dataset_id)||!Gi(o.baseRepo,t.dataset_id)){let g=ot("pr-foreign",`Pull request #${r.number} is not from and into ${mw}/${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 io(t,gs("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 lEe(g,r,o.headSha);if(y!=="ok"){let _=await nRt(g,t,r,o.headSha);if(_){let k=await gy(t,t.status,d_(t,r,o.headSha,_),"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 (${_.synthSha.slice(0,12)}), pushed by an earlier run; re-pull #${t.id} records it.`),{kind:"next",row:k}}let x=y==="unreadable"?ot("branch-unreadable",`Whether the head of ${r.branch} is this re-pull's commit and enrichment's could not be read.`):ot("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 io(t,gs("gates",x),e.opts.out),x}let b=await gy(t,t.status,d_(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 Nl({work:s.dir,baseSha:r.base,env:s.env})}catch(g){if(g instanceof I)g.resumable=!0,await io(t,gs("gates",g),e.opts.out);throw g}let a=await op(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 ot("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 r_(s.dir,r.base,i);if(l===null)throw ot("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 sRt(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 rRt(e,t,r),f=[];if(d!==null)f.push(d);let p=c==="unstable"&&t.origin==="administrator"?await r6({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=Rn[n],h;try{h=await rr(t.id,{from:m.open,to:m.gatesClear,fields:{[m.gates]:r.head}})}catch(g){let y=pn(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 so(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 rRt(e,t,n){let r=n.head,o;try{o=await Ig(t.id)}catch(i){throw so(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 hbe(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(pn(i)!=="screen-exists")throw so(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=ot("screen-blocks",`${s.headline}. A direct identifier cannot be acknowledged: this commit is not merged.`);throw await io(t,gs("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 gbe(t.id,{pr:n.pr,sha:r,reason:e.opts.acknowledgment})}catch(i){throw so(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 oRt(e,t,n,r,o){let s=await uEe(e,t,n);if(!s)throw new I("origin-unreadable","N.0.1's commit could not be found beneath its recorded head on NEMAR's repository.");let i=await fj({dir:e.dir,commit:s,newMain:r}),a=Cn(n.version),c=await Sc(e.dir,[`${i.sha}:${a}`],{versions:[n.version]},e.env,[`--force-with-lease=${a}:${o}`]);if(c.outcome==="rejected")throw new I("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 I("push-failed",`The re-synthesized release/v${n.version} could not be pushed (${vi(c.cause)}).`);return{synthSha:i.sha,synthTree:i.tree}}async function sRt(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 I("declined","Not confirmed; nothing was pushed.");let i=await e.origin(),a;try{a=n.pr==="n0"?await $ke({scratch:i,row:t,newMain:r,liveHead:o}):await oRt(i,t,n,r,o)}catch(l){if(l instanceof I)l.resumable=!0,await io(t,gs("gates",l),e.opts.out);throw l}e.replaced.add(o);let c=await gy(t,t.status,d_(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 oEe(e,t,n){let r=sEe(t,n),o=await iEe(e,r);if(o.state==="merged")return aEe(e,t,r);if(r.claimSha!==null)try{let l=await ybe(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=pn(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 so(l,"The claim to merge could not be resolved")}if(o.state==="closed")return cEe(e,t,r);if(o.headSha!==r.gates){let l=await e.origin(),d=await lEe(l,r,o.headSha);if(d!=="ok")throw ot(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 gy(t,Rn[n].open,d_({...t,status:Rn[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 ${Rn[n].open} again, and its screen runs for the new head.`),{kind:"next",row:f}}let s=await e.origin(),i;try{i=await Nl({work:s.dir,baseSha:r.base,env:s.env})}catch(l){if(l instanceof I)l.resumable=!0;throw l}let a=i===r.base?[]:await r_(s.dir,r.base,i);if(a===null)throw ot("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=Rn[n].open,d=await gy(t,l,d_({...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 iRt(e,t,r,o);return{kind:"done",result:{row:t,outcome:"ready",...c?{bidsFailure:!0}:{}}}}async function iRt(e,t,n,r){if(t.origin!=="administrator")return!1;let o=await op(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 r6({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 aRt(e,t){let n;try{n=await rr(t.id,{from:"patch_released",to:"complete"})}catch(r){throw so(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"}}}no();var zo=(e)=>e?e.slice(0,12):"none";function cRt(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 VF(e.status)?null:`nemar admin repull resume ${t}`}}function dEe(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: ${zo(e.base_sha)} Commit: ${zo(e.synth_sha)} Tree: ${zo(e.synth_tree)}`];if(e.pr_number!==null)n.push(` Pull request: #${e.pr_number} of ${e.branch}, head ${zo(e.head_sha)}`);if(e.gates_sha)n.push(` Gates clear at: ${zo(e.gates_sha)}`);if(e.merge_claim_sha)n.push(` Claim to merge: ${zo(e.merge_claim_sha)}, made ${e.merge_claimed_at} UTC`);if(e.merge_sha)n.push(` Merge: ${zo(e.merge_sha)}`);if(e.tag_sha)n.push(` Tag v${e.to_version}: ${zo(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 ${zo(e.patch_head_sha)}, base ${zo(e.patch_base_sha)}`);if(e.patch_gates_sha)n.push(` N.0.1 gates clear at: ${zo(e.patch_gates_sha)}`);if(e.patch_merge_claim_sha)n.push(` N.0.1 claim to merge: ${zo(e.patch_merge_claim_sha)}, made ${e.patch_merge_claimed_at} UTC`);if(e.patch_merge_sha)n.push(` N.0.1 merge: ${zo(e.patch_merge_sha)}`);if(e.patch_tag_sha)n.push(` Tag v${e.patch_version}: ${zo(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 ${zo(s.sha)} (${s.pr}): ${s.headline} (gate: ${s.gate}${s.waiting?", running":""}${i})`);for(let a of s.lines)n.push(` ${a}`)}let o=cRt(e);if(o)n.push(` Next: ${o}`);return n}function fEe(e){return` #${e.id}: ${e.from_tag} -> ${e.to_tag}, attempt ${e.attempt}, ${e.status}${e.terminal_at?` (${e.terminal_at} UTC)`:""}`}Fi();no();yo();ze();xr();fn();import{mkdirSync as H1t,mkdtempSync as V1t,readFileSync as z1t,rmSync as MSe}from"fs";import{dirname as G1t,join as FSe}from"path";Fi();no();yo();fn();Xi();import{existsSync as wj,mkdirSync as lRt,readFileSync as _j,readdirSync as uRt,renameSync as dRt,rmSync as fRt,statSync as pRt,writeFileSync as xj}from"fs";import{join as Kd}from"path";Hf();var pEe="--automatic-dispatch",mRt="run-upstream-repull",mEe=["mode","dataset_id","upstream_ds","from_tag","to_tag","dispatch_id","dispatch_token","cli_version","repull_id"],hRt=new Set(["repull_id"]);function vj(e){return W$.test(e)?Number(e):null}function br(e){return new I("dispatch-invalid",`The dispatch's ${e} is not what the Worker sends, so the run does not act on it.`)}function gRt(e){if(e===null||typeof e!=="object"||Array.isArray(e))throw br("payload");let t=e,n=mEe;for(let m of Object.keys(t))if(!n.includes(m))throw br("set of keys");for(let m of mEe){if(!(m in t)){if(!hRt.has(m))throw br("set of keys");continue}if(typeof t[m]!=="string")throw br(m)}let r=t,o=r.mode;if(o!=="open"&&o!=="finish")throw br("mode");let s=r.dataset_id;if(!/^on\d{6}$/.test(s))throw br("dataset_id");let i=r.upstream_ds;if(!/^ds\d{6}$/.test(i))throw br("upstream_ds");let{from_tag:a,to_tag:c}=r;if(!Cr(a))throw br("from_tag");if(!Cr(c))throw br("to_tag");if(Ar(a,c))throw br("tag pair");let l=vj(r.dispatch_id);if(l===null)throw br("dispatch_id");let d=null;if(r.repull_id!==void 0){if(d=vj(r.repull_id),d===null)throw br("repull_id")}if(o==="finish"&&d===null)throw br("repull_id");let f=r.dispatch_token;if(!ube.test(f))throw br("dispatch_token");let p=r.cli_version;if(!Pg.test(p))throw br("cli_version");return{mode:o,datasetId:s,upstreamDs:i,fromTag:a,toTag:c,dispatchId:l,repullId:d,token:f,cliVersion:p}}var yRt=1048576;function bRt(e){let t=e.GITHUB_EVENT_PATH,n=()=>new I("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(pRt(t).size>yRt)throw br("event");r=JSON.parse(_j(t,"utf8"))}catch(s){if(s instanceof I)throw s;if(s.code==="ENOENT")throw n();throw br("event")}if(r===null||typeof r!=="object"||Array.isArray(r))throw br("event");let o=r;if(o.action!==mRt)throw br("event type");return gRt(o.client_payload)}var wRt=/^[a-z][a-z0-9-]{0,31}$/,_Rt=/^[a-z][a-z0-9_]{0,31}$/,xRt=/^[a-z0-9_.-]{1,64}$/;function f_(e,t={}){if(!wRt.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(!_Rt.test(r)||!xRt.test(s))return"repull-auto: unprintable-line";n.push(`${r}=${s}`)}return n.join(" ")}var FD=null;function MD(){if(FD)return FD;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(`${f_("quiet",a())}
419
419
  `),d){e(`${f_("report-stands",{phase:d.phase})}
420
420
  `);let{phase:f,code:p}=d;e(`${f_("result",p===void 0?{phase:f}:{phase:f,code:p})}
@@ -444,7 +444,7 @@ ${b.message}`,r);if(_)return Wt("message",`The squash message would not carry th
444
444
  `)return!1;try{return JSON.parse(r).action==="repull-scrubbed"}catch{return!1}}function b1t(e){let{tree:t,base:n,expected:r,preScrub:o,scope:s,scrub:i}=e,a=new Set(e.uploaded.map((k)=>k.key)),c=(k)=>k?.mode===h1t,l=0,d=0,f=0,p=new Set([...t.keys(),...n.keys(),...r.keys()]);for(let k of p){let v=t.get(k),C=__(v),T=r.get(k);if(Qi(k)){if(k===r1){if(!y1t({got:v,base:n.get(k),text:e.ledger,changed:g1t(i)}))f++}else if(k===m1t&&T!==void 0){if(C!==T||v?.key!==null)d++}else if(_y(v)!==_y(n.get(k)))d++;continue}let V=(A)=>s.has(k)&&v!==void 0&&v.key===null&&__(o.get(k))===A&&v.mode===o.get(k)?.mode&&C!==A&&(vp.test(k)||kp.test(k)||Gj.has(k));if(T===void 0){let A=n.get(k);if(_y(v)!==_y(A)&&!(Gj.has(k)&&V(__(A))))l++;continue}if(T==="absent"){if(v)l++;continue}if(T.startsWith("A:")){let A=T.slice(2),F=Uo.test(k)&&i.replacedKeys.has(A)&&v?.key!=null&&a.has(v.key);if(C!==T&&!F||!c(v))l++;continue}if(T.startsWith("L:")){if(!v?.key||!a.has(v.key)||!c(v))l++;continue}if(C!==T&&!V(T))l++}if(l>0)throw Ll("path(s) differ from their target",l);if(d>0)throw Ll("NEMAR-owned path(s) differ from NEMAR's side",d);if(f>0)throw Ll("privacy ledger(s) not the base's plus the scrub's one line",f);let m=new Set;for(let[k,v]of t)if(v.key&&!Qi(k))m.add(v.key);let h=[...m].filter((k)=>i.replacedKeys.has(k)).length;if(h>0)throw Ll("key(s) the scrub replaced are still named",h);let g=new Set(hs(e.body).filter((k)=>k.purpose==="copy").map((k)=>k.key)),y=[...m].filter((k)=>!e.held.has(k)&&!g.has(k)&&!a.has(k)).length;if(y>0)throw Ll("named key(s) are neither held, copied by the plan, nor uploaded",y);let b=e.manifest.items.filter((k)=>!g.has(k.key)).length;if(b>0)throw Ll("copy key(s) are outside the plan",b);let _=e.manifest.local.filter((k)=>!a.has(k.key)).length;if(_>0)throw Ll("local key(s) were not uploaded by this run",_);let x=e.uploaded.filter((k)=>!bl(k)||!m.has(k.key)).length;if(x>0)throw Ll("upload(s) are not a local upload the tree names",x)}async function w1t(e,t){let n=await ee(e,["rev-list","--objects",t],{code:"synthesis-failed",step:"rev-list"}),r=new Set;for(let o of n.stdout.split(`
445
445
  `)){let s=o.slice(0,40);if(/^[0-9a-f]{40}$/.test(s))r.add(s)}return r}function Yj(e){let t=/[zZ]|[+-]\d\d:\d\d$/.test(e)?e:`${e.replace(" ","T")}Z`,n=new Date(t);if(Number.isNaN(n.getTime()))throw new I("synthesis-failed","The re-pull record's creation time does not parse.");return n}async function vSe(e){let{work:t}=e,n=Br(e.body),r=(await ee(t,["write-tree"],{code:"synthesis-failed",step:"write-tree"})).stdout.trim(),o=await Jj(t),s=new Set;for(let[h,g]of o)if(g.key&&!Qi(h))s.add(g.key);let i=Kj({named:s,body:e.body,digest:e.digest,held:e.held}),a=async(h)=>{let g=await ee(t,["cat-file","blob",h],{ok:!0});return g.exitCode===0?g.stdout:null},c=o.get(r1);b1t({tree:o,base:e.base,expected:e.expected,preScrub:e.preScrub,scope:e.scope,body:e.body,scrub:e.scrub,uploaded:e.uploaded,held:e.held,manifest:i,ledger:{base:e.base.has(r1)?await a(`${e.baseSha}:${r1}`):null,synth:c?await a(c.oid):null}});let l=e.scrub.counts,d=[`Re-pull ${n.ds} ${n.fromTag} to ${n.toTag} as v${n.toVersion}`,"",[`Upstream's snapshot ${n.toTag} of ${n.ds}, replayed onto NEMAR's main as one commit (ADR 0111).`,`Paths written: ${e.counts.written}; deleted: ${e.counts.deleted}.`,`Keys copied from upstream by version: ${i.items.length}; uploaded from this host: ${i.local.length}.`,`Recording headers scrubbed: ${l.headers_scrubbed}; acquisition dates set: ${l.headers_dates_normalized}; JSON values blanked: ${l.json_values_blanked}.`].join(`
446
446
  `),"",...Wi({upstream_ds:n.ds,to_tag:n.toTag,plan_digest:e.digest}),""].join(`
447
- `),f=`${Math.floor(Yj(e.createdAt).getTime()/1000)} +0000`,p=(await ee(t,["commit-tree","--no-gpg-sign",r,"-p",e.baseSha,"-F","-"],{stdin:d,code:"synthesis-failed",step:"commit-tree",env:{GIT_AUTHOR_NAME:ln.name,GIT_AUTHOR_EMAIL:ln.email,GIT_AUTHOR_DATE:f,GIT_COMMITTER_NAME:ln.name,GIT_COMMITTER_EMAIL:ln.email,GIT_COMMITTER_DATE:f}})).stdout.trim(),m=new Set;for(let h of e.scope){let g=e.preScrub.get(h),y=o.get(h);if(!g||g.key!==null||g.mode==="120000")continue;if(Gj.has(h))continue;if(__(g)!==__(y))m.add(g.oid)}if(m.size>0){let h=await w1t(t,p),g=[...m].filter((y)=>h.has(y)).length;if(g>0)throw Ll("scrubbed original(s) are reachable from the commit",g)}return await ee(t,["update-ref",`refs/heads/${Ol}`,p],{code:"synthesis-failed",step:"update-ref"}),{synthSha:p,synthTree:r,manifest:i,manifestDigest:Wj(i)}}var ys=["planned","prepared","copied","registered","pr_open"];function jp(e,t){let n=ys,r=n.indexOf(e);return r<0||r>=n.indexOf(t)}function ESe(e,t){if(t instanceof I)return`[${e}:${t.code}] ${t.message}`;if(t instanceof Ke)return`[${e}:write-refused] ${t.message}`;if(t instanceof Bt)return`[${e}:s3-failed] An S3 call failed (${Gd(t)}).`;return`[${e}:${e}-failed] The step failed: ${xo(t)}.`}function _1t(e,t){if(t instanceof I)return t;let n=ESe(e,t),r=/^\[[a-z]+:([a-z0-9-]+)\]/.exec(n)?.[1]??`${e}-failed`;return new I(r,n.replace(/^\[[^\]]+\] /,""))}async function x1t(e,t){let n=Ap(await Cp(e),t);if(n.problem!==null)throw new I("nemar-s3-invalid",n.problem);let r=n.record?.bucket,o=`${t}/objects/`;if(!n.uuid||!r)throw new I("no-nemar-s3","NEMAR's remote.log names no single nemar-s3 bucket.");if(n.prefix!==o)throw new I("destination-prefix",`NEMAR's nemar-s3 is not at ${o}, the only prefix a re-pull writes to.`);return{uuid:n.uuid,bucket:r,region:n.region,prefix:o}}async function Xj(e,t){let n=Br(t.body),r=oy(n.ds,t.env),o=As(r,null),s=await ee(e,["ls-remote",r,`refs/tags/${n.toTag}`],{...o?{env:o}:{},ok:!0}),i=new Map(s.stdout.split(`
447
+ `),f=`${Math.floor(Yj(e.createdAt).getTime()/1000)} +0000`,p=(await ee(t,["commit-tree","--no-gpg-sign",r,"-p",e.baseSha,"-F","-"],{stdin:d,code:"synthesis-failed",step:"commit-tree",env:{GIT_AUTHOR_NAME:ln.name,GIT_AUTHOR_EMAIL:ln.email,GIT_AUTHOR_DATE:f,GIT_COMMITTER_NAME:ln.name,GIT_COMMITTER_EMAIL:ln.email,GIT_COMMITTER_DATE:f}})).stdout.trim(),m=new Set;for(let h of e.scope){let g=e.preScrub.get(h),y=o.get(h);if(!g||g.key!==null||g.mode==="120000")continue;if(Gj.has(h))continue;if(__(g)!==__(y))m.add(g.oid)}if(m.size>0){let h=await w1t(t,p),g=[...m].filter((y)=>h.has(y)).length;if(g>0)throw Ll("scrubbed original(s) are reachable from the commit",g)}return await ee(t,["update-ref",`refs/heads/${Ol}`,p],{code:"synthesis-failed",step:"update-ref"}),{synthSha:p,synthTree:r,manifest:i,manifestDigest:Wj(i)}}var ys=["planned","prepared","copied","registered","pr_open"];function jp(e,t){let n=ys,r=n.indexOf(e);return r<0||r>=n.indexOf(t)}function ESe(e,t){if(t instanceof I)return`[${e}:${t.code}] ${t.message}`;if(t instanceof Ke)return`[${e}:write-refused] ${t.message}`;if(t instanceof Bt)return`[${e}:s3-failed] An S3 call failed (${Gd(t)}).`;return`[${e}:${e}-failed] The step failed: ${xo(t)}.`}function _1t(e,t){if(t instanceof I)return t;let n=ESe(e,t),r=/^\[[a-z]+:([a-z0-9-]+)\]/.exec(n)?.[1]??`${e}-failed`;return new I(r,n.replace(/^\[[^\]]+\] /,""))}async function x1t(e,t){let n=Ap(await Cp(e),t);if(n.problem!==null)throw new I("nemar-s3-invalid",n.problem);let r=n.record?.bucket,o=`${t}/objects/`;if(!n.uuid||!r)throw new I("no-nemar-s3","NEMAR's remote.log names no single nemar-s3 bucket.");if(n.prefix!==o)throw new I("destination-prefix",`NEMAR's nemar-s3 is not at ${o}, the only prefix a re-pull writes to.`);return{uuid:n.uuid,bucket:r,region:n.region,prefix:o}}async function Xj(e,t){let n=Br(t.body),r=oy(n.ds,t.env),o=As(r,null),s=await ee(e,["ls-remote",r,`refs/tags/${n.toTag}`,`refs/tags/${n.toTag}^{}`],{...o?{env:o}:{},ok:!0}),i=new Map(s.stdout.split(`
448
448
  `).map((c)=>c.split("\t")).filter((c)=>c.length===2).map(([c,l])=>[l,c])),a=i.get(`refs/tags/${n.toTag}^{}`)??i.get(`refs/tags/${n.toTag}`)??null;if(s.exitCode!==0||a===null)throw new I("upstream-unreadable",`Upstream's tag ${n.toTag} could not be read.`);if(a!==n.toCommit)throw new I("upstream-tag-moved",`Upstream's tag ${n.toTag} names another commit than the one the plan read: OpenNeuro re-created the snapshot. This re-pull cannot continue: its record has to be ended (nemar admin repull abandon <id>) and the dataset planned again.`)}async function v1t(e,t){let{synth_sha:n,synth_tree:r}=t,o=e.paths.repo,s=async(c)=>(await ee(o,["rev-parse","--verify","--quiet",c],{ok:!0})).stdout.trim();try{if(await s("HEAD")===n&&await s("HEAD^{tree}")===r)return o}catch{}vo(e.paths.root,kSe(kSe(e.paths.lock)));let i=Br(e.body).annexCommit,a=await mD({dir:o,bundle:e.paths.bundle,originUrl:xi(e.datasetId,e.env),baseSha:t.base_sha,token:e.token,annexCommit:t.status==="prepared"?i:null,bundleAnnex:i,synthSha:n,synthTree:r});if(a!==null)throw new I("checkpoint-lost",`Re-pull #${t.id}'s working clone and its checkpoint do not hold the recorded commit (${a}); this re-pull cannot continue: its record has to be ended (nemar admin repull abandon <id>) and the dataset planned again.`);return e.out(`Re-pull #${t.id}'s working clone was restored from the checkpoint.`),o}async function k1t(e,t,n){let r=new Set;for(let[i,a]of await n1(e,n.synth_sha))if(!Qi(i))r.add(a);let o=new Set((await n1(e,n.base_sha)).values()),s=Kj({named:r,body:t.body,digest:t.digest,held:w_(t.body,o)});if(Wj(s)!==n.manifest_digest)throw new I("manifest-mismatch","The copy manifest rebuilt from the synthesized commit is not the one recorded at prepared.");return s}function E1t(e,t,n){let r={};for(let[i,a]of Object.entries(e.env))if(a!==void 0)r[i]=a;let o=OD({commandEnv:r}),s=(i)=>uke(TD({region:i,timeoutMs:AD,env:r,credentials:o}),n);return{source:s(Hke),dest:s(t)}}function S1t(e,t,n){return[...e.items.map((r)=>({key:r.key,sourceUrl:null,source:null,destUri:`s3://${t}/${n}${r.key}`})),...e.local.map((r)=>({key:r.key,sourceUrl:null,source:null,destUri:`s3://${t}/${n}${r.key}`,origin:"local"}))]}function Qj(e,t,n){if(t){n(`Working directory kept at ${e.root}; it holds the delta's unscrubbed originals.`);return}try{Ps(e.root)}catch(r){n(`The working directory ${e.root} could not be removed (${r instanceof I?r.code:xo(r)}); remove it by hand: it holds the delta's unscrubbed originals.`)}}async function o1(e,t,n,r,o){let s=Date.now();try{return r?.beforeStep?.(e),await o()}catch(i){throw await n.recordError(t,ESe(e,i).slice(0,2000)),vc(_1t(e,i),e)}finally{r?.timed?.(e,Date.now()-s)}}async function Zj(e,t,n,r){let o=t;if(jp(o.status,n))return o;let s=Br(e.body),i={versions:[s.toVersion]},a=As(xi(e.datasetId,e.env),e.token),c=await o1(o.status==="prepared"?"copy":o.status==="copied"?"register":"pr",o,r,null,async()=>{let h=await v1t(e,o),g=await x1t(h,e.datasetId),y=await k1t(h,e,o),b={destBucket:g.bucket,prefix:g.prefix,stagingKey:PD(e.datasetId,s.toTag),sourceBucket:gp,sourcePrefix:`${s.ds}/`};return{work:h,remote:g,manifest:y,guard:b,aws:E1t(e,g.region,b)}}),{work:l,remote:d,manifest:f,guard:p,aws:m}=c;if(o.status==="prepared"){let h=await o1("copy",o,r,e,async()=>{if(await Xj(l,e),f.items.some((x)=>x.bucket!==gp))throw new I("copy-source","A copy item names another bucket than upstream's.");await Vke({aws:m.dest,bucket:d.bucket,key:p.stagingKey,manifest:f,dir:e.paths.root});let g=await Wd(m.dest,d.bucket,d.prefix),y=await zke({aws:m,manifest:f,destBucket:d.bucket,prefix:d.prefix,existing:g,...e.copy??{}}),b=await Wd(m.dest,d.bucket,d.prefix),_=UD(S1t(f,d.bucket,d.prefix),b);if(_.message!==null)throw new I("copy-unverified",`${_.missing.length} of ${f.items.length+f.local.length} manifest object(s) are not at their declared size in NEMAR's bucket after the copy (${_.missingUpstream} copied from upstream, ${_.missingLocal} uploaded at prepare).`);return y});if(o=await r.transition(o,"copied",{counts:{copied:h.copied,skipped:h.skipped,bytes:h.bytes}}),e.out(`Copied re-pull #${o.id}: ${h.copied} object(s) copied by version, ${h.skipped} already present.`),jp(o.status,n))return o}if(o.status==="copied"){let h=await o1("register",o,r,e,async()=>{if(!e.token)throw new I("no-github-token","No GitHub token: the registration and the release branch are pushed with the administrator's own (GH_TOKEN, or gh auth login).");await Xj(l,e);let g=await Wd(m.dest,d.bucket,d.prefix);return ySe({work:l,synthSha:o.synth_sha,body:e.body,manifest:f,nemarUuid:d.uuid,listing:g,bucket:d.bucket,datasetId:e.datasetId,push:i,env:a})});if(o=await r.transition(o,"registered",{counts:{registered:h.treeKeys}}),e.out(`Registered re-pull #${o.id}: ${h.treeKeys} key(s) at nemar-s3 (${h.registered} recorded now, ${h.retired} replaced key(s) retired).`),jp(o.status,n))return o}if(o.status==="registered"){let h=o.synth_sha,g=Cn(s.toVersion),y=await o1("pr",o,r,e,async()=>{let b=e.token;if(!b)throw new I("no-github-token","No GitHub token: the pull request is opened with the administrator's own (GH_TOKEN, or gh auth login).");await Xj(l,e),await Nl({work:l,baseSha:o.base_sha,env:a});let _=await xD({work:l,synthSha:h,version:s.toVersion,push:i,env:a});return e.out(_.pushed?`Pushed release/v${s.toVersion}.`:`release/v${s.toVersion} is already this re-pull's commit${_.head===h?"":" (moved by enrichment)"}.`),vD({token:b,base:e.apiBase,datasetId:e.datasetId,version:s.toVersion,body:fke({datasetId:e.datasetId,repullId:o.id,ds:s.ds,fromTag:s.fromTag,toTag:s.toTag,toVersion:s.toVersion,patchVersion:s.patchVersion,digest:e.digest,doiCount:Dc(e.body).doi_count??1,counts:o.counts}),acceptHead:(x)=>Ns({work:l,from:h,head:x,ref:g,env:a})})});o=await r.transition(o,"pr_open",{branch:`release/v${s.toVersion}`,pr_number:y.number,head_sha:y.head}),e.out(`${y.reused?"Found":"Opened"} pull request #${y.number} of release/v${s.toVersion}; re-pull #${o.id} is pr_open. Execute never merges.`),Qj(e.paths,e.keepWorkdir,e.out)}return o}no();ze();var SSe=300000,$Se=15000,RSe=30;async function DSe(e){let t=e.now??Date.now,n=e.sleep??((b)=>new Promise((_)=>setTimeout(_,b))),r=e.row;if(r.status!=="pr_open"||!r.synth_sha||!r.branch||!r.head_sha)throw new I("repull-not-ready",`Re-pull #${r.id} is ${r.status}, not an open pull request with a recorded head.`);let o=Cn(r.to_version),s=t(),i=e.deadlineMs===void 0?Number.POSITIVE_INFINITY:e.deadlineMs-s,a=Math.min(e.opts.maxWaitMs,i),c=i<e.opts.maxWaitMs,l=async(b,_,x,k)=>{let v=`${r.branch} could not be read while the run settled it (${b}); the pull request stays open, and an administrator's resume settles it.`;return await io(r,`${XF}head-unreadable] ${v}`,e.out),{outcome:"unreadable",row:r,reads:_,moves:x,unreadable:k,cause:b}};if(i<=0)return l("token-hour",0,0,0);let d=null,f=null,p=null,m=0,h=0,g=0,y=!1;for(;;){m++;let b=null;try{if(b=(await Il(e.scratch,[o])).get(o)??null,b===null)p="branch-absent"}catch(x){p=$1t(x)}if(b===null)g++;else if(b===r.head_sha)f=t(),d??=f;else{let x=await Ns({work:e.scratch.dir,from:r.synth_sha,head:b,ref:o,env:e.scratch.env});if(x==="foreign"){let k=`${r.branch} moved by a commit enrichment does not make while the run settled it: the pull request is left open at the recorded head, and the record is to be abandoned.`;return await io(r,`${XF}head-foreign] ${k}`,e.out),{outcome:"foreign",row:r,reads:m,moves:h,unreadable:g,cause:p}}if(x==="unreadable")g++,p="branch-unreadable";else r=await R1t(r,b),h++,f=t(),d=f,e.out(`${r.branch} moved by enrichment; re-pull #${r.id} records the new head.`)}let _=t();if(y=d!==null&&f!==null&&f-d>=e.opts.quietMs,y||_-s>=a)break;await n(Math.max(0,Math.min(e.opts.pollMs,a-(_-s))))}if(f===null||f<t()-e.opts.quietMs)return l(p??"unknown",m,h,g);if(c&&!y)return l("token-hour",m,h,g);return{outcome:"settled",row:r,reads:m,moves:h,unreadable:g,cause:p}}function $1t(e){if(e instanceof I)return e.code;let t=e instanceof Error?e.name:"";return/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(t)?t:"error"}async function R1t(e,t){try{return await rr(e.id,{from:"pr_open",to:"pr_open",fields:{branch:e.branch,pr_number:e.pr_number,head_sha:t}})}catch(n){let r=pn(n),o=new I(r??(n instanceof L?"record-refused":"github-failed"),`The moved head of ${e.branch} could not be recorded on re-pull #${e.id}.`);throw o.resumable=!0,o}}var ISe=["planned","prepared"];function O1t(e){let t=e.NEMAR_REPULL_UPSTREAM_OBJECTS_BASE?.trim();if(!t)return;try{let n=new URL(t);if(n.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(n.hostname))return t.replace(/\/+$/,"")}catch{}throw new I("test-base-refused","NEMAR_REPULL_UPSTREAM_OBJECTS_BASE is set but is not an http://127.0.0.1, http://localhost or http://[::1] address. It is only for tests, so it is refused rather than ignored.")}function rL(e){let t=pn(e);return new I(t??"record-refused",`The NEMAR API refused the record${t?` (${t})`:""}: ${e instanceof Error?e.message:String(e)}`)}var tL="[prepare:";function T1t(e){if(e instanceof I)return`${tL}${e.code}] ${e.message}`;return`${tL}prepare-failed] The preparation failed: ${xo(e)}.`}function CSe(e,t){try{Ps(e)}catch(n){t(`The scratch directory ${e} could not be removed (${n instanceof I?n.code:xo(n)}); remove it by hand.`)}}function ASe(e){try{if(C1t(e).length===0)A1t(e)}catch{}}async function c1(e){let t=e.env??process.env,n=e.until??"pr_open";if(!ys.includes(n))throw new I("until-not-allowed",`Execution stops at ${ys.join(", ")}; it never goes past the open pull request.`);return Vd(()=>I1t(e,t,n))}function NSe(e,t){if(t.origin!=="automatic")throw vc(new I("repull-in-flight",`Re-pull #${t.id} of ${t.dataset_id} is an administrator's: a dispatched run never takes it up.`),"record");if(e.repullId!==null&&t.id!==e.repullId)throw vc(new I("repull-mismatch",`The dispatch continues re-pull #${e.repullId}, and the record found is #${t.id}.`),"record")}async function s1(e,t,n,r,o){if(!e.automatic||o.status!=="pr_open")return;let s=await Pl({configDir:Jn(),datasetId:o.dataset_id,digest:r,purpose:"settle",env:t,token:n}),i=e.automatic;try{return await oL(i,"settle",()=>DSe({scratch:s,row:o,opts:i.settle,out:e.out,deadlineMs:(i.tokenSince+gw)*1000,...i.now?{now:i.now}:{}}))}catch(a){throw a1(vc(a,"settle"))}finally{s.close()}}async function P1t(e){try{return(await Lo({dataset:e,open:!0,limit:1})).repulls[0]??null}catch(t){if(t instanceof L)throw vc(rL(t),"record");throw t}}async function OSe(e,t,n,r,o){if(!e.confirm)return;let s=Br(t);if(!await e.confirm({...o?{supersedes:{id:o.id,toTag:o.to_tag,status:o.status,prNumber:o.pr_number}}:{},datasetId:s.datasetId,fromTag:s.fromTag,toTag:s.toTag,toVersion:s.toVersion,doiCount:Dc(t).doi_count??1,copyItems:hs(t).filter((a)=>a.purpose==="copy").length,status:n,until:r}))throw new I("declined","Not confirmed; nothing was written.")}async function oL(e,t,n){let r=e?.measured;if(!r)return n();let o=Date.now();try{return await n()}finally{r(t,Math.round((Date.now()-o)/1000))}}function TSe(e,t){if(!e)return{};let n=e.now??Date.now;return{beforeStep(r){let o=r==="copy"?m_(t):0,s=p_(e.tokenSince,n(),o);if(s)throw s},timed:(r,o)=>e.measured?.(r,Math.round(o/1000))}}function a1(e){if(e instanceof I)e.resumable=!0;return e}async function I1t(e,t,n){let{datasetId:r,digest:o}=fD(e.planPath),s=bn(t),i=Cl(t),a=O1t(t),c=Jn(),l=Ec(c,r,o),d=x_(c,"repull");vo(v_(l.lock),d);let f=Tl(l.lock);try{let p=await hi(t);if(!p.ok)e.out(`No GitHub token (${p.reason}); release-pr will be unchecked.`);let m=await fc(r);Al(m);let h=await P1t(r),g=h&&h.plan_digest!==o?F1t(h,e,r,Op(e.planPath,{environment:Ir(),env:t,openNeuroGraphqlUrl:i}).body):null;if(h&&h.plan_digest===o&&e.supersede)e.out(`Re-pull #${h.id} is this plan's own record; --supersede has nothing to supersede.`);if(h&&h.plan_digest===o&&!ISe.includes(h.status)){let{body:_}=Op(e.planPath,{environment:Ir(),env:t,openNeuroGraphqlUrl:i});if(e.automatic)NSe(e.automatic,h),LD(_);let x={env:t,token:p.ok?p.token:null,datasetId:r,digest:o,body:_,paths:l,apiBase:s,keepWorkdir:e.keepWorkdir===!0,out:e.out,...e.copy?{copy:e.copy}:{},...TSe(e.automatic,_)};if(e.out(`Found re-pull #${h.id} of ${r}, ${h.status}.`),jp(h.status,"pr_open"))Qj(l,x.keepWorkdir,e.out);if(jp(h.status,n)){if(!ys.includes(h.status))e.out(`Re-pull #${h.id} is past the open pull request; execute never merges. Take it on with: nemar admin repull resume ${r}`);let C=await s1(e,t,x.token,o,h);return{row:C?.row??h,stoppedAt:h.status,...C?{settled:C}:{}}}await OSe(e,_,h.status,n);let k;try{k=await Zj(x,h,n,PSe(e.out))}catch(C){throw a1(C)}let v=await s1(e,t,x.token,o,k);return{row:v?.row??k,stoppedAt:k.status,...v?{settled:v}:{}}}let y;try{if(e.automatic)y=N1t(e.planPath,e.automatic,t,i);else{Ps(l.plan),vo(l.plan,d);let _=new Map,x=await Lve(e.planPath,{catalog:m,github:{token:p.ok?p.token:null,apiBase:s},environment:Ir(),env:t,workRoot:l.plan,collect:{computed:_},openNeuroGraphqlUrl:i,...e.maxFetchBytes!==void 0?{maxFetchBytes:e.maxFetchBytes}:{},...g?{ownRelease:(k)=>M1t(g,k)}:{}});y={body:x.live.body,plannerDir:x.workdir,computed:_,rebasedOnto:x.rebasedOnto}}}catch(_){throw CSe(l.plan,e.out),ASe(l.root),ASe(v_(l.root)),_}let b={env:t,token:p.ok?p.token:null,datasetId:r,digest:o,body:y.body,paths:l,plannerDir:y.plannerDir,computed:y.computed,objectsBase:a,normalizeMaxBytes:e.normalizeMaxBytes??Mw,automatic:e.automatic,out:e.out};try{if(await OSe(e,b.body,h?.plan_digest===o?h.status:null,n,g??void 0),g)await j1t(g,{datasetId:r,token:p.ok?p.token:null,apiBase:s,env:t,configDir:c,out:e.out});let _=await L1t(b,y.rebasedOnto,n);if(jp(_.row.status,n)){let v=await s1(e,t,b.token,o,_.row);return v?{..._,row:v.row,settled:v}:_}let x;try{x=await Zj({env:t,token:b.token,datasetId:r,digest:o,body:b.body,paths:l,apiBase:s,keepWorkdir:e.keepWorkdir===!0,out:e.out,...e.copy?{copy:e.copy}:{},...TSe(e.automatic,b.body)},_.row,n,PSe(e.out))}catch(v){throw a1(v)}let k=await s1(e,t,b.token,o,x);return{row:k?.row??x,stoppedAt:x.status,...k?{settled:k}:{}}}finally{if(!e.keepWorkdir)CSe(l.plan,e.out)}}finally{f()}}function N1t(e,t,n,r){let{body:o}=Op(e,{environment:Ir(),env:n,openNeuroGraphqlUrl:r});LD(o);let s=p_(t.tokenSince,(t.now??Date.now)(),m_(o));if(s)throw s;let{workdir:i,computed:a}=kEe(e,gc(o));return{body:o,plannerDir:i,computed:a,rebasedOnto:null}}function F1t(e,t,n,r){if(!t.supersede)throw vc(new I("repull-in-flight",`Re-pull #${e.id} of ${n} (${e.from_tag} to ${e.to_tag}) is ${e.status}, and a dataset has one open re-pull at a time: pass --supersede to end it and execute this plan (a newer tag, before its merge), or end it with nemar admin repull abandon ${n}.`),"record");let o=Br(r);if(e.origin!=="administrator")throw new I("supersede-automatic",`Re-pull #${e.id} was opened by the automatic path; an administrator takes one over by ending it (nemar admin repull abandon ${n}) and executing again, never by a supersede.`);if(Ar(e.to_tag,o.toTag))throw new I("supersede-same-tag",`Re-pull #${e.id} pulls ${e.to_tag} too: a supersede is for a newer tag. End it with nemar admin repull abandon ${n}, then execute this plan.`);if(!Ar(e.from_tag,o.fromTag))throw new I("supersede-from-tag",`Re-pull #${e.id} pulls from ${e.from_tag} and this plan from ${o.fromTag}; a superseding plan is made again from the same from_tag.`);if(!Tg.includes(e.status))throw new I("supersede-too-late",`Re-pull #${e.id} is ${e.status}: past its merge it is released (nemar admin repull resume ${n}), never superseded.`);if(e.merge_claim_sha!==null)throw new I("merge-claim-held",`A claim to merge re-pull #${e.id}'s pull request is held, so it may have merged: run nemar admin repull resume ${n}, which reads GitHub and records the merge or expires the claim.`);return e}function M1t(e,t){let n=`release/v${e.to_version}`,r=Uj.includes(e.status),o=t.branches.filter((l)=>!(r&&l===`refs/heads/${n}`));if(o.length>0){let l=o.map((d)=>d.replace(/^refs\/heads\//,"")).join(", ");return{ok:!1,why:r?`release branch(es) other than re-pull #${e.id}'s own exist (${l}); delete them by hand if they are stale`:`re-pull #${e.id} is ${e.status} and pushed no branch, yet release branch(es) exist (${l})`}}if(t.pulls===null)return{ok:!1,why:`the open pull requests were not read whole (${t.pullsUnread??"unread"})`};let s=`${ry}/${e.dataset_id}`,i=t.pulls.filter((l)=>l.headRef.startsWith("release/")),a=i.filter((l)=>r&&l.headRef===n&&l.headRepo===s&&(e.pr_number===null||l.number===e.pr_number)),c=i.filter((l)=>!a.includes(l));if(c.length>0)return{ok:!1,why:`another release pull request is open (#${c[0]?.number})`};if(a.length>1)return{ok:!1,why:`re-pull #${e.id} recorded no pull request, and ${a.length} are open of ${n} (#${a.map((l)=>l.number).join(", #")}), so which is its own is not known`};return{ok:!0}}async function j1t(e,t){let n=t.configDir??Jn(),r=t.out??(()=>{});if(!t.token)throw new I("no-github-token","No GitHub token: the superseded record's pull request is closed with the administrator's own (GH_TOKEN, or gh auth login).");let o=t.token,s=Ec(n,t.datasetId,e.plan_digest);vo(v_(s.lock),x_(n,"repull"));let i=Tl(s.lock),a=null;try{let c=await Hj({datasetId:t.datasetId,token:o,base:t.apiBase,env:t.env,configDir:n,out:r,origin:async()=>(a??=await Pl({configDir:n,datasetId:t.datasetId,digest:e.plan_digest,purpose:"resume",env:t.env,token:o}),a)},e,"superseded",void 0,{branchMustGo:!0}),l=c.report.orphans;r(`Re-pull #${e.id} (${e.from_tag} to ${e.to_tag}) is superseded${l?`; ${l.objects} object(s), ${l.bytes} byte(s), its copy and uploads wrote stay in NEMAR's bucket, not deleted`:`; what its copy and uploads wrote stays in NEMAR's bucket (not counted: ${c.report.orphansUnknown})`}.`)}finally{a?.close(),i()}}async function L1t(e,t,n){let r=Br(e.body),o=t??r.mainCommit;if(t)e.out("NEMAR's main moved by .nemar/** only since the plan; executing on the live main.");let s=Dc(e.body),i;try{i=await pbe({dataset_id:e.datasetId,upstream_ds:r.ds,from_tag:r.fromTag,to_tag:r.toTag,from_version:r.fromVersion,to_version:r.toVersion,plan_digest:e.digest,planner:r.planner,base_sha:o,lineage_recordable:r.lineageRecordable,counts:{delta_paths:s.delta_paths??0,unexplained:s.unexplained??0,conflicts:s.conflicts??0,corrections:s.corrections??0,...e.automatic&&s.copy_bytes!==void 0?{copy_bytes:s.copy_bytes}:{}},...e.automatic?{dispatch_id:e.automatic.dispatchId,dispatch_token:e.automatic.token}:{}})}catch(c){if(c instanceof L)throw vc(rL(c),"record");throw c}let a=i.repull;if(e.automatic)NSe(e.automatic,a);if(e.out(i.created?`Recorded re-pull #${a.id} of ${e.datasetId} (${r.fromTag} -> ${r.toTag}), planned.`:`Found re-pull #${a.id} of ${e.datasetId}, ${a.status}.`),n==="planned"||!ISe.includes(a.status))return{row:a,stoppedAt:a.status};try{vo(e.paths.root,v_(v_(e.paths.lock)));let c=a;a=await oL(e.automatic,"prepare",()=>c.status==="planned"?q1t(e,c,o):B1t(e,c,o))}catch(c){throw a1(vc(c,"prepare"))}return{row:a,stoppedAt:a.status}}function PSe(e){return{transition:(t,n,r)=>l1(t,n,r),async recordError(t,n){let r=t.status==="prepared"?sL(t):{};try{await rr(t.id,{from:t.status,to:t.status,fields:r,error:n})}catch(o){e(`The failure could not be recorded on re-pull #${t.id} (${pn(o)??(o instanceof L?`HTTP ${o.statusCode}`:xo(o))}); its record keeps the last error it had.`)}}}}async function q1t(e,t,n){let r;try{r=await nL(e,t,n)}catch(s){throw await i1(e,t,"planned",{},s),s}let o=await l1(t,"prepared",{synth_tree:r.synthTree,synth_sha:r.synthSha,manifest_digest:r.manifestDigest,...n!==t.base_sha?{base_sha:n}:{},counts:r.counts});return e.out(`Prepared re-pull #${t.id}: commit ${r.synthSha.slice(0,12)}.`),o}function sL(e){return{synth_tree:e.synth_tree,synth_sha:e.synth_sha,manifest_digest:e.manifest_digest}}async function eL(e){if(e.last_error===null||!e.last_error.startsWith(tL))return e;return l1(e,"prepared",sL(e))}async function B1t(e,t,n){let r=sL(t);if(n!==t.base_sha){let a;try{a=await nL(e,t,n)}catch(c){throw await i1(e,t,"prepared",r,c),c}return e.out(`Re-pull #${t.id} prepared again onto the live main.`),l1(t,"prepared",{synth_tree:a.synthTree,synth_sha:a.synthSha,manifest_digest:a.manifestDigest,base_sha:n,counts:a.counts})}let o=await U1t(e.paths.repo,r.synth_sha,r.synth_tree);if(o===null){if(e.out(`Re-pull #${t.id} is prepared, and its working clone holds its commit.`),!D1t(e.paths.bundle))await KM(e.paths.repo,e.paths.bundle,n);return eL(t)}e.out(`Re-pull #${t.id}'s working clone is not usable (${o}).`);let s=await mD({dir:e.paths.repo,bundle:e.paths.bundle,originUrl:xi(e.datasetId,e.env),baseSha:n,token:e.token,annexCommit:Br(e.body).annexCommit,synthSha:r.synth_sha,synthTree:r.synth_tree});if(s===null)return e.out(`Re-pull #${t.id} is prepared; its working clone was restored from the checkpoint.`),eL(t);e.out(`Re-pull #${t.id}'s checkpoint was not used (${s}); preparing again.`);let i;try{i=await nL(e,t,n)}catch(a){throw await i1(e,t,"prepared",r,a),a}if(i.synthTree!==r.synth_tree||i.synthSha!==r.synth_sha||i.manifestDigest!==r.manifest_digest){let a=new I("prepare-not-reproducible",`Preparing again from the same plan and base gave another tree, commit or copy manifest than the one recorded; this re-pull cannot continue: end its record with nemar admin repull abandon ${e.datasetId} and plan the dataset again.`);throw await i1(e,t,"prepared",r,a),a}return e.out(`Re-pull #${t.id} is prepared; its working clone was prepared again, to the same commit.`),eL(t)}async function U1t(e,t,n){let r,o;try{r=(await ee(e,["rev-parse","--verify","--quiet","HEAD"],{ok:!0})).stdout,o=(await ee(e,["rev-parse","--verify","--quiet","HEAD^{tree}"],{ok:!0})).stdout}catch{return"no-working-clone"}return r.trim()===t&&o.trim()===n?null:"clone-at-another-commit"}async function l1(e,t,n,r){try{return await rr(e.id,{from:e.status,to:t,fields:n,...r?{error:r}:{}})}catch(o){if(o instanceof L)throw rL(o);throw o}}async function i1(e,t,n,r,o){try{await rr(t.id,{from:n,to:n,fields:r,error:T1t(o).slice(0,2000)})}catch(s){e.out(`The failure could not be recorded on re-pull #${t.id} (${pn(s)??(s instanceof L?`HTTP ${s.statusCode}`:xo(s))}); its record keeps the last error it had.`)}}async function nL(e,t,n){let{body:r,datasetId:o,paths:s}=e,i=Br(r),a=await oL(e.automatic,"clone",()=>WM({dir:s.repo,originUrl:xi(o,e.env),baseSha:n,token:e.token,annexCommit:i.annexCommit})),c=Ap(await Cp(a),o);if(c.problem!==null)throw new I("nemar-s3-invalid",c.problem);let l=c.record?.bucket;if(!c.uuid||!l)throw new I("no-nemar-s3","NEMAR's remote.log names no single nemar-s3 bucket.");let d=`${o}/objects/`;if(kD(r).destinationPrefix!==d||c.prefix!==d)throw new I("destination-prefix",`The plan's destination is not ${d}, the only prefix a re-pull uploads to.`);let f=Bj({bucket:l,datasetId:o,region:c.region,remoteUuid:c.uuid,workDir:s.upload}),p=UR({baseUrl:e.objectsBase}),m=await hr(a),h=await xSe(a,n,m),g=new Set(m.values()),y=x_(s.root,"scratch");Ps(y),vo(y,s.root);let b=await xke({work:a,body:r,upstreamBare:x_(e.plannerDir,"upstream.git"),upstreamEnv:As(oy(i.ds,e.env),null),computed:e.computed,reader:p,scratch:y});if(b.nemarOwned.left.length>0)e.out(`NEMAR-owned edit(s) the plan listed and the preparation left as they are: ${b.nemarOwned.left.length} (${b.nemarOwned.left.join(", ")}).`);let _=new Set(b.deltaPaths),x=await ee(a,["ls-files","-z","--",Os,gi]);for(let P of x.stdout.split("\x00"))if(P)_.add(P);let k=Yj(t.created_at);await vke(a,n,_,k);let v=new Map;for(let[P,O]of await Jj(a))if(_.has(P))v.set(P,O);let{scrub:C,uploaded:T}=await _Se({work:a,datasetId:o,scope:_,body:r,oursKeys:g,annexFromGit:b.annexFromGit,reader:p,upload:f,bucket:l,now:k,maxBytes:e.normalizeMaxBytes,upstreamBare:x_(e.plannerDir,"upstream.git")});Ps(y);let V=w_(r,g),A=await vSe({work:a,baseSha:n,createdAt:t.created_at,body:r,digest:e.digest,scrub:C,uploaded:T,held:V,base:h,expected:b.expected,preScrub:v,scope:_,counts:{written:b.written,deleted:b.deleted}});await KM(a,s.bundle,n);let F=(P)=>P.every((O)=>O.size!==null)?{known:!0,bytes:P.reduce((O,H)=>O+(H.size??0),0)}:{known:!1,bytes:0},M=F(A.manifest.items),U=F(A.manifest.local),B=C.counts;return{synthSha:A.synthSha,synthTree:A.synthTree,manifestDigest:A.manifestDigest,counts:{delta_paths:b.deltaPaths.size,written:b.written,deleted:b.deleted,annex_copy_items:A.manifest.items.length,...M.known?{copy_bytes:M.bytes}:{},local_uploads:A.manifest.local.length,...U.known?{local_upload_bytes:U.bytes}:{},scrubbed_recordings:B.headers_scrubbed,dated_recordings:B.headers_dates_normalized,scrubbed_json:B.json_files_blanked,headers_not_read_nemar_held:B.headers_not_read_nemar_held,headers_not_read_no_source:B.headers_not_read_no_source,json_files_unread:B.json_files_unread,json_files_annexed:B.json_files_annexed,scans_tables_unread:B.scans_tables_unread,headers_dates_unproven:B.headers_dates_unproven,headers_dates_left:B.headers_dates_left,nemar_owned_edits:b.nemarOwned.applied,nemar_owned_edits_left:b.nemarOwned.left.length}}}var k_=`--automatic-dispatch <id> is the central run-upstream-repull workflow's, never an
449
449
  administrator's: the run reads its dispatch from the event file GitHub delivered, reports to the
450
450
  Worker with the dispatch's token, and prints only fixed lines (repull-auto: ...) because its log
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.29-PR2104.e70fa53",
4
+ "version": "0.10.30-PR2105.5c13a80",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",