nemar-cli 0.10.24-PR1976.b970305 → 0.10.24-PR1976.f7bc3db

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.
Files changed (2) hide show
  1. package/dist/index.js +3 -3
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -99,7 +99,7 @@ ${t}`,XHe,QHe,ZHe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=YHe.bind(nul
99
99
  `)}var RI=!1;var{spawn:Mdt}=globalThis.Bun;function Af(e,t=[]){let n=e.replace(jdt,'("$1","<redacted>")');for(let r of t)if(r.length>=Ldt)n=n.split(r).join("<redacted>");return n}function fS(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 zde(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 C(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=Mdt({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??qdt)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=Wh()?[...fS(n),...t.redact??[]]:[];if(Wh()){let y=t.cwd?` (cwd=${t.cwd})`:"";cd(u.dim(Af(`$ ${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([zde(r.stdout,f),zde(r.stderr,f),g])}finally{if(c(),s)clearTimeout(s)}if(Wh()){if(t.sensitiveOutput)cd(u.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())cd(u.dim(Af(p.trimEnd(),d)));if(m.trim())cd(u.yellow(Af(m.trimEnd(),d)))}cd(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 jdt,Ldt=8,qdt=120000;var zt=V(()=>{ze();jdt=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function Udt(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function Vde(e,t=Udt()){return e.installInstructions[t]}function zdt(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function Vdt(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Hdt}async function Gde(e){try{let{exitCode:t,stdout:n,timedOut:r}=await C(e.cmd,{timeout:Vdt()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:zdt(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 Sb(){let e=Object.entries(Hde);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await Gde(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:Vde(n)}}))}async function Wde(){let t=(await Sb()).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 Of(e){let n=Bdt[e].map((i)=>Hde[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await Gde(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:Vde(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 Hde,Bdt,Hdt=4000;var $b=V(()=>{zt();Hde={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)"}}},Bdt={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 Jde;var Kde=V(()=>{Jde={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.24-PR1976.b970305",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.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 xs;var Tf=V(()=>{Kde();xs=Jde.version});import{mkdirSync as Wdt,readdirSync as Kdt,unlinkSync as Jdt,writeFileSync as Ydt}from"fs";import{join as CI}from"path";function tfe(){Kh=!0}function ol(){return Kh}function nfe(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Rb(e){efe=e,Dn(`Step: ${e}`)}function Do(){Qde=!0}function rfe(){return Qde}function ce(){if(Zde)return;OI=!0}function Cb(){OI=!1,Zde=!0}function ofe(){return OI}function Dn(e){if(Kh)process.stderr.write(`[debug] ${e}
102
+ `))}var Hde,Bdt,Hdt=4000;var $b=V(()=>{zt();Hde={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)"}}},Bdt={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 Jde;var Kde=V(()=>{Jde={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.24-PR1976.f7bc3db",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.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 xs;var Tf=V(()=>{Kde();xs=Jde.version});import{mkdirSync as Wdt,readdirSync as Kdt,unlinkSync as Jdt,writeFileSync as Ydt}from"fs";import{join as CI}from"path";function tfe(){Kh=!0}function ol(){return Kh}function nfe(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Rb(e){efe=e,Dn(`Step: ${e}`)}function Do(){Qde=!0}function rfe(){return Qde}function ce(){if(Zde)return;OI=!0}function Cb(){OI=!1,Zde=!0}function ofe(){return OI}function Dn(e){if(Kh)process.stderr.write(`[debug] ${e}
103
103
  `)}function eft(e){let t={};for(let[n,r]of Object.entries(e))t[n]=Zdt.has(n.toLowerCase())?"[REDACTED]":r;return t}function ife(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function AI(e,t,n=0){if(n>nft)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>AI(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=AI(o,s,n+1);return r}if(typeof t==="string"){if(tft.test(e))return"[REDACTED]";return t.replace(sfe,ife)}return t}function TI(e){return e.replace(rft,"Bearer [REDACTED]").replace(oft,"[REDACTED_AWS_KEY]").replace(sft,"$1[REDACTED]").replace(ift,"$1$2=[REDACTED]").replace(sfe,ife)}function aft(e){return TI(e)}function Yde(e,t=Qdt){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(AI("",r))}catch{}if(n=TI(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function hS(e){if(!Kh)return;let t=aft(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?eft(e.requestHeaders):void 0,requestBody:Yde(e.requestBody),responseBody:Yde(e.responseBody)};mS.push(n),Dn(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=G(n);mS.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),Dn(`redaction failed for ${e.method} ${t}: ${r}`)}}async function cft(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${xs}`),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=nn();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 Sb();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 PI(){return(await cft()).join(`
104
104
  `)}async function afe(){if(!Kh||pS!==void 0)return;try{pS=await PI()}catch(e){let t=G(e);pS=`(could not build environment report: ${t})`,Dn(`environment snapshot failed: ${t}`)}}function cfe(e){if(Xde.has(e))return{flag:e};for(let t of Xde){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 lft(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=cfe(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 uft(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=cfe(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function dft(e){let t=[];for(let r of uft(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 fft(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${TI(lft(e).join(" "))}`),n.push(""),n.push(pS??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),mS.length===0)n.push(" (none)");else mS.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: ${efe??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
105
105
  `)}
@@ -369,7 +369,7 @@ ${Abe(r[1],s)}
369
369
  `)}
370
370
  `});if(o.exitCode!==0)throw Error(`git fetch of ${n.length} blob(s) failed: ${fp(o)}`);let s=await Pd(this.clone.path,n);for(let i of n){let a=s.get(i);if(!a){t.add(i),this.refused.add(i),this.budget.used-=r.get(i)??0;continue}this.bytes.set(i,a),this.missing.delete(i),this.budget.used+=a.length-(r.get(i)??0)}return t}}class G6{max;used=0;refused=0;constructor(e){this.max=e}claim(e){if(this.used+e>this.max)return this.refused++,!1;return this.used+=e,!0}}async function axe(e){let t=Lw(e.env,"bucket");if(t)try{return{status:"ok",uuid:ivt(z6(t,`${e.prefix}annex-uuid`),"utf8").trim()}}catch(o){let s=o.code;if(s==="ENOENT")return{status:"absent",detail:"no annex-uuid object"};if(s==="EACCES"||s==="EPERM")return{status:"forbidden",detail:s};return{status:"error",detail:s??"read failed"}}let n=`${e.prefix}annex-uuid`.split("/").map(encodeURIComponent).join("/"),r=`https://${e.bucket}.s3.${e.region}.amazonaws.com/${n}`;try{let o=await ID(r,{headers:{"User-Agent":"nemar-cli-repull-plan"},signal:AbortSignal.timeout(15000)});if(o.status===404)return{status:"absent",detail:"HTTP 404"};if(o.status===403)return{status:"forbidden",detail:"HTTP 403"};if(!o.ok)return{status:"error",detail:`HTTP ${o.status}`};return{status:"ok",uuid:(await o.text()).trim()}}catch(o){return{status:"error",detail:o instanceof Error?o.name:"fetch failed"}}}async function cxe(e){let t=new Map,n=Lw(e.env,"bucket");if(n){let i=z6(n,e.prefix),a=[];try{a=avt(i)}catch(c){if(c.code!=="ENOENT")throw c}for(let c of a){let l=cvt(z6(i,c));if(l.isFile())t.set(c,l.size)}return oxe(t,e.prefix)}let r=await rxe(["s3api","list-objects-v2","--bucket",e.bucket,"--prefix",e.prefix,"--region",e.region,"--output","json"],e.env);if(r.exitCode!==0)throw Error(`aws s3api list-objects-v2 failed: ${fp(r)}`);let o=r.stdout.toString("utf8").trim(),s=o?JSON.parse(o):{};for(let i of s.Contents??[]){if(typeof i.Key!=="string"||!i.Key.startsWith(e.prefix))continue;let a=i.Key.slice(e.prefix.length);if(a)t.set(a,typeof i.Size==="number"?i.Size:-1)}return oxe(t,e.prefix)}function oxe(e,t){if(!e.has("annex-uuid"))throw Error(`the listing of ${t} holds no annex-uuid object, so it cannot be told from an empty or partial one`);return e}async function mp(e){return(await Pd(e,["refs/heads/git-annex:remote.log"])).get("refs/heads/git-annex:remote.log")?.toString("utf8")??""}async function lxe(e,t){let n=new Map;if(t.length===0)return n;let r=ep(await mp(e)),o=(i)=>`refs/heads/git-annex:${yw(i)}${bw(i)}.log.rmet`,s=await Pd(e,t.map(o));for(let i of t){let a=s.get(o(i));if(!a)continue;let c=Z$(a.toString("utf8"),r);if(c.length>0)n.set(i,c)}return n}function W6(e){if(typeof e!=="object"||e===null)return null;let t=e,n=t.head??{},r=t.base??{},o=n.repo??null;if(typeof t.number!=="number"||!Number.isSafeInteger(t.number)||t.number<=0||typeof n.ref!=="string"||typeof n.sha!=="string"||!/^[0-9a-f]{40}$/.test(n.sha)||typeof r.ref!=="string")return null;return{number:t.number,state:typeof t.state==="string"?t.state:"",headRef:n.ref,headSha:n.sha,headRepo:o&&typeof o.full_name==="string"?o.full_name:null,baseRef:r.ref}}function Jg(e){switch(e.kind){case"unreachable":return`GitHub could not be reached (${e.detail})`;case"status":return`GitHub answered HTTP ${e.status}`;case"too-many":return"100 or more pull requests are listed, which one page cannot show complete";default:return"GitHub's list of pull requests was unreadable"}}async function Yg(e){let t=e.head?`&head=${encodeURIComponent(`${Hg}:${e.head}`)}`:"",n=`${e.base}/repos/${Hg}/${e.datasetId}/pulls?state=${e.state}${t}&per_page=100`,r;try{r=await(e.fetcher??fetch)(n,{headers:{Authorization:`Bearer ${e.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":e.userAgent??"nemar-cli repull"},signal:AbortSignal.timeout(20000)})}catch(i){return{ok:!1,kind:"unreachable",detail:i instanceof Error?i.name:"fetch failed"}}if(r.status!==200)return{ok:!1,kind:"status",status:r.status};let o=await r.json().catch(()=>null);if(!Array.isArray(o))return{ok:!1,kind:"unreadable"};if(o.length>=100)return{ok:!1,kind:"too-many"};let s=o.map(W6);if(s.some((i)=>i===null))return{ok:!1,kind:"unreadable"};return{ok:!0,pulls:s}}function uxe(e){let{row:t,mapped:n}=e;if(!t)return{ds:null,check:{name:"source",status:"refused",code:"not-found",detail:"no dataset row"}};let r=typeof t.source_id==="string"&&/^ds\d{6}$/.test(t.source_id)?t.source_id:null;if(t.source!=="openneuro")return{ds:null,check:{name:"source",status:"refused",code:"not-a-mirror",detail:`the dataset row's source is ${t.source??"unset"}, not openneuro`}};if(n&&r&&r!==n)return{ds:null,check:{name:"source",status:"refused",code:"source-disagrees",detail:`${e.datasetId} maps to ${n} but the row names ${r}`}};let o=n??r;if(!o)return{ds:null,check:{name:"source",status:"refused",code:"no-source-id",detail:"no upstream ds id"}};return{ds:o,check:{name:"source",status:"ok",detail:o}}}function dxe(e){let t=e.flag?.trim()||void 0,n=(d,f,p=null)=>({tag:p,check:{name:"to-tag",status:"refused",code:d,detail:f}}),r=(d,f)=>({tag:d,check:{name:"to-tag",status:"unchecked",code:"order-unverified",detail:f}});if(t!==void 0&&!Go(t))return n("to-tag-malformed",`${t} is not an OpenNeuro snapshot tag`);let o=mvt(e.upstream),s=o.tag===null?null:Xc(o.tag),i=t!==void 0?Xc(t):s;if(i===null)return n("latest-unknown",`${o.tag===null?o.reason:"no tag"}; name one with --to-tag`);if(!Q$(i))return n("to-tag-unrecordable",`${i} is not a tag the version rows can record, so a re-pull to it could never be proved`);if(!e.mirrorTags.includes(i))return n("mirror-lag",`${i} is not on the GitHub mirror yet`);if(e.fromTag!==null&&kr(i,e.fromTag))return n("nothing-to-pull",`${i} is the mirrored tag`,i);let a=e.upstream,c=e.fromTag??"the mirrored tag (unknown)";if(o.tag===null||s===null||a.kind!=="snapshot"||a.latest===null)return r(i,`OpenNeuro could not say which snapshot is latest (${o.tag===null?o.reason:"no answer"}), so that ${i} is newer than ${c} is not proved`);if(!kr(i,s))return r(i,`${i} is not OpenNeuro's latest snapshot (${s}), so that it is newer than ${c} is not proved`);if(e.fromTag===null)return r(i,`there is no from_tag to order ${i} against`);let l=Z_e(a.latest,a.snapshots,e.fromTag);if(l.kind==="newer")return{tag:i,check:{name:"to-tag",status:"ok",detail:`${i} (OpenNeuro's latest)`}};return r(i,`${pvt(l,i,e.fromTag)}, so OpenNeuro's creation order does not show ${i} is newer; a re-pull to it is not executable`)}function pvt(e,t,n){switch(e.kind){case"same":return`OpenNeuro's list names ${t} as the mirrored ${n}`;case"latest_undated":return`the creation date of OpenNeuro's latest ${t} is unreadable`;case"latest_inconsistent":return`OpenNeuro calls ${t} its latest, but ${e.later} in its own list was created later`;case"recorded_absent":return`the mirrored ${n} is not among OpenNeuro's snapshots`;case"recorded_undated":return`the creation date of the mirrored ${n} is unreadable`;case"list_undated":return`the creation date of ${e.undated} in OpenNeuro's list is unreadable, and it could be newer`;case"not_after":return`OpenNeuro's latest ${t} was not created after the mirrored ${n}`}}function mvt(e){if(e.kind==="error")return{tag:null,reason:e.reason};if(e.kind!=="snapshot")return{tag:null,reason:`OpenNeuro: ${e.reason}`};if(e.latest===null)return{tag:null,reason:"OpenNeuro names no snapshot for this dataset yet"};if(!Go(e.latest.tag))return{tag:null,reason:"OpenNeuro named a latest tag of an unexpected shape"};return{tag:e.latest.tag}}function MD(e){let t=null;for(let n of e){let r=wl(Ug(n));if(!r)continue;let o=`${r.major}.${r.minor}.${r.patch}`;if(t===null||hvt(o,t)>0)t=o}return t}function hvt(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number);for(let o=0;o<3;o++){let s=n[o]-r[o];if(s!==0)return s}return 0}function fxe(e){let t=MD(e.tags),n=e.mainVersion?MD([e.mainVersion]):null;if(e.rows!==null&&e.rows.length===0)return{current:null,next:null,check:{name:"version",status:"refused",code:"never-released",detail:"no version row"}};let r=e.rows?MD(e.rows.map((a)=>a.version)):null,o=[r,t,n].filter((a)=>a!==null),s=MD(o),i=s?fi(s,"major"):null;if(e.rows===null)return{current:s,next:i,check:{name:"version",status:"unchecked",code:"rows-unavailable",detail:`version rows could not be read; tag ${t??"none"}, main ${n??"none"}`}};if(r===null||t===null||n===null||r!==t||t!==n)return{current:s,next:i,check:{name:"version",status:"refused",code:"versions-disagree",detail:`row ${r??"none"}, tag ${t??"none"}, main ${n??"none"}`}};return{current:r,next:i,check:{name:"version",status:"ok",detail:`${r} -> ${i}`}}}async function pxe(e){let t=e.nextVersion?`refs/heads/release/v${e.nextVersion}`:null,n=e.branches.filter((a)=>a.startsWith("refs/heads/release/")),r=e.token?await Yg({token:e.token,base:e.apiBase,datasetId:e.datasetId,state:"open",fetcher:ID,userAgent:"nemar-cli-repull-plan"}):null,o={branches:n,pulls:r?.ok?r.pulls:null,...r?.ok?{}:{pullsUnread:r?Jg(r):"no GitHub token"}},s=(a)=>({check:a,facts:o});if(t&&e.branches.includes(t))return s({name:"release-pr",status:"refused",code:"release-branch-exists",detail:`${t.slice(11)} exists`});if(!r)return s({name:"release-pr",status:"unchecked",code:"no-token",detail:"no GitHub token"});if(!r.ok)switch(r.kind){case"unreachable":return s({name:"release-pr",status:"unchecked",code:"github-unreachable",detail:r.detail});case"status":return s({name:"release-pr",status:"unchecked",code:"github-error",detail:`HTTP ${r.status}`});case"too-many":return s({name:"release-pr",status:"unchecked",code:"too-many-open",detail:"100 or more open"});default:return s({name:"release-pr",status:"unchecked",code:"github-error",detail:"unreadable answer"})}let i=r.pulls.filter((a)=>a.headRef.startsWith("release/"));if(i.length>0)return s({name:"release-pr",status:"refused",code:"release-pr-open",detail:i.map((a)=>`#${a.number} (${a.headRef})`).join(", ")});return s({name:"release-pr",status:"ok",detail:`${r.pulls.length} open, none a release`})}function mxe(e){if(e.remoteUuids.length===0)return{name:"annex-uuid",status:"refused",code:"no-nemar-s3-remote",detail:"remote.log names none"};if(e.remoteUuids.length>1)return{name:"annex-uuid",status:"refused",code:"nemar-s3-ambiguous",detail:`remote.log names ${e.remoteUuids.length}: ${e.remoteUuids.join(", ")}`};let t=e.remoteUuids[0],n=e.marker;if(!n)return{name:"annex-uuid",status:"unchecked",code:"no-bucket",detail:"nemar-s3 is not an S3 remote"};if(n.status!=="ok")return{name:"annex-uuid",status:"unchecked",code:`marker-${n.status}`,detail:n.detail};if(n.uuid!==t)return{name:"annex-uuid",status:"refused",code:"annex-uuid-mismatch",detail:`bucket marker ${n.uuid}, remote.log nemar-s3 ${t}`};return{name:"annex-uuid",status:"ok",detail:t}}var hxe=".nemar/metadata.json",wvt=5368709120,_vt=/^[a-z]{2}\d{6}$/;class mo extends Error{constructor(e){super(e);this.name="RepullCannotPlan"}}function xvt(e,t){let n=!1,r=()=>{if(n)return;if(n=!0,!t)yvt(e,{recursive:!0,force:!0,maxRetries:5,retryDelay:50})},o=(s)=>{nxe(),r(),process.exit(s==="SIGINT"?130:143)};return process.on("SIGINT",o),process.on("SIGTERM",o),()=>{process.off("SIGINT",o),process.off("SIGTERM",o),r()}}async function Xg(e){let t=e.env??process.env,n=e.datasetId;if(!_vt.test(n))throw new mo(`${n} is not a dataset id`);let r=uxe({datasetId:n,mapped:GF(n),row:e.catalog.dataset});if(!r.ds)return{planned:!1,preflight:[r.check],reason:r.check.code??"source",workdir:null};let o=r.ds,s=Vg(o,t),i=pi(n,t),a=Gg(s,null),c=Gg(i,e.github.token),l=await O_e(o,{graphqlUrl:e.openNeuroGraphqlUrl,attempts:2,retryDelayMs:1000}),d,f;try{d=await H6(s,["refs/tags/*","refs/heads/git-annex"],a),f=await H6(i,["refs/heads/main","refs/heads/git-annex","refs/heads/release/*","refs/tags/v*"],c)}catch(_){throw new mo(`could not list the remotes: ${_ instanceof Error?_.message:String(_)}`)}if(!f.has("refs/heads/main")||!f.has("refs/heads/git-annex"))throw new mo(`${n} has no main or no git-annex branch`);let p=[...d.keys()].filter((_)=>_.startsWith("refs/tags/")).map((_)=>_.slice(10)),m=[...f.keys()].filter((_)=>_.startsWith("refs/tags/v")).map((_)=>_.slice(10)),h=[...f.keys()].filter((_)=>_.startsWith("refs/heads/release/")),g=gvt(K6(e.workRoot??bvt(),`nemar-repull-${n}-`)),y=e.keepWorkdir===!0,b=xvt(g,y);try{let _=await V6({url:i,dest:K6(g,"nemar.git"),branch:"main",extra:["refs/heads/git-annex"],token:e.github.token}),x=await U_e({rows:e.catalog.versions,highestTag:vvt(m),flag:e.fromTag,ds:o,readTagged:async(K)=>{let _t=`refs/tags/v${K}`;if(!f.has(_t))return;if((await Fo(["fetch","--quiet","--depth=1","--no-tags","origin",`+${_t}:${_t}`],{cwd:_.path,env:_.env})).exitCode!==0)throw new mo(`could not fetch ${_t}`);let wo=`${_t}:${En}`,Zi=(await Pd(_.path,[wo])).get(wo);if(!Zi)return;try{return JSON.parse(cs(Zi.toString("utf8")))}catch{return null}}}),k=dxe({flag:e.toTag,mirrorTags:p,fromTag:x.tag,upstream:l}),v=[x.check,k.check].filter((K)=>K.status==="refused"&&K.code!=="from-tag-not-recorded");if(x.tag===null||k.tag===null||v.length>0)return{planned:!1,preflight:[r.check,x.check,k.check],reason:(v[0]??x.check).code??"preflight",workdir:y?g:null};let R=x.tag,T=k.tag;if(!p.includes(R))throw new mo(`the mirrored tag ${R} is not on the GitHub mirror`);let H=d.has("refs/heads/git-annex"),A=await V6({url:s,dest:K6(g,"upstream.git"),branch:T,extra:[`refs/tags/${T}`,`refs/tags/${R}`,...H?["refs/heads/git-annex"]:[]]});for(let K of[A.path,_.path])if(await ixe(K)!=="sha1")throw new mo("only SHA-1 repositories are planned");let F=await Wg(A.path,`refs/tags/${R}`),M=await Wg(A.path,`refs/tags/${T}`),U=await Wg(_.path,"refs/heads/main"),B=await Wg(_.path,"refs/heads/git-annex"),P=H?await Wg(A.path,"refs/heads/git-annex"):null,[O,z,re]=await Promise.all([pp(A.path,F.commit),pp(A.path,M.commit),pp(_.path,U.commit)]),ke=new G6(e.maxFetchBytes??wvt),Yt=new FD(A,await Kg(A.path,[F.commit,M.commit]),ke),ft=new FD(_,await Kg(_.path,[U.commit]),ke),Ze=re.get(En);if(Ze)await ft.load([Ze.oid]);let oe=Ze?Evt(ft.get(Ze.oid)):null,je=typeof oe?.Version==="string"?Ug(oe.Version):null,Ie=fxe({rows:e.catalog.versions,tags:m,mainVersion:je});if(Ie.next===null)return{planned:!1,preflight:[r.check,x.check,k.check,Ie.check],reason:Ie.check.code??"version",workdir:y?g:null};let Q=[],pt=Bg(e.catalog.dataset?.concept_doi),Be=Bg(typeof oe?.DatasetDOI==="string"?oe.DatasetDOI:null);if(pt!==null&&Be!==null&&pt!==Be)Q.push({code:"concept-doi-disagrees",detail:`the catalog's concept DOI is ${pt} and main's DatasetDOI is ${Be}`});let W=TD(_.env),J=new Map,le=async(K)=>{let _t=K.filter((wo)=>!J.has(wo));if(_t.length===0)return;let Yn=await kd(_.path,"refs/heads/git-annex",_t,W);_t.forEach((wo,Zi)=>J.set(wo,Yn[Zi]??""))},ne=await Y_e({base:O,theirs:z,ours:re,upstream:Yt,nemar:ft,ds:o,toTag:T,nextVersion:Ie.next,conceptDoi:pt,prepareDeadKeys:le,deadAtNemar:(K)=>li(J.get(K)??""),collect:e.collect}),Ue=hp(await mp(_.path),n),{uuids:It,uuid:dr,record:Ac,region:Re,prefix:ot}=Ue,On=new Map;for(let K of ne.decisions){if(!K.delta||K.target.kind!=="annex"&&K.target.kind!=="unannex")continue;let _t=On.get(K.target.key)??{paths:[],purpose:K.target.kind==="annex"?"copy":"unannex"};if(K.target.kind==="annex")_t.purpose="copy";_t.paths.push(K.path),On.set(K.target.key,_t)}await le([...On.keys()]);let Ll=null;if(e.presence==="bucket-listing"){if(!Ac?.bucket)throw new mo("nemar-s3 names no bucket, so there is no bucket to list");try{Ll=await cxe({bucket:Ac.bucket,region:Re,prefix:ot,env:t})}catch(K){throw new mo(`the bucket listing failed: ${K instanceof Error?K.message:String(K)}`)}}let ps=(K,_t)=>Ll?sr(K,Ll):dr!==null&&qi(_t).has(dr)||ne.oursKeys.has(K),xy=[],M_=[],i3=0;for(let[K,{paths:_t,purpose:Yn}]of[...On].sort(([wo],[Zi])=>wo<Zi?-1:1)){let wo=J.get(K)??"";if(li(wo)){if(_t.every((Zi)=>Io.test(Zi)))M_.push(K);else Q.push({code:"target-names-dead-key",detail:`${_t.length} path(s) would name a key NEMAR's git-annex branch marks dead`});continue}if(Yn==="copy"&&ps(K,wo)){i3++;continue}xy.push({key:K,purpose:Yn})}if(M_.length>0)Q.push({code:"dead-recording-unpinned",detail:`${M_.length} recording(s) N.0.0 would name carry a key NEMAR's git-annex branch marks dead, and no upstream version is pinned to scrub them from`});let iCe=H?await lxe(A.path,xy.map((K)=>K.key)):new Map,a3=[],j_=[],J1=0,Y1=0,X1=0,c3=0;for(let{key:K,purpose:_t}of xy){let Yn=[...iCe.get(K)??[]].filter((Zi)=>Zi.bucket===tp).pop()??null,wo=No(K)?.size??null;if(_t==="copy")if(X1++,wo===null)Y1++;else J1+=wo;else c3++;if(!Yn)j_.push(K);a3.push({key:K,purpose:_t,paths:[...On.get(K)?.paths??[]].sort(),size:wo,pin:Yn?{bucket:Yn.bucket,object:Yn.object,version:Yn.version}:null})}let vy=ne.decisions.filter((K)=>K.delta&&K.target.kind==="annex-from-git").map((K)=>{let _t=K.target;return{path:K.path,oid:_t.oid,size:_t.size}}),l3=vy.reduce((K,_t)=>K+(_t.size??0),0),u3=vy.filter((K)=>K.size===null).length,Wd=await $vt(re,ft),L_=ne.decisions.filter((K)=>K.class==="conflict"),Mp=ne.decisions.filter((K)=>K.class==="correction"),q_=ne.decisions.filter((K)=>K.class==="unchecked"),Q1=L_.length+Mp.length+q_.length;if(Wd.status==="unreadable")Q.push({code:"ledger-unreadable",detail:`${uo} does not parse as a ledger: ${Wd.error}`});else if(Wd.recordedCorrections>0&&Q1>0)Q.push({code:"ledger-correction-unexplained",detail:`the ledger records ${Wd.recordedCorrections} correction(s) and ${Q1} path(s) are unexplained; a re-pull could revert one, so it refuses with no override`});if(ne.gitlinks.length>0)Q.push({code:"gitlink",detail:`${ne.gitlinks.length} submodule path(s)`});let d3=ne.decisions.filter((K)=>K.target.kind==="unknown");if(d3.length>0)Q.push({code:"target-unknown",detail:`${d3.length} path(s) whose N.0.0 content could not be computed`});if(ne.fetchRefused>0)Q.push({code:"fetch-bound",detail:`${ne.fetchRefused} blob(s) a check needed were not fetched (over --max-fetch-gb, or not delivered); ${q_.length} path(s) are unchecked`});let f3=await pxe({datasetId:n,nextVersion:Ie.next,branches:h,token:e.github.token,apiBase:e.github.apiBase}),aCe=Ac?.bucket?await axe({bucket:Ac.bucket,region:Re,prefix:ot,env:t}):null,p3=[r.check,x.check,k.check,Ie.check,f3.check,mxe({remoteUuids:It,marker:aCe})],B_=Rvt(ne.decisions),cCe=new Set(B_.map((K)=>K.from)),lCe=new Set(B_.map((K)=>K.to)),Kd=ne.decisions.filter((K)=>K.delta),m3=ne.decisions.filter((K)=>K.deleted),h3=(K)=>ne.sides.get(K.path)?.ours??{kind:"absent"},g3=(K)=>K.delta&&h3(K).kind==="absent",Z1=Kd.filter((K)=>Io.test(K.path)),y3=0,b3=0;for(let K of Z1){let _t=K.target,Yn=_t.kind==="annex"?No(_t.key)?.size??null:_t.kind==="annex-from-git"?_t.size:0;if(Yn===null)b3++;else y3+=Yn}let w3=X1>0||vy.length>0||[...Kd,...m3].some((K)=>{let _t=h3(K),Yn=K.target;return _t.kind==="annex"||Yn.kind==="annex"||Yn.kind==="annex-from-git"||Yn.kind==="unannex"||Co(K.path,0)}),_3=(K)=>{let _t={};for(let Yn of K)_t[Yn.subtype??"none"]=(_t[Yn.subtype??"none"]??0)+1;return _t},eC=ne.description.keys,uCe={added:Kd.filter((K)=>g3(K)&&!lCe.has(K.path)).length,changed:Kd.filter((K)=>!g3(K)).length,deleted:m3.filter((K)=>!cCe.has(K.path)).length,renamed:B_.length,delta_paths:Kd.length,upstream_changed:ne.decisions.filter((K)=>K.upstreamChanged).length,unexplained:Q1,corrections:Mp.length,corrections_by_subtype:_3(Mp),conflicts:L_.length,conflicts_by_subtype:_3(L_),unchecked:q_.length,description_corrections:eC.filter((K)=>K.class==="correction").length,description_conflicts:eC.filter((K)=>K.class==="conflict").length,copy_items:X1,copy_bytes:J1,copy_bytes_unknown:Y1,copy_unpinned:j_.length,copy_already_held:i3,unannex_items:c3,local_uploads:vy.length,local_bytes:l3,local_bytes_unknown:u3,orphan_bytes_max:J1+l3+y3,orphan_bytes_unknown:Y1+u3+b3,data_changing:w3,metadata_only:!w3,doi_count:Mp.length>0?2:1,fetched_bytes:ke.used,fetch_refused:ne.fetchRefused},dCe={recordings_to_read:Z1.length,json_files_to_read:Kd.filter((K)=>ap.test(K.path)&&(K.target.kind==="git"||K.target.kind==="description")).length,scans_tables_to_read:Kd.filter((K)=>cp.test(K.path)&&K.target.kind==="git").length,non_sha256e_recordings:Z1.filter((K)=>K.target.kind==="annex"&&No(K.target.key)?.backend!=="SHA256E").length},x3=ne.gitlinks.length===0&&ne.decisions.every((K)=>K.explainedBy.base!==null)&&ne.description.explainedBase,fCe=Mp.length>0?fi(Ie.next,"patch"):null,v3={planner:fw,dataset:n,upstream:{ds:o,from_tag:R,to_tag:T,from_tag_source:x.source,from_commit:F.commit,from_tree:F.tree,to_commit:M.commit,to_tree:M.tree,annex_commit:P?.commit??null},nemar:{main_commit:U.commit,main_tree:U.tree,annex_commit:B.commit,concept_doi:pt},versions:{current:Ie.current,n0:Ie.next,n1:fCe},lineage:{holds:x3,recordable:x3&&x.source!=="flag"},paths:ne.decisions.map(Cvt),renames:B_.map((K)=>({from:K.from,to:K.to})),description:{status:ne.description.status,keys:eC.map((K)=>({...K})),source_datasets:{kept:ne.description.sourceDatasets.kept,added_by_nemar:ne.description.sourceDatasets.addedByNemar,removed_by_upstream:ne.description.sourceDatasets.removedByUpstream},merged_json:ne.description.mergedJson},corrections:Mp.map((K)=>({path:K.path,group:K.group,subtype:K.subtype})),conflicts:L_.map((K)=>({path:K.path,group:K.group,subtype:K.subtype})),unchecked:q_.map((K)=>({path:K.path,group:K.group,subtype:K.subtype})),copy:{presence_basis:Ll?"bucket-listing":"location-log",destination_prefix:ot,items:a3,unpinned:j_,dead_recordings:M_},local_uploads:vy,scrub_forecast:dCe,ledger:{status:Wd.status,lines:Wd.lines,recorded_corrections:Wd.recordedCorrections},nemar_owned_edits:await Dvt(re,ft,o,T),counts:uCe,refusals:Q},pCe=p3.every((K)=>K.status==="ok")&&j_.length===0&&Q.length===0;return{planned:!0,file:{schema:uw,version:dw,digest:dc(v3),created_at:(e.now??new Date).toISOString(),environment:e.environment,sources:ND(t,e.openNeuroGraphqlUrl),preflight:p3,executable:pCe,body:v3},workdir:y?g:null,release:f3.facts}}finally{b()}}function vvt(e){let t=null;for(let n of e){let r=/^v(\d+)\.(\d+)\.(\d+)$/.exec(n);if(!r)continue;let o=[Number(r[1]),Number(r[2]),Number(r[3])];if(!t||kvt(o,t.parts)>0)t={tag:n,parts:o}}return t?.tag??null}function kvt(e,t){for(let n=0;n<3;n++){let r=e[n]-t[n];if(r!==0)return r}return 0}function Evt(e){if(!e)return null;try{let t=JSON.parse(cs(e.toString("utf8")));return t&&typeof t==="object"&&!Array.isArray(t)?t:null}catch{return null}}function hp(e,t){let n=Dg(e,Og),r=n.length===1?n[0]??null:null,o=r?ep(e).get(r):void 0;return{uuids:n,uuid:r,record:o,region:o?Svt(e,o.uuid)??"us-east-2":"us-east-2",prefix:o?.fileprefix??`${t}/objects/`}}function Svt(e,t){let n=null;for(let r of e.split(`
371
371
  `)){let o=r.trim().split(/\s+/);if(o[0]!==t)continue;let s=o.find((i)=>i.startsWith("datacenter="));if(s)n=s.slice(11)}return n}function gxe(e){return e instanceof Error&&/^[A-Za-z]{1,40}$/.test(e.name)?e.name:"unparseable"}async function $vt(e,t){let n=e.get(uo);if(!n)return{status:"absent",lines:0,recordedCorrections:0,error:null};await t.load([n.oid]);let r=t.get(n.oid);if(!r)return{status:"unreadable",lines:0,recordedCorrections:0,error:"its blob is not in the clone (1 MiB or larger)"};try{let o=gw(r.toString("utf8"));return{status:"ok",lines:o.length,recordedCorrections:o.filter((s)=>!J$.has(s.action)).length,error:null}}catch(o){return{status:"unreadable",lines:0,recordedCorrections:0,error:gxe(o)}}}async function Dvt(e,t,n,r){let o=e.get(hxe),s=`10.18112/openneuro.${n}.v${r}`,i=(f,p,m=null)=>[{path:hxe,edit:"is-identical-to",status:f,from:p,to:s,error:m}];if(!o)return i("absent",null);await t.load([o.oid]);let a=t.get(o.oid);if(!a)return i("unreadable",null,"its blob is not in the clone (1 MiB or larger)");let c;try{c=JSON.parse(cs(a.toString("utf8")))}catch(f){return i("unparseable",null,gxe(f))}let l=c?.related_identifiers,d=Array.isArray(l)?l.find((f)=>f?.relation_type==="IsIdenticalTo"):void 0;if(typeof d?.identifier!=="string")return i("no-is-identical-to",null);return i("ok",d.identifier)}function Rvt(e){let t=(i)=>i.kind==="annex"?`A:${i.key}`:i.kind==="git"?`G:${i.oid}`:null,n=(i)=>i.ours.startsWith("A:")?i.ours:i.ours.startsWith("G:")?`G:${i.ours.split(":")[2]}`:null,r=e.filter((i)=>i.delta&&i.ours==="absent"),o=new Set,s=[];for(let i of e.filter((a)=>a.deleted)){let a=n(i);if(!a)continue;let c=r.find((l)=>!o.has(l.path)&&t(l.target)===a);if(!c)continue;o.add(c.path),s.push({from:i.path,to:c.path})}return s}function Cvt(e){return{path:e.path,group:e.group,base:e.base,theirs:e.theirs,ours:e.ours,upstream_changed:e.upstreamChanged,explained_by_base:e.explainedBy.base,explained_by_theirs:e.explainedBy.theirs,class:e.class,subtype:e.subtype,decision:e.decision,target:{...e.target},delta:e.delta,deleted:e.deleted}}function yxe(e){return e.body.counts}function bxe(e){return e.body.upstream}function wxe(e){return e.body.versions}function jD(e){let t=Object.entries(e??{});return t.length===0?"":` (${t.map(([n,r])=>`${n} ${r}`).join(", ")})`}function LD(e,t){let n=Number(t??0);return n>0?`${e} bytes known, plus ${n} of unknown size`:`${e} bytes`}function _xe(e,t){let n=Number(t??0);return n>0?`${e} bytes known, plus ${n} of unknown size, no upper bound`:`at most ${e} bytes`}function Avt(e){return(e.body.nemar_owned_edits??[]).filter((n)=>n.status!=="ok").map((n)=>` ${n.path}: ${n.status}${n.error?` (${n.error})`:""}`)}function Qg(e){return e.map((t)=>` ${t.name.padEnd(11)} ${t.status.padEnd(9)} ${t.code?`${t.code}`:""}${t.detail?`${t.code?": ":""}${t.detail}`:""}`)}function xxe(e,t){let n=yxe(e),r=bxe(e),o=wxe(e),s=e.body.refusals,i=[`Re-pull plan for ${e.body.dataset}: ${r.ds} ${r.from_tag} -> ${r.to_tag} (from ${r.from_tag_source})`,`Versions: ${o.current} -> ${o.n0}${o.n1?`, then ${o.n1} for the corrections`:""}`,"","Paths:",` delta ${n.delta_paths}: added ${n.added}, changed ${n.changed}, renamed ${n.renamed}; deleted ${n.deleted}`,` upstream-changed ${n.upstream_changed}, unexplained ${n.unexplained}`,` conflicts ${n.conflicts}${jD(n.conflicts_by_subtype)}`,` corrections ${n.corrections}${jD(n.corrections_by_subtype)}`,` unchecked ${n.unchecked} (bytes a check needed could not be read)`,` description keys: ${n.description_conflicts} conflict(s), ${n.description_corrections} correction(s)`,"Data:",` copy ${n.copy_items} key(s), ${LD(n.copy_bytes,n.copy_bytes_unknown)}, unpinned ${n.copy_unpinned}, already held ${n.copy_already_held}; un-annexed from upstream ${n.unannex_items}`,` local uploads ${n.local_uploads}, ${LD(n.local_bytes,n.local_bytes_unknown)}`,` orphan bytes if abandoned: ${_xe(n.orphan_bytes_max,n.orphan_bytes_unknown)}; ${n.data_changing?"data-changing":"metadata-only"}; DOIs ${n.doi_count}`,` fetched ${n.fetched_bytes} bytes of large blobs; ${n.fetch_refused} needed and not fetched`,"","Preflight:",...Qg(e.preflight)],a=Avt(e);if(a.length>0)i.push("","NEMAR-owned edits that could not be read:",...a);if(s.length>0)i.push("","Refusals:",...s.map((c)=>` ${c.code}: ${c.detail}`));return i.push("",`Digest: ${e.digest}`,`Executable: ${e.executable?"yes":"no"}`,...t?[`Plan file: ${t}`]:[]),i}function vxe(e){let t=yxe(e),n=bxe(e),r=wxe(e),o=(i,a)=>`| ${i} | ${a} |`,s=e.body.refusals;return[`**Re-pull plan, ${e.body.dataset}** (${n.ds} ${n.from_tag} to ${n.to_tag}, ${r.current} to ${r.n0}${r.n1?` and ${r.n1}`:""})`,"","| Count | Value |","|---|---|",o("delta paths",t.delta_paths),o("added / changed / renamed / deleted",`${t.added} / ${t.changed} / ${t.renamed} / ${t.deleted}`),o("upstream-changed",t.upstream_changed),o("unexplained",t.unexplained),o("conflicts",`${t.conflicts}${jD(t.conflicts_by_subtype)}`),o("corrections",`${t.corrections}${jD(t.corrections_by_subtype)}`),o("unchecked",t.unchecked),o("copy keys / bytes",`${t.copy_items} / ${LD(t.copy_bytes,t.copy_bytes_unknown)}`),o("copy keys unpinned",t.copy_unpinned),o("local uploads / bytes",`${t.local_uploads} / ${LD(t.local_bytes,t.local_bytes_unknown)}`),o("orphan bytes if abandoned",_xe(t.orphan_bytes_max,t.orphan_bytes_unknown)),o("data-changing",t.data_changing?"yes":"no"),o("DOIs",t.doi_count),"",`Preflight: ${e.preflight.map((i)=>`${i.name} ${i.status}${i.code?` (${i.code})`:""}`).join(", ")}.`,`Refusals: ${s.length===0?"none":s.map((i)=>i.code).join(", ")}. Executable: ${e.executable?"yes":"no"}. Digest \`${e.digest.slice(0,19)}\`.`,""].join(`
372
- `)}class N extends Error{code;lines;constructor(e,t,n=[]){super(t);this.code=e;this.lines=n;this.name="ExecuteRefused"}resumable=!1;step}function yc(e,t){if(e instanceof N)e.step??=t;return e}function Y6(e){let t=e.nemar;return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}function Ivt(e,t){if(dc(e)===dc(t))return"equal";let n=Y6(e),r={...t,nemar:{...t.nemar,main_commit:n.main_commit,main_tree:n.main_tree}};return dc(r)===dc(e)?"nemar-only-moved":"different"}function Nvt(e){return e.length>0&&e.every((t)=>t.startsWith(".nemar/")&&t!==".nemar/corrections.jsonl")}function Fvt(e,t){let n=new Set;for(let[r,o]of e){let s=t.get(r);if(!s||s.mode!==o.mode||s.oid!==o.oid)n.add(r)}for(let r of t.keys())if(!e.has(r))n.add(r);return[...n].sort()}function Zg(e){return typeof e==="string"?e:null}function qD(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function kxe(e){let t;try{t=Ovt(e,"utf8")}catch(i){let a=i.code;throw new N("plan-unreadable",`The plan file could not be read${typeof a==="string"?` (${a})`:""}.`)}let n;try{n=q$(t)}catch{throw new N("plan-unreadable","The plan file is not JSON.")}let{file:r,body:o,digest:s}=n;if(r.schema!==uw||r.version!==dw)throw new N("plan-schema",`The file is not a re-pull plan this build reads (${uw} version ${dw}).`);if(o.planner!==fw)throw new N("planner-version",`The plan was made by planner ${String(o.planner)}, and this build executes plans of planner ${fw} only: plan again, so the plan is made under the rules it is executed with.`);if(typeof r.digest!=="string"||r.digest!==s)throw new N("plan-tampered","The plan's body does not hash to the digest the file states, so it is not the plan that was reviewed. Plan again.");return{file:r,body:o}}function BD(e){let{file:t,body:n}=kxe(e),r=Zg(n.dataset);if(!r||!/^[a-z]{2}\d{6}$/.test(r))throw new N("plan-schema","The plan names no dataset id.");return{datasetId:r,digest:t.digest}}function kl(e){if(!e.dataset)throw new N("dataset-missing","The NEMAR API has no dataset row for the plan's dataset.");let t=e.dataset.anonymous;if(t!==0)throw new N(t===1?"anonymous-dataset":"anonymity-unknown",t===1?"An anonymous dataset is never re-pulled: the re-pull takes upstream's authors and README, which would undo the blind.":"The dataset row does not say whether it is an anonymous deposit, and an anonymous one is never re-pulled.")}function gp(e,t){let{file:n,body:r}=kxe(e);if(n.environment!==t.environment)throw new N("plan-environment","The plan was made against another NEMAR API than the one this execution talks to.");let o=ND(t.env,t.openNeuroGraphqlUrl);if(n.sources!==o)throw new N("plan-sources",`The plan was made from ${String(n.sources)} and this execution reads ${o}; a plan made from test bases never executes against the real remotes, nor the reverse.`);return{file:n,body:r}}async function Exe(e,t){let{file:n,body:r}=gp(e,t);kl(t.catalog);let o=qD(r.upstream),s=qD(r.copy),i=Zg(r.dataset),a=Zg(o.to_tag);if(!i||!a)throw new N("plan-schema","The plan names no dataset or no to_tag.");let c;try{c=await Xg({datasetId:i,toTag:a,fromTag:o.from_tag_source==="flag"?Zg(o.from_tag)??void 0:void 0,presence:s.presence_basis==="bucket-listing"?"bucket-listing":"location-log",...t.maxFetchBytes!==void 0?{maxFetchBytes:t.maxFetchBytes}:{},keepWorkdir:!0,workRoot:t.workRoot,env:t.env,catalog:t.catalog,github:t.github,environment:t.environment,openNeuroGraphqlUrl:t.openNeuroGraphqlUrl,collect:t.collect})}catch(f){throw new N("not-planned",f instanceof mo?`The plan could not be made again: ${f.message}.`:`The plan could not be made again: ${f instanceof Error?f.name:"error"}.`)}let l=c.workdir,d=()=>{if(l)Tvt(l,{recursive:!0,force:!0,maxRetries:5,retryDelay:50})};if(!c.planned||!l)throw d(),new N("not-planned",c.planned?"The planner kept no scratch clones.":`Nothing was planned from live sources: ${c.reason}.`,c.planned?[]:Qg(c.preflight));try{let f=Ivt(r,c.file.body),p=null;if(f==="different")throw J6();if(f==="nemar-only-moved"){let h=Zg(Y6(r).main_commit),g=Zg(Y6(c.file.body).main_commit);if(!h||!g)throw J6();let y=await jvt(Pvt(l,"nemar.git"),i,h,g,{env:t.env,token:t.github.token});if(y===null||!Nvt(y))throw J6();p=g}let m=c.file.executable?null:Mvt(c.file,c.release,t);if(!c.file.executable&&m?.ok!==!0){let h=c.file.body.refusals??[],g=qD(c.file.body.copy).unpinned??[];throw new N("not-executable",`The plan is not executable now: ${[...c.file.preflight.filter((y)=>y.status!=="ok").map((y)=>y.code??y.name),...h.map((y)=>String(y.code)),...g.length>0?[`${g.length} unpinned key(s)`]:[]].join(", ")}.`,[...Qg(c.file.preflight),...m&&!m.ok?[`Not superseded: ${m.why}.`]:[]])}return{file:n,body:r,live:c.file,rebasedOnto:p,workdir:l}}catch(f){throw d(),f}}function Mvt(e,t,n){if(!n.ownRelease)return null;let r=e.preflight.filter((a)=>a.status!=="ok"),o=e.body.refusals??[],s=qD(e.body.copy).unpinned??[];if(o.length>0||s.length>0||r.length!==1)return{ok:!1,why:"the plan is not executable for more than the superseded record's own release"};let i=r[0]?.code;if(i!=="release-branch-exists"&&i!=="release-pr-open")return{ok:!1,why:"the plan is not executable for another reason than a release branch or pull request"};return n.ownRelease(t)}function J6(){return new N("plan-stale","The live sources no longer give the reviewed plan: plan again and review the new digest.")}async function jvt(e,t,n,r,o){let s=Gg(pi(t,o.env),o.token);if((await Fo(["fetch","--quiet","--depth=1","--no-tags","origin",n],{cwd:e,env:s})).exitCode!==0)return null;try{let[a,c]=await Promise.all([pp(e,n),pp(e,r)]);return Fvt(a,c)}catch{return null}}var an={name:"NEMAR re-pull",email:"noreply@nemar.org"},El="repull-work";function Uw(e){return e.slice(7,15)}function wc(e,t,n){let r=bc(e,"repull",t),o=bc(r,"work",Uw(n));return{root:o,repo:bc(o,"repo"),plan:bc(o,"plan"),upload:bc(o,"upload"),bundle:bc(r,`${Uw(n)}.bundle`),lock:bc(r,`${Uw(n)}.lock`)}}function ho(e,t){Dxe(e,{recursive:!0,mode:448});for(let n=e;n.startsWith(t);n=zvt(n))if(eM(n,448),n===t)break}var yp={GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_NOSYSTEM:"1"},Hvt=["gc.auto=0","maintenance.auto=false","annex.addunlocked=false","core.autocrlf=false","core.hooksPath=/dev/null","core.attributesFile=/dev/null","core.excludesFile=/dev/null"],UD=0,$xe=[];async function Id(e){if(UD===0)$xe=Object.keys(yp).map((t)=>[t,process.env[t]]),Object.assign(process.env,yp);UD++;try{return await e()}finally{if(UD--,UD===0)for(let[t,n]of $xe)if(n===void 0)Reflect.deleteProperty(process.env,t);else process.env[t]=n}}async function te(e,t,n={}){let r=await C(["git",...t],{cwd:e,...n.stdin!==void 0?{stdin:n.stdin}:{},env:{...yp,...n.env}});if(r.exitCode!==0&&!n.ok)throw new N(n.code??"git-failed",`git ${n.step??t[0]??""} failed in the working clone (exit ${r.exitCode}).`);return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}async function Z6(e,t){return(await C(["git","cat-file","-e",`${t}^{commit}`],{cwd:e,env:{...yp,GIT_NO_LAZY_FETCH:"1"}})).exitCode===0}async function nM(e){Ds(e.dir);let t=Es(e.originUrl,e.token),n=await C(["git","clone","--quiet","--no-tags","--depth=2",...Hvt.flatMap((i)=>["--config",i]),"--branch","main",e.originUrl,e.dir],{env:{...yp,...t}});if(n.exitCode!==0)throw new N("clone-failed",`NEMAR's repository could not be cloned (exit ${n.exitCode}).`);let r=e.dir,o=t?{env:t}:{};if(!await Z6(r,e.baseSha))await te(r,["fetch","--quiet","--no-tags","--depth=2","origin",e.baseSha],{...o,ok:!0});if(!await Z6(r,e.baseSha))throw new N("main-moved","The commit the re-pull bases on is no longer reachable on NEMAR's main: plan again.");await te(r,["config","user.name",an.name]),await te(r,["config","user.email",an.email]),await te(r,["config","commit.gpgsign","false"]),await te(r,["checkout","--quiet","-B",El,e.baseSha],{step:"checkout"}),await te(r,["fetch","--quiet","--no-tags","--depth=1","origin","+refs/heads/git-annex:refs/remotes/origin/git-annex"],{...o,code:"clone-failed",step:"fetch of the git-annex branch"});let s=(await te(r,["rev-parse","--verify","--quiet","refs/remotes/origin/git-annex"],{ok:!0})).stdout.trim();if(e.annexCommit!==null&&s!==e.annexCommit)throw new N("plan-stale","NEMAR's git-annex branch moved since the plan was made again: plan again and review the new digest.");return await te(r,["annex","init","--quiet","--no-autoenable","nemar-repull"],{code:"clone-failed",step:"annex init"}),r}async function rM(e,t,n){Bw(t,{force:!0}),await te(e,["bundle","create","--quiet",t,`refs/heads/${El}`,"refs/heads/git-annex",`^${n}`,"^refs/remotes/origin/git-annex"],{code:"checkpoint-failed",step:"bundle create"}),eM(t,384)}async function zD(e){if(!tM(e.bundle))return"no-checkpoint";let t;try{t=await nM({dir:e.dir,originUrl:e.originUrl,baseSha:e.baseSha,token:e.token,annexCommit:e.annexCommit})}catch{return"clone-failed"}if(e.bundleAnnex&&!await Z6(t,e.bundleAnnex)){let i=Es(e.originUrl,e.token);await te(t,["fetch","--quiet","--no-tags","--depth=1","origin",e.bundleAnnex],{...i?{env:i}:{},ok:!0})}if((await te(t,["bundle","verify","--quiet",e.bundle],{ok:!0})).exitCode!==0)return"checkpoint-unverified";if((await te(t,["fetch","--quiet","--no-tags",e.bundle,`refs/heads/${El}:refs/remotes/checkpoint/${El}`,"refs/heads/git-annex:refs/remotes/checkpoint/git-annex"],{ok:!0})).exitCode!==0)return"checkpoint-unreadable";await te(t,["checkout","--quiet","-B",El,e.synthSha],{ok:!0});let o=async(i)=>(await te(t,["rev-parse","--verify","--quiet",i],{ok:!0})).stdout.trim();if(await o("HEAD")!==e.synthSha||await o("HEAD^{tree}")!==e.synthTree||await o("HEAD^")!==e.baseSha)return"commit-not-in-checkpoint";return(await te(t,["annex","merge","--quiet"],{ok:!0})).exitCode===0?null:"annex-merge-failed"}function Sl(e){for(let t=0;t<3;t++){let n=`${e}.${process.pid}.${Sxe()}.new`;Dxe(n,{mode:448}),Uvt(bc(n,"pid"),`${process.pid}
372
+ `)}class N extends Error{code;lines;constructor(e,t,n=[]){super(t);this.code=e;this.lines=n;this.name="ExecuteRefused"}resumable=!1;step}function yc(e,t){if(e instanceof N)e.step??=t;return e}function Y6(e){let t=e.nemar;return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}function Ivt(e,t){if(dc(e)===dc(t))return"equal";let n=Y6(e),r={...t,nemar:{...t.nemar,main_commit:n.main_commit,main_tree:n.main_tree}};return dc(r)===dc(e)?"nemar-only-moved":"different"}function Nvt(e){return e.length>0&&e.every((t)=>t.startsWith(".nemar/")&&t!==".nemar/corrections.jsonl")}function Fvt(e,t){let n=new Set;for(let[r,o]of e){let s=t.get(r);if(!s||s.mode!==o.mode||s.oid!==o.oid)n.add(r)}for(let r of t.keys())if(!e.has(r))n.add(r);return[...n].sort()}function Zg(e){return typeof e==="string"?e:null}function qD(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function kxe(e){let t;try{t=Ovt(e,"utf8")}catch(i){let a=i.code;throw new N("plan-unreadable",`The plan file could not be read${typeof a==="string"?` (${a})`:""}.`)}let n;try{n=q$(t)}catch{throw new N("plan-unreadable","The plan file is not JSON.")}let{file:r,body:o,digest:s}=n;if(r.schema!==uw||r.version!==dw)throw new N("plan-schema",`The file is not a re-pull plan this build reads (${uw} version ${dw}).`);if(o.planner!==fw)throw new N("planner-version",`The plan was made by planner ${String(o.planner)}, and this build executes plans of planner ${fw} only: plan again, so the plan is made under the rules it is executed with.`);if(typeof r.digest!=="string"||r.digest!==s)throw new N("plan-tampered","The plan's body does not hash to the digest the file states, so it is not the plan that was reviewed. Plan again.");return{file:r,body:o}}function BD(e){let{file:t,body:n}=kxe(e),r=Zg(n.dataset);if(!r||!/^[a-z]{2}\d{6}$/.test(r))throw new N("plan-schema","The plan names no dataset id.");return{datasetId:r,digest:t.digest}}function kl(e){if(!e.dataset)throw new N("dataset-missing","The NEMAR API has no dataset row for the plan's dataset.");let t=e.dataset.anonymous;if(t!==0)throw new N(t===1?"anonymous-dataset":"anonymity-unknown",t===1?"An anonymous dataset is never re-pulled: the re-pull takes upstream's authors and README, which would undo the blind.":"The dataset row does not say whether it is an anonymous deposit, and an anonymous one is never re-pulled.")}function gp(e,t){let{file:n,body:r}=kxe(e);if(n.environment!==t.environment)throw new N("plan-environment","The plan was made against another NEMAR API than the one this execution talks to.");let o=ND(t.env,t.openNeuroGraphqlUrl);if(n.sources!==o)throw new N("plan-sources",`The plan was made from ${String(n.sources)} and this execution reads ${o}; a plan made from test bases never executes against the real remotes, nor the reverse.`);return{file:n,body:r}}async function Exe(e,t){let{file:n,body:r}=gp(e,t);kl(t.catalog);let o=qD(r.upstream),s=qD(r.copy),i=Zg(r.dataset),a=Zg(o.to_tag);if(!i||!a)throw new N("plan-schema","The plan names no dataset or no to_tag.");let c;try{c=await Xg({datasetId:i,toTag:a,fromTag:o.from_tag_source==="flag"?Zg(o.from_tag)??void 0:void 0,presence:s.presence_basis==="bucket-listing"?"bucket-listing":"location-log",...t.maxFetchBytes!==void 0?{maxFetchBytes:t.maxFetchBytes}:{},keepWorkdir:!0,workRoot:t.workRoot,env:t.env,catalog:t.catalog,github:t.github,environment:t.environment,openNeuroGraphqlUrl:t.openNeuroGraphqlUrl,collect:t.collect})}catch(p){throw new N("not-planned",p instanceof mo?`The plan could not be made again: ${p.message}.`:`The plan could not be made again: ${p instanceof Error?p.name:"error"}.`)}let l=c.workdir,d=()=>{if(l)Tvt(l,{recursive:!0,force:!0,maxRetries:5,retryDelay:50})};if(!c.planned||!l)throw d(),new N("not-planned",c.planned?"The planner kept no scratch clones.":`Nothing was planned from live sources: ${c.reason}.`,c.planned?[]:Qg(c.preflight));let f=c.file;try{let p=Ivt(r,f.body),m=null;if(p==="different")throw J6();if(p==="nemar-only-moved"){let g=Zg(Y6(r).main_commit),y=Zg(Y6(f.body).main_commit);if(!g||!y)throw J6();let b=await jvt(Pvt(l,"nemar.git"),i,g,y,{env:t.env,token:t.github.token});if(b===null||!Nvt(b))throw J6();m=y}let h=f.executable?null:Mvt(f,c.release,t);if(!f.executable&&h?.ok!==!0){let g=f.body.refusals??[],y=qD(f.body.copy).unpinned??[];throw new N("not-executable",`The plan is not executable now: ${[...f.preflight.filter((b)=>b.status!=="ok").map((b)=>b.code??b.name),...g.map((b)=>String(b.code)),...y.length>0?[`${y.length} unpinned key(s)`]:[]].join(", ")}.`,[...Qg(f.preflight),...h&&!h.ok?[`Not superseded: ${h.why}.`]:[]])}return{file:n,body:r,live:f,rebasedOnto:m,workdir:l}}catch(p){throw d(),p}}function Mvt(e,t,n){if(!n.ownRelease)return null;let r=e.preflight.filter((a)=>a.status!=="ok"),o=e.body.refusals??[],s=qD(e.body.copy).unpinned??[];if(o.length>0||s.length>0||r.length!==1)return{ok:!1,why:"the plan is not executable for more than the superseded record's own release"};let i=r[0]?.code;if(i!=="release-branch-exists"&&i!=="release-pr-open")return{ok:!1,why:"the plan is not executable for another reason than a release branch or pull request"};return n.ownRelease(t)}function J6(){return new N("plan-stale","The live sources no longer give the reviewed plan: plan again and review the new digest.")}async function jvt(e,t,n,r,o){let s=Gg(pi(t,o.env),o.token);if((await Fo(["fetch","--quiet","--depth=1","--no-tags","origin",n],{cwd:e,env:s})).exitCode!==0)return null;try{let[a,c]=await Promise.all([pp(e,n),pp(e,r)]);return Fvt(a,c)}catch{return null}}var an={name:"NEMAR re-pull",email:"noreply@nemar.org"},El="repull-work";function Uw(e){return e.slice(7,15)}function wc(e,t,n){let r=bc(e,"repull",t),o=bc(r,"work",Uw(n));return{root:o,repo:bc(o,"repo"),plan:bc(o,"plan"),upload:bc(o,"upload"),bundle:bc(r,`${Uw(n)}.bundle`),lock:bc(r,`${Uw(n)}.lock`)}}function ho(e,t){Dxe(e,{recursive:!0,mode:448});for(let n=e;n.startsWith(t);n=zvt(n))if(eM(n,448),n===t)break}var yp={GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_NOSYSTEM:"1"},Hvt=["gc.auto=0","maintenance.auto=false","annex.addunlocked=false","core.autocrlf=false","core.hooksPath=/dev/null","core.attributesFile=/dev/null","core.excludesFile=/dev/null"],UD=0,$xe=[];async function Id(e){if(UD===0)$xe=Object.keys(yp).map((t)=>[t,process.env[t]]),Object.assign(process.env,yp);UD++;try{return await e()}finally{if(UD--,UD===0)for(let[t,n]of $xe)if(n===void 0)Reflect.deleteProperty(process.env,t);else process.env[t]=n}}async function te(e,t,n={}){let r=await C(["git",...t],{cwd:e,...n.stdin!==void 0?{stdin:n.stdin}:{},env:{...yp,...n.env}});if(r.exitCode!==0&&!n.ok)throw new N(n.code??"git-failed",`git ${n.step??t[0]??""} failed in the working clone (exit ${r.exitCode}).`);return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}async function Z6(e,t){return(await C(["git","cat-file","-e",`${t}^{commit}`],{cwd:e,env:{...yp,GIT_NO_LAZY_FETCH:"1"}})).exitCode===0}async function nM(e){Ds(e.dir);let t=Es(e.originUrl,e.token),n=await C(["git","clone","--quiet","--no-tags","--depth=2",...Hvt.flatMap((i)=>["--config",i]),"--branch","main",e.originUrl,e.dir],{env:{...yp,...t}});if(n.exitCode!==0)throw new N("clone-failed",`NEMAR's repository could not be cloned (exit ${n.exitCode}).`);let r=e.dir,o=t?{env:t}:{};if(!await Z6(r,e.baseSha))await te(r,["fetch","--quiet","--no-tags","--depth=2","origin",e.baseSha],{...o,ok:!0});if(!await Z6(r,e.baseSha))throw new N("main-moved","The commit the re-pull bases on is no longer reachable on NEMAR's main: plan again.");await te(r,["config","user.name",an.name]),await te(r,["config","user.email",an.email]),await te(r,["config","commit.gpgsign","false"]),await te(r,["checkout","--quiet","-B",El,e.baseSha],{step:"checkout"}),await te(r,["fetch","--quiet","--no-tags","--depth=1","origin","+refs/heads/git-annex:refs/remotes/origin/git-annex"],{...o,code:"clone-failed",step:"fetch of the git-annex branch"});let s=(await te(r,["rev-parse","--verify","--quiet","refs/remotes/origin/git-annex"],{ok:!0})).stdout.trim();if(e.annexCommit!==null&&s!==e.annexCommit)throw new N("plan-stale","NEMAR's git-annex branch moved since the plan was made again: plan again and review the new digest.");return await te(r,["annex","init","--quiet","--no-autoenable","nemar-repull"],{code:"clone-failed",step:"annex init"}),r}async function rM(e,t,n){Bw(t,{force:!0}),await te(e,["bundle","create","--quiet",t,`refs/heads/${El}`,"refs/heads/git-annex",`^${n}`,"^refs/remotes/origin/git-annex"],{code:"checkpoint-failed",step:"bundle create"}),eM(t,384)}async function zD(e){if(!tM(e.bundle))return"no-checkpoint";let t;try{t=await nM({dir:e.dir,originUrl:e.originUrl,baseSha:e.baseSha,token:e.token,annexCommit:e.annexCommit})}catch{return"clone-failed"}if(e.bundleAnnex&&!await Z6(t,e.bundleAnnex)){let i=Es(e.originUrl,e.token);await te(t,["fetch","--quiet","--no-tags","--depth=1","origin",e.bundleAnnex],{...i?{env:i}:{},ok:!0})}if((await te(t,["bundle","verify","--quiet",e.bundle],{ok:!0})).exitCode!==0)return"checkpoint-unverified";if((await te(t,["fetch","--quiet","--no-tags",e.bundle,`refs/heads/${El}:refs/remotes/checkpoint/${El}`,"refs/heads/git-annex:refs/remotes/checkpoint/git-annex"],{ok:!0})).exitCode!==0)return"checkpoint-unreadable";await te(t,["checkout","--quiet","-B",El,e.synthSha],{ok:!0});let o=async(i)=>(await te(t,["rev-parse","--verify","--quiet",i],{ok:!0})).stdout.trim();if(await o("HEAD")!==e.synthSha||await o("HEAD^{tree}")!==e.synthTree||await o("HEAD^")!==e.baseSha)return"commit-not-in-checkpoint";return(await te(t,["annex","merge","--quiet"],{ok:!0})).exitCode===0?null:"annex-merge-failed"}function Sl(e){for(let t=0;t<3;t++){let n=`${e}.${process.pid}.${Sxe()}.new`;Dxe(n,{mode:448}),Uvt(bc(n,"pid"),`${process.pid}
373
373
  `,{mode:384});try{return X6(n,e),()=>{if(qw(e)===process.pid)Bw(e,{recursive:!0,force:!0})}}catch(s){Bw(n,{recursive:!0,force:!0});let i=s.code;if(i!=="ENOTEMPTY"&&i!=="EEXIST")throw s}let r=qw(e);if(r===void 0)continue;if(r===null||Vvt(r))throw Q6(e,r);let o=`${e}.${process.pid}.${Sxe()}.stale`;try{X6(e,o)}catch{continue}if(qw(o)!==r){try{X6(o,e)}catch{}throw Q6(e,qw(e)??null)}Bw(o,{recursive:!0,force:!0})}throw Q6(e,qw(e)??null)}function qw(e){if(!tM(e))return;let t;try{t=qvt(bc(e,"pid"),"utf8")}catch{return null}let n=Number.parseInt(t,10);return/^\d+\n?$/.test(t)&&Number.isSafeInteger(n)&&n>0?n:null}function Q6(e,t){return new N("execution-locked",`Another execution of this plan holds its lock (${t===null?"its process id cannot be read":`process ${t}`}): ${e}. Wait for it to finish. If no execution is running (a crashed run whose process id is now another process's), remove that directory and run again.`)}function Vvt(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Rxe(e){let t;try{t=Lvt(e)}catch{return}if(!t.isDirectory())return;try{eM(e,t.mode&4095|448)}catch{}for(let n of Bvt(e))Rxe(bc(e,n))}function Ds(e){for(let t=1;tM(e);t++){Rxe(e);try{Bw(e,{recursive:!0,maxRetries:5,retryDelay:50})}catch(n){if(t>=5)throw new N("workdir-busy",`A working directory could not be removed (${n.code??"error"}); is another run using it?`)}}}var bp=20,ls=bp+2,Gvt=".nemar/corrections.jsonl";async function Cxe(e,t,n){let r=await te(e,["diff-tree","-r","-z","--no-commit-id","--raw",t,n],{ok:!0});if(r.exitCode!==0)return null;let o=r.stdout.split("\x00"),s=[];for(let i=0;i+1<o.length;i+=2){let a=/^:([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) ([A-Z])\d*$/.exec(o[i]);if(!a)return null;s.push({srcMode:a[1],dstMode:a[2],srcOid:a[3],dstOid:a[4],status:a[5],path:o[i+1]})}return s}async function zw(e,t,n){let r=await Cxe(e,t,n);if(r===null)return null;return r.map((o)=>o.path).filter((o)=>!o.startsWith(".nemar/")&&!o.startsWith(".github/"))}async function oM(e,t){let n=await te(e,["cat-file","blob",t],{ok:!0});return n.exitCode===0?n.stdout:null}async function Wvt(e,t,n){let r=n.dstMode==="100644";if(n.path.startsWith(".nemar/")&&n.path!==Gvt)return r&&(n.status==="A"||n.status==="M");if(n.path===".bidsignore"){if(!r||n.status!=="A"&&n.status!=="M")return!1;let o=n.status==="A"?"":await oM(e,n.srcOid),s=await oM(e,n.dstOid);if(o===null||s===null)return!1;let i=ll(o,cl);return i.changed&&s===i.content}if(n.path==="participants.tsv"){if(!r||n.status!=="A")return!1;let o=await te(e,["ls-tree","-r","-z","--name-only",t],{ok:!0});if(o.exitCode!==0)return!1;let s=vg(o.stdout.split("\x00").filter(Boolean).map((i)=>({path:i})));if(s.length===0)return!1;return await oM(e,n.dstOid)===kg(s)}return!1}async function _c(e,t,n){if(t===n)return{ok:!0,head:n,commits:0};let r=await te(e,["merge-base","--is-ancestor",t,n],{ok:!0});if(r.exitCode===1)return{ok:!1,code:"head-foreign",detail:"not a descendant of the recorded commit"};if(r.exitCode!==0)return{ok:!1,code:"unreadable",detail:"the commits are not in the working clone"};let o=await te(e,["rev-list","--reverse","--parents",`${t}..${n}`],{ok:!0});if(o.exitCode!==0)return{ok:!1,code:"unreadable",detail:"the commits could not be listed"};let s=o.stdout.split(`
374
374
  `).filter(Boolean).map((i)=>i.split(" "));if(s.length>bp)return{ok:!1,code:"head-foreign",detail:`${s.length} commits`};for(let[i,...a]of s){if(a.length!==1)return{ok:!1,code:"head-foreign",detail:"a merge commit"};let c=await Cxe(e,a[0],i);if(c===null)return{ok:!1,code:"unreadable",detail:"a commit's changes could not be read"};for(let l of c)if(!await Wvt(e,i,l))return{ok:!1,code:"head-foreign",detail:"a commit changes a path enrichment does not write"}}return{ok:!0,head:n,commits:s.length}}lc();import{join as Axe}from"path";function Kvt(e,t,n,r){return Axe(e,"repull",t,r,`${Uw(n)}-${process.pid}`)}async function $l(e){let t=Kvt(e.configDir,e.datasetId,e.digest,e.purpose);Ds(t),ho(t,Axe(e.configDir,"repull"));let n=pi(e.datasetId,e.env);await te(t,["init","--quiet","--bare"],{code:"origin-unreadable",step:"init"});for(let[r,o]of[["gc.auto","0"],["maintenance.auto","false"],["core.hooksPath","/dev/null"]])await te(t,["config",r,o],{code:"origin-unreadable",step:"config"});return await te(t,["remote","add","origin",n],{code:"origin-unreadable",step:"remote"}),{dir:t,env:Es(n,e.token),close:()=>Ds(t)}}async function br(e,t,n){let r=/^[0-9a-f]{40}$/.test(t)?t:`+${t}:${t.replace(/^refs\/(heads|tags)\//,"refs/remotes/origin/$1/")}`;return(await te(e.dir,["fetch","--quiet","--no-tags",`--depth=${n}`,"origin",r],{...e.env?{env:e.env}:{},ok:!0})).exitCode===0}async function Dl(e,t){let n=await te(e.dir,["ls-remote","origin",...t],{...e.env?{env:e.env}:{},code:"origin-unreadable",step:"ls-remote"}),r=new Map,o=new Map;for(let s of n.stdout.split(`
375
375
  `)){let[i,a]=s.split("\t");if(!i||!a||!/^[0-9a-f]{40}$/.test(i))continue;if(a.endsWith("^{}"))o.set(a.slice(0,-3),i);else r.set(a,i)}for(let[s,i]of o)r.set(s,i);return r}import{lstatSync as Jvt,readFileSync as Yvt,readdirSync as Xvt,writeFileSync as Qvt}from"fs";import{join as sM}from"path";var Oxe=200;function Zvt(e){return e.replace(/\s+/g," ").trim()}function VD(e,t){return e==="title"?Zvt(t??""):(t??"").trim()}var ekt=[/^save changes$/,/^update from branch(?: \S+)?$/,/^update [a-z]{2}\d{6} to v?\d+\.\d+\.\d+$/,/^(?:tbd|tba|todo|fixme|n\/a|na|none|null|undefined|untitled|placeholder)$/,/^(?:title|description|message|summary|text|test|testing|asdf|x{3,})$/,/^lorem ipsum\b/],tkt=/^(?:(?:sha\d*|md5|git|commit)[:\s-]*)?(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,64}$/i;function nkt(e){if(!/^[[{]/.test(e)||!/[\]}]$/.test(e))return!1;try{let t=JSON.parse(e);return typeof t==="object"&&t!==null}catch{return!1}}function rkt(e){let t=e.replace(/\s+/g," ").toLowerCase(),n=t.length;while(n>0&&" .!:;,".includes(t.charAt(n-1)))n--;return t.slice(0,n)}function GD(e){let t=e.replace(/\s+/g," ");return`"${t.length>60?`${t.slice(0,57)}...`:t}"`}function iM(e){return`has a citation (an author and a year, or a DOI) in it (${GD(e)}); describe the change in plain words, such as "Add three EEG recordings", and cite the paper in ReferencesAndLinks and the README instead`}function Mxe(e){return`still has an unfilled template field (${GD(e)}); put the real value in its place`}function okt(e,t=iM){let n=f$(e);if(n!==null)return{code:"author_year",reason:t(n)};let r=p$(e);if(r!==null)return{code:"doi",reason:t(r)};let o=eF(e);if(o!==null)return{code:"template_field",reason:Mxe(o)};return null}function aM(e,t){let n=VD(e,t);if(n==="")return{code:"empty",reason:"is empty; say in plain words what changed"};let r=e==="title"?f$(n):null;if(r!==null)return{code:"author_year",reason:iM(r)};let o=e==="title"?p$(n):null;if(o!==null)return{code:"doi",reason:iM(o)};if(tkt.test(n)||nkt(n))return{code:"machine_output",reason:"is a raw hash or JSON; write a sentence that says what changed"};let s=rkt(n);if(ekt.some((a)=>a.test(s)))return{code:"placeholder",reason:`is placeholder text (${GD(n)}); say what actually changed`};let i=e==="title"?eF(n):null;if(i!==null)return{code:"template_field",reason:Mxe(i)};if(!/\p{L}{2,}/u.test(n))return{code:"no_words",reason:"has no words in it; write a sentence that says what changed"};if(e==="title"&&n.length>Oxe)return{code:"too_long",reason:`is ${n.length} characters; keep the title to one line of at most ${Oxe} and put the detail in the description`};return null}function cM(e,t){return`${e} ${t.reason}.`}function WD(e){return okt(e,(t)=>`has an author and a year in it (${GD(t)}): the version added to the title starts with a year, as a calendar version such as 2020.1.0 does, and the review refuses a title that reads that way`)}function jxe(e,t){return`The title as it will be sent, "${e}", ${t.reason}.`}function skt(e){if(e.startsWith("A")||e.startsWith("C"))return"added";if(e.startsWith("D"))return"removed";return"modified"}function Lxe(e){let t=e.split("\x00"),n=[],r=0;while(r<t.length){let o=t[r];if(!o){r++;continue}let s=o.startsWith("R")||o.startsWith("C"),i=t[r+(s?2:1)];if(r+=s?3:2,i)n.push({status:skt(o),path:i})}return n}function qxe(e){let t=e.split("\x00"),n=[];for(let r=0;r<t.length;r++){let o=t[r];if(!o||o.length<4)continue;if(n.push(o.slice(3)),/[RC]/.test(o.slice(0,2)))r++}return n}var HD=20,Txe=10,ikt=["added","modified","removed"];function Hw(e,t){return`${e} ${t}${e===1?"":"s"}`}function Pxe(e){return ikt.map((t)=>[t,e.filter((n)=>n.status===t).length]).filter(([,t])=>t>0).map(([t,n])=>`${n} ${t}`).join(", ")}function Ixe(e,t){return e.path<t.path?-1:e.path>t.path?1:0}function Bxe(e){return`\`${e.replace(/[\u0000-\u001f\u007f`]/g,"?")}\``}function Nxe(e){return`- ${Bxe(e.path)} (${e.status})`}function akt(e){if(e.length===0)return"No files changed.";if(e.length<=HD)return[...e].sort(Ixe).map(Nxe).join(`
@@ -443,7 +443,7 @@ ${b.message}`,r);if(_)return on("message",`The squash message would not carry th
443
443
  `).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 N("upstream-unreadable",`Upstream's tag ${n.toTag} could not be read.`);if(a!==n.toCommit)throw new N("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 uDt(e,t){let{synth_sha:n,synth_tree:r}=t,o=e.paths.repo,s=async(c)=>(await te(o,["rev-parse","--verify","--quiet",c],{ok:!0})).stdout.trim();try{if(await s("HEAD")===n&&await s("HEAD^{tree}")===r)return o}catch{}ho(e.paths.root,eEe(eEe(e.paths.lock)));let i=Tr(e.body).annexCommit,a=await zD({dir:o,bundle:e.paths.bundle,originUrl:pi(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 N("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 dDt(e,t,n){let r=new Set;for(let[i,a]of await OR(e,n.synth_sha))if(!Hi(i))r.add(a);let o=new Set((await OR(e,n.base_sha)).values()),s=nj({named:r,body:t.body,digest:t.digest,held:s_(t.body,o)});if(tj(s)!==n.manifest_digest)throw new N("manifest-mismatch","The copy manifest rebuilt from the synthesized commit is not the one recorded at prepared.");return s}function fDt(e,t,n){let r={};for(let[i,a]of Object.entries(e.env))if(a!==void 0)r[i]=a;let o=aR({commandEnv:r}),s=(i)=>Kxe(cR({region:i,timeoutMs:iR,env:r,credentials:o}),n);return{source:s($ve),dest:s(t)}}function pDt(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 ij(e,t,n){if(t){n(`Working directory kept at ${e.root}; it holds the delta's unscrubbed originals.`);return}try{Ds(e.root)}catch(r){n(`The working directory ${e.root} could not be removed (${r instanceof N?r.code:po(r)}); remove it by hand: it holds the delta's unscrubbed originals.`)}}async function PR(e,t,n,r,o){let s=Date.now();try{return r?.beforeStep?.(e),await o()}catch(i){throw await n.recordError(t,tEe(e,i).slice(0,2000)),yc(cDt(e,i),e)}finally{r?.timed?.(e,Date.now()-s)}}async function aj(e,t,n,r){let o=t;if(Ep(o.status,n))return o;let s=Tr(e.body),i={versions:[s.toVersion]},a=Es(pi(e.datasetId,e.env),e.token),c=await PR(o.status==="prepared"?"copy":o.status==="copied"?"register":"pr",o,r,null,async()=>{let h=await uDt(e,o),g=await lDt(h,e.datasetId),y=await dDt(h,e,o),b={destBucket:g.bucket,prefix:g.prefix,stagingKey:lR(e.datasetId,s.toTag),sourceBucket:tp,sourcePrefix:`${s.ds}/`};return{work:h,remote:g,manifest:y,guard:b,aws:fDt(e,g.region,b)}}),{work:l,remote:d,manifest:f,guard:p,aws:m}=c;if(o.status==="prepared"){let h=await PR("copy",o,r,e,async()=>{if(await sj(l,e),f.items.some((x)=>x.bucket!==tp))throw new N("copy-source","A copy item names another bucket than upstream's.");await Dve({aws:m.dest,bucket:d.bucket,key:p.stagingKey,manifest:f,dir:e.paths.root});let g=await Md(m.dest,d.bucket,d.prefix),y=await Rve({aws:m,manifest:f,destBucket:d.bucket,prefix:d.prefix,existing:g,...e.copy??{}}),b=await Md(m.dest,d.bucket,d.prefix),_=yR(pDt(f,d.bucket,d.prefix),b);if(_.message!==null)throw new N("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.`),Ep(o.status,n))return o}if(o.status==="copied"){let h=await PR("register",o,r,e,async()=>{if(!e.token)throw new N("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 sj(l,e);let g=await Md(m.dest,d.bucket,d.prefix);return Kke({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).`),Ep(o.status,n))return o}if(o.status==="registered"){let h=o.synth_sha,g=Wn(s.toVersion),y=await PR("pr",o,r,e,async()=>{let b=e.token;if(!b)throw new N("no-github-token","No GitHub token: the pull request is opened with the administrator's own (GH_TOKEN, or gh auth login).");await sj(l,e),await Rl({work:l,baseSha:o.base_sha,env:a});let _=await YD({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)"}.`),XD({token:b,base:e.apiBase,datasetId:e.datasetId,version:s.toVersion,body:Yxe({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:kc(e.body).doi_count??1,counts:o.counts}),acceptHead:(x)=>Rs({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.`),ij(e.paths,e.keepWorkdir,e.out)}return o}We();var nEe=300000,rEe=15000,oEe=30;async function sEe(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 N("repull-not-ready",`Re-pull #${r.id} is ${r.status}, not an open pull request with a recorded head.`);let o=Wn(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 Jr(r,`${hF}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 Dl(e.scratch,[o])).get(o)??null,b===null)p="branch-absent"}catch(x){p=mDt(x)}if(b===null)g++;else if(b===r.head_sha)f=t(),d??=f;else{let x=await Rs({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 Jr(r,`${hF}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 hDt(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 mDt(e){if(e instanceof N)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 hDt(e,t){try{return await Qn(e.id,{from:"pr_open",to:"pr_open",fields:{branch:e.branch,pr_number:e.pr_number,head_sha:t}})}catch(n){let r=Cn(n),o=new N(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 dEe=["planned","prepared"];function wDt(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 N("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 dj(e){let t=Cn(e);return new N(t??"record-refused",`The NEMAR API refused the record${t?` (${t})`:""}: ${e instanceof Error?e.message:String(e)}`)}var lj="[prepare:";function _Dt(e){if(e instanceof N)return`${lj}${e.code}] ${e.message}`;return`${lj}prepare-failed] The preparation failed: ${po(e)}.`}function iEe(e,t){try{Ds(e)}catch(n){t(`The scratch directory ${e} could not be removed (${n instanceof N?n.code:po(n)}); remove it by hand.`)}}function aEe(e){try{if(yDt(e).length===0)bDt(e)}catch{}}async function MR(e){let t=e.env??process.env,n=e.until??"pr_open";if(!fs.includes(n))throw new N("until-not-allowed",`Execution stops at ${fs.join(", ")}; it never goes past the open pull request.`);return Id(()=>vDt(e,t,n))}function fEe(e,t){if(t.origin!=="automatic")throw yc(new N("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 yc(new N("repull-mismatch",`The dispatch continues re-pull #${e.repullId}, and the record found is #${t.id}.`),"record")}async function IR(e,t,n,r,o){if(!e.automatic||o.status!=="pr_open")return;let s=await $l({configDir:Hn(),datasetId:o.dataset_id,digest:r,purpose:"settle",env:t,token:n}),i=e.automatic;try{return await fj(i,"settle",()=>sEe({scratch:s,row:o,opts:i.settle,out:e.out,deadlineMs:(i.tokenSince+ow)*1000,...i.now?{now:i.now}:{}}))}catch(a){throw FR(yc(a,"settle"))}finally{s.close()}}async function xDt(e){try{return(await Oo({dataset:e,open:!0,limit:1})).repulls[0]??null}catch(t){if(t instanceof L)throw yc(dj(t),"record");throw t}}async function cEe(e,t,n,r,o){if(!e.confirm)return;let s=Tr(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:kc(t).doi_count??1,copyItems:us(t).filter((a)=>a.purpose==="copy").length,status:n,until:r}))throw new N("declined","Not confirmed; nothing was written.")}async function fj(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 lEe(e,t){if(!e)return{};let n=e.now??Date.now;return{beforeStep(r){let o=r==="copy"?e_(t):0,s=Zw(e.tokenSince,n(),o);if(s)throw s},timed:(r,o)=>e.measured?.(r,Math.round(o/1000))}}function FR(e){if(e instanceof N)e.resumable=!0;return e}async function vDt(e,t,n){let{datasetId:r,digest:o}=BD(e.planPath),s=kn(t),i=vl(t),a=wDt(t),c=Hn(),l=wc(c,r,o),d=a_(c,"repull");ho(c_(l.lock),d);let f=Sl(l.lock);try{let p=await ai(t);if(!p.ok)e.out(`No GitHub token (${p.reason}); release-pr will be unchecked.`);let m=await ac(r);kl(m);let h=await xDt(r),g=h&&h.plan_digest!==o?EDt(h,e,r,gp(e.planPath,{environment:Dr(),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&&!dEe.includes(h.status)){let{body:_}=gp(e.planPath,{environment:Dr(),env:t,openNeuroGraphqlUrl:i});if(e.automatic)fEe(e.automatic,h),mR(_);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}:{},...lEe(e.automatic,_)};if(e.out(`Found re-pull #${h.id} of ${r}, ${h.status}.`),Ep(h.status,"pr_open"))ij(l,x.keepWorkdir,e.out);if(Ep(h.status,n)){if(!fs.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 R=await IR(e,t,x.token,o,h);return{row:R?.row??h,stoppedAt:h.status,...R?{settled:R}:{}}}await cEe(e,_,h.status,n);let k;try{k=await aj(x,h,n,uEe(e.out))}catch(R){throw FR(R)}let v=await IR(e,t,x.token,o,k);return{row:v?.row??k,stoppedAt:k.status,...v?{settled:v}:{}}}let y;try{if(e.automatic)y=kDt(e.planPath,e.automatic,t,i);else{Ds(l.plan),ho(l.plan,d);let _=new Map,x=await Exe(e.planPath,{catalog:m,github:{token:p.ok?p.token:null,apiBase:s},environment:Dr(),env:t,workRoot:l.plan,collect:{computed:_},openNeuroGraphqlUrl:i,...e.maxFetchBytes!==void 0?{maxFetchBytes:e.maxFetchBytes}:{},...g?{ownRelease:(k)=>SDt(g,k)}:{}});y={body:x.live.body,plannerDir:x.workdir,computed:_,rebasedOnto:x.rebasedOnto}}}catch(_){throw iEe(l.plan,e.out),aEe(l.root),aEe(c_(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??Sw,automatic:e.automatic,out:e.out};try{if(await cEe(e,b.body,h?.plan_digest===o?h.status:null,n,g??void 0),g)await $Dt(g,{datasetId:r,token:p.ok?p.token:null,apiBase:s,env:t,configDir:c,out:e.out});let _=await DDt(b,y.rebasedOnto,n);if(Ep(_.row.status,n)){let v=await IR(e,t,b.token,o,_.row);return v?{..._,row:v.row,settled:v}:_}let x;try{x=await aj({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}:{},...lEe(e.automatic,b.body)},_.row,n,uEe(e.out))}catch(v){throw FR(v)}let k=await IR(e,t,b.token,o,x);return{row:k?.row??x,stoppedAt:x.status,...k?{settled:k}:{}}}finally{if(!e.keepWorkdir)iEe(l.plan,e.out)}}finally{f()}}function kDt(e,t,n,r){let{body:o}=gp(e,{environment:Dr(),env:n,openNeuroGraphqlUrl:r});mR(o);let s=Zw(t.tokenSince,(t.now??Date.now)(),e_(o));if(s)throw s;let{workdir:i,computed:a}=eke(e,dc(o));return{body:o,plannerDir:i,computed:a,rebasedOnto:null}}function EDt(e,t,n,r){if(!t.supersede)throw yc(new N("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=Tr(r);if(e.origin!=="administrator")throw new N("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(kr(e.to_tag,o.toTag))throw new N("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(!kr(e.from_tag,o.fromTag))throw new N("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(!_g.includes(e.status))throw new N("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 N("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 SDt(e,t){let n=`release/v${e.to_version}`,r=YM.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=`${Hg}/${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 $Dt(e,t){let n=t.configDir??Hn(),r=t.out??(()=>{});if(!t.token)throw new N("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=wc(n,t.datasetId,e.plan_digest);ho(c_(s.lock),a_(n,"repull"));let i=Sl(s.lock),a=null;try{let c=await XM({datasetId:t.datasetId,token:o,base:t.apiBase,env:t.env,configDir:n,out:r,origin:async()=>(a??=await $l({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 DDt(e,t,n){let r=Tr(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=kc(e.body),i;try{i=await p0e({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 yc(dj(c),"record");throw c}let a=i.repull;if(e.automatic)fEe(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"||!dEe.includes(a.status))return{row:a,stoppedAt:a.status};try{ho(e.paths.root,c_(c_(e.paths.lock)));let c=a;a=await fj(e.automatic,"prepare",()=>c.status==="planned"?RDt(e,c,o):CDt(e,c,o))}catch(c){throw FR(yc(c,"prepare"))}return{row:a,stoppedAt:a.status}}function uEe(e){return{transition:(t,n,r)=>jR(t,n,r),async recordError(t,n){let r=t.status==="prepared"?pj(t):{};try{await Qn(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} (${Cn(o)??(o instanceof L?`HTTP ${o.statusCode}`:po(o))}); its record keeps the last error it had.`)}}}}async function RDt(e,t,n){let r;try{r=await uj(e,t,n)}catch(s){throw await NR(e,t,"planned",{},s),s}let o=await jR(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 pj(e){return{synth_tree:e.synth_tree,synth_sha:e.synth_sha,manifest_digest:e.manifest_digest}}async function cj(e){if(e.last_error===null||!e.last_error.startsWith(lj))return e;return jR(e,"prepared",pj(e))}async function CDt(e,t,n){let r=pj(t);if(n!==t.base_sha){let a;try{a=await uj(e,t,n)}catch(c){throw await NR(e,t,"prepared",r,c),c}return e.out(`Re-pull #${t.id} prepared again onto the live main.`),jR(t,"prepared",{synth_tree:a.synthTree,synth_sha:a.synthSha,manifest_digest:a.manifestDigest,base_sha:n,counts:a.counts})}let o=await ADt(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.`),!gDt(e.paths.bundle))await rM(e.paths.repo,e.paths.bundle,n);return cj(t)}e.out(`Re-pull #${t.id}'s working clone is not usable (${o}).`);let s=await zD({dir:e.paths.repo,bundle:e.paths.bundle,originUrl:pi(e.datasetId,e.env),baseSha:n,token:e.token,annexCommit:Tr(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.`),cj(t);e.out(`Re-pull #${t.id}'s checkpoint was not used (${s}); preparing again.`);let i;try{i=await uj(e,t,n)}catch(a){throw await NR(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 N("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 NR(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.`),cj(t)}async function ADt(e,t,n){let r,o;try{r=(await te(e,["rev-parse","--verify","--quiet","HEAD"],{ok:!0})).stdout,o=(await te(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 jR(e,t,n,r){try{return await Qn(e.id,{from:e.status,to:t,fields:n,...r?{error:r}:{}})}catch(o){if(o instanceof L)throw dj(o);throw o}}async function NR(e,t,n,r,o){try{await Qn(t.id,{from:n,to:n,fields:r,error:_Dt(o).slice(0,2000)})}catch(s){e.out(`The failure could not be recorded on re-pull #${t.id} (${Cn(s)??(s instanceof L?`HTTP ${s.statusCode}`:po(s))}); its record keeps the last error it had.`)}}async function uj(e,t,n){let{body:r,datasetId:o,paths:s}=e,i=Tr(r),a=await fj(e.automatic,"clone",()=>nM({dir:s.repo,originUrl:pi(o,e.env),baseSha:n,token:e.token,annexCommit:i.annexCommit})),c=hp(await mp(a),o),l=c.record?.bucket;if(!c.uuid||!l)throw new N("no-nemar-s3","NEMAR's remote.log names no single nemar-s3 bucket.");let d=`${o}/objects/`;if(QD(r).destinationPrefix!==d||c.prefix!==d)throw new N("destination-prefix",`The plan's destination is not ${d}, the only prefix a re-pull uploads to.`);let f=JM({bucket:l,datasetId:o,region:c.region,remoteUuid:c.uuid,workDir:s.upload}),p=xD({baseUrl:e.objectsBase}),m=await ar(a),h=await Qke(a,n,m),g=new Set(m.values()),y=a_(s.root,"scratch");Ds(y),ho(y,s.root);let b=await sve({work:a,body:r,upstreamBare:a_(e.plannerDir,"upstream.git"),upstreamEnv:Es(Vg(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 te(a,["ls-files","-z","--",Ss,ci]);for(let P of x.stdout.split("\x00"))if(P)_.add(P);let k=oj(t.created_at);await ive(a,n,_,k);let v=new Map;for(let[P,O]of await rj(a))if(_.has(P))v.set(P,O);let{scrub:R,uploaded:T}=await Xke({work:a,datasetId:o,scope:_,body:r,oursKeys:g,annexFromGit:b.annexFromGit,reader:p,upload:f,bucket:l,now:k,maxBytes:e.normalizeMaxBytes,upstreamBare:a_(e.plannerDir,"upstream.git")});Ds(y);let H=s_(r,g),A=await Zke({work:a,baseSha:n,createdAt:t.created_at,body:r,digest:e.digest,scrub:R,uploaded:T,held:H,base:h,expected:b.expected,preScrub:v,scope:_,counts:{written:b.written,deleted:b.deleted}});await rM(a,s.bundle,n);let F=(P)=>P.every((O)=>O.size!==null)?{known:!0,bytes:P.reduce((O,z)=>O+(z.size??0),0)}:{known:!1,bytes:0},M=F(A.manifest.items),U=F(A.manifest.local),B=R.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 l_=`--automatic-dispatch <id> is the central run-upstream-repull workflow's, never an
444
444
  administrator's: the run reads its dispatch from the event file GitHub delivered, reports to the
445
445
  Worker with the dispatch's token, and prints only fixed lines (repull-auto: ...) because its log
446
- is public. It refuses anything but the release the dispatch names, and needs GH_TOKEN.`;function hEe(e){let t=process.env.NEMAR_REPULL_POLL_MS;return t&&/^\d+$/.test(t)?Math.max(100,Number(t)):e}function NDt(e){if(e instanceof N){let t=e.step?{step:e.step}:{};return e.resumable?{phase:"failed",code:e.code,exit:3,...t}:{phase:"refused",code:e.code,exit:1,...t}}return{phase:"failed",code:"runner-failed",exit:1}}var FDt=new Set(["auto-token-on-argv","auto-token-hour","auto-token-clock","head-unreadable","head-foreign"]),gEe=(e)=>Math.max(0,Math.round((Date.now()-e)/1000));function yEe(){let e=pR(process.env,Date.now());if(e===null)throw new N("auto-token-clock","When the App token was minted is not known.");return e}function LR(e,t,n){if(e.time("run",gEe(n)),e.emit("quiet",e.quietFields()),t.phase==="refused"||t.phase==="failed")e.emit("result",{phase:t.phase,code:gR(t.code)}),process.exitCode=t.exit;else e.emit("result",{phase:t.phase}),process.exitCode=0;ce()}async function mj(e){try{await MDt(e)}finally{try{e.cleanup?.()}catch{}}}async function MDt(e){let t=Date.now(),n=fR();ce(),n.emit("start",{command:e.command,...R$.test(e.option)?{dispatch:e.option}:{}});let r=pR(process.env,t);if(r!==null)n.time("token_age",Math.max(0,Math.round(t/1000-r)));let o;try{o=Kve(e.option,process.env,n)}catch(i){LR(n,{phase:"failed",code:i instanceof N?i.code:"runner-failed",exit:1},t);return}if(!Jve(Dr())){LR(n,{phase:"failed",code:"auto-api-not-production",exit:1},t);return}let s;try{let i=TM(o.dispatch,process.argv);if(i)throw i;let a=Yve(o.dispatch,{mode:e.mode,datasetId:e.datasetOf(),argv:process.argv,env:process.env});if(a)throw a;if(!Qe())throw new N("runner-failed","The CLI is not signed in to NEMAR.");if(e.reportsStart){let c=await PM(o,"started");if(!c.stored&&c.code!=="already-started"){LR(n,{phase:"failed",code:c.code,exit:1},t);return}}s=await e.body(o)}catch(i){s=NDt(i)}if((s.phase==="refused"||s.phase==="failed")&&!FDt.has(s.code)&&await tke(o.dispatch.datasetId,process.env))s={phase:e.mode==="open"&&s.phase==="failed"&&s.exit===3?"refused":"failed",code:"token-expired",exit:s.exit};if(s.phase==="refused"||s.phase==="failed")s={...s,code:gR(s.code,s.step??e.step)};if(s.phase!=="planned"){let i=await PM(o,s.phase,s.phase==="opened"?{repullId:s.repullId}:s.phase==="refused"||s.phase==="failed"?{code:s.code}:{});if(!i.stored&&(s.phase==="opened"||s.phase==="finished"))s={phase:"failed",code:i.code,exit:1}}LR(n,s,t)}async function jDt(e){try{return await ac(e)}catch(t){if(t instanceof L)throw new N("record-refused","The NEMAR API did not answer for the dataset.");throw t}}function LDt(e){let n=(Array.isArray(e.body.refusals)?e.body.refusals:[]).find((s)=>typeof s?.code==="string");if(n)return n.code;let r=e.body.copy;if(Array.isArray(r?.unpinned)&&r.unpinned.length>0)return"key-without-pin";let o=e.preflight.find((s)=>s.status!=="ok");return o?.code??o?.name??"not-executable"}function hj(e){for(let[t,n]of e)if(n)throw oy(t,"not-taken")}function bEe(e,t,n){return mj({command:"plan",mode:"open",step:"plan",option:e,datasetOf:()=>t,reportsStart:!0,async body(r){if(hj([["--json",n.json===!0],["--counts",n.counts===!0],["--keep-workdir",n.keepWorkdir===!0],["--from-tag",n.fromTag!==void 0]]),!n.bucketListing)throw oy("--bucket-listing","required");if(!n.toTag)throw oy("--to-tag","required");if(!kr(n.toTag,r.dispatch.toTag))throw new N("dispatch-mismatch","--to-tag is not the dispatch's tag.");let o=yEe(),s=await jDt(t);kl(s);let i=n.out?IDt(n.out):pEe(Hn(),"repull",t);ODt(i,{recursive:!0,mode:448});let a=TDt(pEe(i,".planning-"));try{let c=new Map,l,d=Date.now();try{l=await Xg({datasetId:t,toTag:r.dispatch.toTag,maxFetchBytes:Math.floor(n.maxFetchGb*1073741824),keepWorkdir:!0,workRoot:a,collect:{computed:c},catalog:s,github:{token:process.env.GH_TOKEN?.trim()??null,apiBase:kn()},environment:Dr(),presence:"bucket-listing",openNeuroGraphqlUrl:vl(process.env)})}catch(b){if(b instanceof mo)return{phase:"failed",code:"not-planned",exit:1};throw b}finally{r.sink.time("plan",gEe(d))}if(!l.planned)return{phase:"refused",code:l.reason,exit:1};let f=l.file,p=Tr(f.body);if(p.ds!==r.dispatch.upstreamDs||!kr(p.fromTag,r.dispatch.fromTag))return{phase:"refused",code:"dispatch-mismatch",exit:1};let m=n.out??Rg(Hn(),t,p.toTag,f.digest);B$(m,f);let h=kc(f.body),g={executable:f.executable};for(let b of["delta_paths","copy_items","unexplained","conflicts","corrections"])if(h[b]!==void 0)g[b]=h[b];if(r.sink.emit("plan",g),!f.executable)return{phase:"refused",code:LDt(f),exit:3};try{Qve(f)}catch(b){if(b instanceof N)return{phase:"refused",code:b.code,exit:3};throw b}let y=Zw(o,Date.now(),e_(f.body));if(y)return{phase:"refused",code:y.code,exit:1};if(l.workdir===null)return{phase:"failed",code:"not-planned",exit:1};return Zve(m,l.workdir,c,f.digest),{phase:"planned"}}finally{mEe(a,{recursive:!0,force:!0,maxRetries:5,retryDelay:50})}}})}function wEe(e,t,n){return mj({command:"execute",mode:"open",step:"plan",option:e,datasetOf:()=>BD(t).datasetId,reportsStart:!1,cleanup:()=>mEe(hR(t),{recursive:!0,force:!0}),async body(r){if(hj([["--json",n.json===!0],["--keep-workdir",n.keepWorkdir===!0],["--until",n.until!=="pr_open"]]),!n.yes)throw oy("--yes","required");let o=Tr(q$(PDt(t,"utf8")).body);if(o.ds!==r.dispatch.upstreamDs||!kr(o.fromTag,r.dispatch.fromTag)||!kr(o.toTag,r.dispatch.toTag))throw new N("dispatch-mismatch","The plan is not for the dispatch's tags.");let s=await MR({planPath:t,until:"pr_open",keepWorkdir:!1,...n.normalizeMaxGb!==void 0?{normalizeMaxBytes:Math.floor(n.normalizeMaxGb*1073741824)}:{},maxFetchBytes:Math.floor(n.maxFetchGb*1073741824),automatic:{dispatchId:r.dispatch.dispatchId,token:r.dispatch.token,repullId:r.dispatch.repullId,settle:{maxWaitMs:(n.settleMinutes??oEe)*60000,quietMs:nEe,pollMs:hEe(rEe)},tokenSince:yEe(),measured:(a,c)=>r.sink.time(a,c)},out:(a)=>r.sink.drop(a)}),i=s.row;if(r.sink.emit("execute",{status:i.status,repull:i.id,pr:i.pr_number??0}),s.settled){let a=s.settled;if(r.sink.emit("settle",{reads:a.reads,moves:a.moves,unreadable:a.unreadable}),a.outcome==="foreign")return{phase:"failed",code:"head-foreign",exit:1};if(a.outcome==="unreadable")return{phase:"failed",code:"head-unreadable",exit:3}}return{phase:"opened",repullId:i.id}}})}function _Ee(e,t,n){return mj({command:"resume",mode:"finish",step:"finish",option:e,datasetOf:()=>t,reportsStart:!0,async body(r){if(hj([["--json",n.json===!0],["--acknowledge-identifier-screen",n.acknowledgeIdentifierScreen!==void 0]]),!n.yes)throw oy("--yes","required");let o=r.dispatch.repullId,s=await uR({datasetId:t,waitMinutes:n.waitMinutes,automaticFinish:{repullId:o},out:(i)=>r.sink.drop(i),pollMs:hEe(15000)});if(r.sink.emit("resume",{status:s.row?.status??"none",outcome:s.outcome}),s.outcome==="complete")return{phase:"finished"};if(s.outcome==="ended"||s.outcome==="nothing")return{phase:"refused",code:"finish-not-merged",exit:1};return{phase:"failed",code:"finish-incomplete",exit:3}}})}var Sp=3;function cy(e,t){if(/^[a-z]{2}\d{6}$/.test(e))return e;return dt(`"${e}" is not a dataset id (like on004362).`,{json:t,answered:!0}),Do(),null}function gj(e){let t=Number(e);if(!/^\d{1,3}$/.test(e.trim())||t>120)throw new Ns("a whole number of minutes from 0 to 120 is required.");return t}function xEe(e){let t=e.trim();if(t.length<Wo||t.length>Ko)throw new Ns(`a reason of ${Wo} to ${Ko} characters is required.`);return t}function yj(e,t,n){if(e instanceof N){dt(`Refused (${e.code}): ${e.message}`,{json:t,answered:!0});for(let r of e.lines)n(r);if(e.resumable)process.exitCode=Sp;return}dt(`Failed: ${G(e)}`,{json:t,answered:e instanceof L})}var vEe=new de("status").argument("<datasetId>").description("Show the record of a dataset's re-pulls: state, pull request, screen, what is next").option("--json","Print the records and the newest one's screens as JSON").action(async(e,t)=>{let n=t.json===!0;if(!pn(n))return;if(!cy(e,n))return;try{let{repulls:r}=await Oo({dataset:e,limit:5}),o=r[0],s=o?await xg(o.id):null;if(n){console.log(JSON.stringify({repulls:r,screens:s},null,2));return}if(!o){console.log(`${e} has no re-pull on record.`);return}for(let i of Uve(o,s?.exempt?null:s?.screens??[]))console.log(i);if(r.length>1){console.log("Earlier attempts:");for(let i of r.slice(1))console.log(zve(i))}}catch(r){dt(`Could not read the re-pulls of ${e}: ${G(r)}`,{json:n,answered:r instanceof L})}}),qDt=`
446
+ is public. It refuses anything but the release the dispatch names, and needs GH_TOKEN.`;function hEe(e){let t=process.env.NEMAR_REPULL_POLL_MS;return t&&/^\d+$/.test(t)?Math.max(100,Number(t)):e}function NDt(e){if(e instanceof N){let t=e.step?{step:e.step}:{};return e.resumable?{phase:"failed",code:e.code,exit:3,...t}:{phase:"refused",code:e.code,exit:1,...t}}return{phase:"failed",code:"runner-failed",exit:1}}var FDt=new Set(["auto-token-on-argv","auto-token-hour","auto-token-clock","head-unreadable","head-foreign"]),gEe=(e)=>Math.max(0,Math.round((Date.now()-e)/1000));function yEe(){let e=pR(process.env,Date.now());if(e===null)throw new N("auto-token-clock","When the App token was minted is not known.");return e}function LR(e,t,n){if(e.time("run",gEe(n)),e.emit("quiet",e.quietFields()),t.phase==="refused"||t.phase==="failed")e.emit("result",{phase:t.phase,code:gR(t.code)}),process.exitCode=t.exit;else e.emit("result",{phase:t.phase}),process.exitCode=0;ce()}async function mj(e){let t;try{t=await MDt(e)}finally{try{e.cleanup?.(t)}catch{}}}async function MDt(e){let t=Date.now(),n=fR();ce(),n.emit("start",{command:e.command,...R$.test(e.option)?{dispatch:e.option}:{}});let r=pR(process.env,t);if(r!==null)n.time("token_age",Math.max(0,Math.round(t/1000-r)));let o;try{o=Kve(e.option,process.env,n)}catch(a){LR(n,{phase:"failed",code:a instanceof N?a.code:"runner-failed",exit:1},t);return}if(!Jve(Dr())){LR(n,{phase:"failed",code:"auto-api-not-production",exit:1},t);return}let s;try{let a=TM(o.dispatch,process.argv);if(a)throw a;let c=Yve(o.dispatch,{mode:e.mode,datasetId:e.datasetOf(),argv:process.argv,env:process.env});if(c)throw c;if(!Qe())throw new N("runner-failed","The CLI is not signed in to NEMAR.");if(e.reportsStart){let l=await PM(o,"started");if(!l.stored&&l.code!=="already-started"){LR(n,{phase:"failed",code:l.code,exit:1},t);return}}s=await e.body(o)}catch(a){s=NDt(a)}let i=s.phase==="refused"||s.phase==="failed"?s.code:void 0;if((s.phase==="refused"||s.phase==="failed")&&!FDt.has(s.code)&&await tke(o.dispatch.datasetId,process.env))s={phase:e.mode==="open"&&s.phase==="failed"&&s.exit===3?"refused":"failed",code:"token-expired",exit:s.exit};if(s.phase==="refused"||s.phase==="failed")s={...s,code:gR(s.code,s.step??e.step)};if(s.phase!=="planned"){let a=await PM(o,s.phase,s.phase==="opened"?{repullId:s.repullId}:s.phase==="refused"||s.phase==="failed"?{code:s.code}:{});if(!a.stored&&(s.phase==="opened"||s.phase==="finished"))s={phase:"failed",code:a.code,exit:1}}return LR(n,s,t),i}async function jDt(e){try{return await ac(e)}catch(t){if(t instanceof L)throw new N("record-refused","The NEMAR API did not answer for the dataset.");throw t}}function LDt(e){let n=(Array.isArray(e.body.refusals)?e.body.refusals:[]).find((s)=>typeof s?.code==="string");if(n)return n.code;let r=e.body.copy;if(Array.isArray(r?.unpinned)&&r.unpinned.length>0)return"key-without-pin";let o=e.preflight.find((s)=>s.status!=="ok");return o?.code??o?.name??"not-executable"}function hj(e){for(let[t,n]of e)if(n)throw oy(t,"not-taken")}function bEe(e,t,n){return mj({command:"plan",mode:"open",step:"plan",option:e,datasetOf:()=>t,reportsStart:!0,async body(r){if(hj([["--json",n.json===!0],["--counts",n.counts===!0],["--keep-workdir",n.keepWorkdir===!0],["--from-tag",n.fromTag!==void 0]]),!n.bucketListing)throw oy("--bucket-listing","required");if(!n.toTag)throw oy("--to-tag","required");if(!kr(n.toTag,r.dispatch.toTag))throw new N("dispatch-mismatch","--to-tag is not the dispatch's tag.");let o=yEe(),s=await jDt(t);kl(s);let i=n.out?IDt(n.out):pEe(Hn(),"repull",t);ODt(i,{recursive:!0,mode:448});let a=TDt(pEe(i,".planning-"));try{let c=new Map,l,d=Date.now();try{l=await Xg({datasetId:t,toTag:r.dispatch.toTag,maxFetchBytes:Math.floor(n.maxFetchGb*1073741824),keepWorkdir:!0,workRoot:a,collect:{computed:c},catalog:s,github:{token:process.env.GH_TOKEN?.trim()??null,apiBase:kn()},environment:Dr(),presence:"bucket-listing",openNeuroGraphqlUrl:vl(process.env)})}catch(b){if(b instanceof mo)return{phase:"failed",code:"not-planned",exit:1};throw b}finally{r.sink.time("plan",gEe(d))}if(!l.planned)return{phase:"refused",code:l.reason,exit:1};let f=l.file,p=Tr(f.body);if(p.ds!==r.dispatch.upstreamDs||!kr(p.fromTag,r.dispatch.fromTag))return{phase:"refused",code:"dispatch-mismatch",exit:1};let m=n.out??Rg(Hn(),t,p.toTag,f.digest);B$(m,f);let h=kc(f.body),g={executable:f.executable};for(let b of["delta_paths","copy_items","unexplained","conflicts","corrections"])if(h[b]!==void 0)g[b]=h[b];if(r.sink.emit("plan",g),!f.executable)return{phase:"refused",code:LDt(f),exit:3};try{Qve(f)}catch(b){if(b instanceof N)return{phase:"refused",code:b.code,exit:3};throw b}let y=Zw(o,Date.now(),e_(f.body));if(y)return{phase:"refused",code:y.code,exit:1};if(l.workdir===null)return{phase:"failed",code:"not-planned",exit:1};return Zve(m,l.workdir,c,f.digest),{phase:"planned"}}finally{mEe(a,{recursive:!0,force:!0,maxRetries:5,retryDelay:50})}}})}function wEe(e,t,n){return mj({command:"execute",mode:"open",step:"plan",option:e,datasetOf:()=>BD(t).datasetId,reportsStart:!1,cleanup:(r)=>{if(r!=="execution-locked")mEe(hR(t),{recursive:!0,force:!0})},async body(r){if(hj([["--json",n.json===!0],["--keep-workdir",n.keepWorkdir===!0],["--until",n.until!=="pr_open"]]),!n.yes)throw oy("--yes","required");let o=Tr(q$(PDt(t,"utf8")).body);if(o.ds!==r.dispatch.upstreamDs||!kr(o.fromTag,r.dispatch.fromTag)||!kr(o.toTag,r.dispatch.toTag))throw new N("dispatch-mismatch","The plan is not for the dispatch's tags.");let s=await MR({planPath:t,until:"pr_open",keepWorkdir:!1,...n.normalizeMaxGb!==void 0?{normalizeMaxBytes:Math.floor(n.normalizeMaxGb*1073741824)}:{},maxFetchBytes:Math.floor(n.maxFetchGb*1073741824),automatic:{dispatchId:r.dispatch.dispatchId,token:r.dispatch.token,repullId:r.dispatch.repullId,settle:{maxWaitMs:(n.settleMinutes??oEe)*60000,quietMs:nEe,pollMs:hEe(rEe)},tokenSince:yEe(),measured:(a,c)=>r.sink.time(a,c)},out:(a)=>r.sink.drop(a)}),i=s.row;if(r.sink.emit("execute",{status:i.status,repull:i.id,pr:i.pr_number??0}),s.settled){let a=s.settled;if(r.sink.emit("settle",{reads:a.reads,moves:a.moves,unreadable:a.unreadable}),a.outcome==="foreign")return{phase:"failed",code:"head-foreign",exit:1};if(a.outcome==="unreadable")return{phase:"failed",code:"head-unreadable",exit:3}}return{phase:"opened",repullId:i.id}}})}function _Ee(e,t,n){return mj({command:"resume",mode:"finish",step:"finish",option:e,datasetOf:()=>t,reportsStart:!0,async body(r){if(hj([["--json",n.json===!0],["--acknowledge-identifier-screen",n.acknowledgeIdentifierScreen!==void 0]]),!n.yes)throw oy("--yes","required");let o=r.dispatch.repullId,s=await uR({datasetId:t,waitMinutes:n.waitMinutes,automaticFinish:{repullId:o},out:(i)=>r.sink.drop(i),pollMs:hEe(15000)});if(r.sink.emit("resume",{status:s.row?.status??"none",outcome:s.outcome}),s.outcome==="complete")return{phase:"finished"};if(s.outcome==="ended"||s.outcome==="nothing")return{phase:"refused",code:"finish-not-merged",exit:1};return{phase:"failed",code:"finish-incomplete",exit:3}}})}var Sp=3;function cy(e,t){if(/^[a-z]{2}\d{6}$/.test(e))return e;return dt(`"${e}" is not a dataset id (like on004362).`,{json:t,answered:!0}),Do(),null}function gj(e){let t=Number(e);if(!/^\d{1,3}$/.test(e.trim())||t>120)throw new Ns("a whole number of minutes from 0 to 120 is required.");return t}function xEe(e){let t=e.trim();if(t.length<Wo||t.length>Ko)throw new Ns(`a reason of ${Wo} to ${Ko} characters is required.`);return t}function yj(e,t,n){if(e instanceof N){dt(`Refused (${e.code}): ${e.message}`,{json:t,answered:!0});for(let r of e.lines)n(r);if(e.resumable)process.exitCode=Sp;return}dt(`Failed: ${G(e)}`,{json:t,answered:e instanceof L})}var vEe=new de("status").argument("<datasetId>").description("Show the record of a dataset's re-pulls: state, pull request, screen, what is next").option("--json","Print the records and the newest one's screens as JSON").action(async(e,t)=>{let n=t.json===!0;if(!pn(n))return;if(!cy(e,n))return;try{let{repulls:r}=await Oo({dataset:e,limit:5}),o=r[0],s=o?await xg(o.id):null;if(n){console.log(JSON.stringify({repulls:r,screens:s},null,2));return}if(!o){console.log(`${e} has no re-pull on record.`);return}for(let i of Uve(o,s?.exempt?null:s?.screens??[]))console.log(i);if(r.length>1){console.log("Earlier attempts:");for(let i of r.slice(1))console.log(zve(i))}}catch(r){dt(`Could not read the re-pulls of ${e}: ${G(r)}`,{json:n,answered:r instanceof L})}}),qDt=`
447
447
  Takes a dataset's open re-pull up where it stopped, past its open pull request, on this machine
448
448
  with your own GitHub token (GH_TOKEN, else \`gh auth token\`). It never merges.
449
449
 
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.24-PR1976.b970305",
4
+ "version": "0.10.24-PR1976.f7bc3db",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",