nemar-cli 0.10.37-PR2286.09be6aa → 0.10.37-PR2286.abb2a7d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,7 +23,7 @@ ${t}`,zM,GM,KM=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=VM.bind(null,n,
23
23
  `)}var Fl=!1;var{spawn:WF}=globalThis.Bun;function Vl(e,t=[]){let r=e.replace(YF,'("$1","<redacted>")');for(let n of t)if(n.length>=XF)r=r.split(n).join("<redacted>");return r}function QF(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],r=new Set;for(let n of[process.env,e??{}])for(let s of t){let o=n[s];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function hw(e,t){let r=e.getReader(),n=new TextDecoder,s="";while(!0){let{done:o,value:i}=await r.read();if(o)break;if(i.byteLength===0)continue;t(),s+=n.decode(i,{stream:!0})}return s+n.decode()}async function mw(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete r[y];let n=WF({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),s=!1,o,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??JF)};if(u(),t.timeout)o=setTimeout(()=>{s=!0,c(),n.kill()},t.timeout);let d=ic()?[...QF(r),...t.redact??[]]:[];if(ic()){let y=t.cwd?` (cwd=${t.cwd})`:"";qs(Nt.dim(Vl(`$ ${e.join(" ")}${y}`,d)))}let l=()=>{a=performance.now(),u()},p,f,h,m=n.exited.then((y)=>(c(),y));try{[p,f,h]=await Promise.all([hw(n.stdout,l),hw(n.stderr,l),m])}finally{if(c(),o)clearTimeout(o)}if(ic()){if(t.sensitiveOutput)qs(Nt.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())qs(Nt.dim(Vl(p.trimEnd(),d)));if(f.trim())qs(Nt.yellow(Vl(f.trimEnd(),d)))}qs(Nt.dim(`(exit ${h})`))}if(s)return{stdout:p,stderr:f||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:f,exitCode:h,timedOut:!1}}var YF,XF=8,JF=120000;var gw=F(()=>{Ul();YF=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function eV(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function _w(e,t=eV()){return e.installInstructions[t]}function tV(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function nV(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:rV}async function vw(e){try{let{exitCode:t,stdout:r,timedOut:n}=await mw(e.cmd,{timeout:nV()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:tV(r)}}catch(t){let r=t instanceof Error?t.message:String(t);if(!r.includes("ENOENT")&&!r.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${r}`);return{available:!1}}}async function zl(){let e=Object.entries(yw);return Promise.all(e.map(async([t,r])=>{let{available:n,version:s,timedOut:o}=await vw(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:s,timedOut:o,installInstruction:_w(r)}}))}async function Z3(){let t=(await zl()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
24
24
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let r of t)console.warn(` - ${r.name} (${r.purpose})`),console.warn(` Install: ${r.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function eB(e){let r=ZF[e].map((i)=>yw[i]).filter(Boolean),n=await Promise.all(r.map(async(i)=>{let a=await vw(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of n)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let s=n.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:_w(i.check)}));if(s.length===0)return;let o=[`
25
25
  Missing required tools:`];for(let i of s)o.push(` ${i.tool} not installed`),o.push(` Install: ${i.installInstruction}`);throw Error(o.join(`
26
- `))}var yw,ZF,rV=4000;var $w=F(()=>{gw();yw={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},ZF={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var bw;var Ew=F(()=>{bw={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.37-PR2286.09be6aa",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Ew();ac=bw.version});import{mkdirSync as oV,readdirSync as iV,unlinkSync as aV,writeFileSync as cV}from"fs";import{join as Kl}from"path";function dB(){Ds=!0}function lc(){return Ds}function fB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function pB(e){Tw=e,pr(`Step: ${e}`)}function hB(){xw=!0}function mB(){return xw}function gB(){if(Rw)return;Bl=!0}function yB(){Bl=!1,Rw=!0}function _B(){return Bl}function pr(e){if(Ds)process.stderr.write(`[debug] ${e}
26
+ `))}var yw,ZF,rV=4000;var $w=F(()=>{gw();yw={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},ZF={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var bw;var Ew=F(()=>{bw={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.37-PR2286.abb2a7d",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Ew();ac=bw.version});import{mkdirSync as oV,readdirSync as iV,unlinkSync as aV,writeFileSync as cV}from"fs";import{join as Kl}from"path";function dB(){Ds=!0}function lc(){return Ds}function fB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function pB(e){Tw=e,pr(`Step: ${e}`)}function hB(){xw=!0}function mB(){return xw}function gB(){if(Rw)return;Bl=!0}function yB(){Bl=!1,Rw=!0}function _B(){return Bl}function pr(e){if(Ds)process.stderr.write(`[debug] ${e}
27
27
  `)}function fV(e){let t={};for(let[r,n]of Object.entries(e))t[r]=dV.has(r.toLowerCase())?"[REDACTED]":n;return t}function Ow(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Hl(e,t,r=0){if(r>hV)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>Hl(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[s,o]of Object.entries(t))n[s]=Hl(s,o,r+1);return n}if(typeof t==="string"){if(pV.test(e))return"[REDACTED]";return t.replace(kw,Ow)}return t}function Wl(e){return e.replace(mV,"Bearer [REDACTED]").replace(gV,"[REDACTED_AWS_KEY]").replace(yV,"$1[REDACTED]").replace(_V,"$1$2=[REDACTED]").replace(kw,Ow)}function vV(e){return Wl(e)}function ww(e,t=lV){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(Hl("",n))}catch{}if(r=Wl(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function dc(e){if(!Ds)return;let t=vV(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?fV(e.requestHeaders):void 0,requestBody:ww(e.requestBody),responseBody:ww(e.responseBody)};uc.push(r),pr(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=dr(r);uc.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),pr(`redaction failed for ${e.method} ${t}: ${n}`)}}async function $V(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${ac}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${dr(t)})`)}e.push(""),e.push("Active account:");try{let t=hn();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${dr(t)})`)}e.push(""),e.push("External tools:");try{let t=await zl();for(let r of t){let n=r.available?r.version??"installed":r.timedOut?"(timed out)":"not installed";e.push(` ${r.name}: ${n}`)}}catch(t){e.push(` (could not probe external tools: ${dr(t)})`)}return e}async function EV(){return(await $V()).join(`
28
28
  `)}async function vB(){if(!Ds||cc!==void 0)return;try{cc=await EV()}catch(e){let t=dr(e);cc=`(could not build environment report: ${t})`,pr(`environment snapshot failed: ${t}`)}}function Aw(e){if(Sw.has(e))return{flag:e};for(let t of Sw){if(!e.startsWith(t)||e.length<=t.length)continue;if(t.length===2)return{flag:t,kind:"short-attached"};if(e[t.length]==="=")return{flag:t,kind:"long-eq"}}return null}function bV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Aw(n);if(!s){t.push(n);continue}if(s.kind==="long-eq")t.push(`${s.flag}=[REDACTED]`);else if(s.kind==="short-attached")t.push(`${s.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function wV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Aw(n);if(!s){t.push(n);continue}if(!s.kind&&r+1<e.length)r++}return t}function SV(e){let t=[];for(let n of wV(e)){if(n.startsWith("-"))continue;if(t.push(n),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function xV(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${Wl(bV(e).join(" "))}`),r.push(""),r.push(cc??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),uc.length===0)r.push(" (none)");else uc.forEach((n,s)=>{if(r.push(` [${s+1}] ${n.method} ${n.url} -> ${n.status??"ERROR"} (${n.durationMs}ms)`),n.error)r.push(` Error: ${n.error}`);if(n.note)r.push(` Note: ${n.note}`);if(n.requestHeaders)r.push(` Request headers: ${JSON.stringify(n.requestHeaders)}`);if(n.requestBody)r.push(` Request body: ${n.requestBody}`);if(n.responseBody)r.push(` Response body: ${n.responseBody}`)});return r.push(""),r.push(`Failing step: ${Tw??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
29
29
  `)}
package/dist/index.js CHANGED
@@ -100,7 +100,7 @@ ${t}`,IQe,NQe,FQe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=PQe.bind(nul
100
100
  `)}var RM=!1;var{spawn:jwt}=globalThis.Bun;function wp(e,t=[]){let n=e.replace(Lwt,'("$1","<redacted>")');for(let r of t)if(r.length>=qwt)n=n.split(r).join("<redacted>");return n}function n$(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 zge(e,t){let n=e.getReader(),r=new TextDecoder,o="";while(!0){let{done:s,value:i}=await n.read();if(s)break;if(i.byteLength===0)continue;t(),o+=r.decode(i,{stream:!0})}return o+r.decode()}async function O(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=jwt({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??Uwt)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=Gg()?[...n$(n),...t.redact??[]]:[];if(Gg()){let y=t.cwd?` (cwd=${t.cwd})`:"";Gd(u.dim(wp(`$ ${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([zge(r.stdout,f),zge(r.stderr,f),g])}finally{if(c(),s)clearTimeout(s)}if(Gg()){if(t.sensitiveOutput)Gd(u.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())Gd(u.dim(wp(p.trimEnd(),d)));if(m.trim())Gd(u.yellow(wp(m.trimEnd(),d)))}Gd(u.dim(`(exit ${h})`))}if(o)return{stdout:p,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:m,exitCode:h,timedOut:!1}}var Lwt,qwt=8,Uwt=120000;var Gt=G(()=>{We();Lwt=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function Hwt(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function Wge(e,t=Hwt()){return e.installInstructions[t]}function Gwt(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function Vwt(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:zwt}async function Kge(e){try{let{exitCode:t,stdout:n,timedOut:r}=await O(e.cmd,{timeout:Vwt()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:Gwt(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 Kw(){let e=Object.entries(Vge);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await Kge(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:Wge(n)}}))}async function Jge(){let t=(await Kw()).filter((n)=>n.required&&!n.available);if(t.length===0)return[];console.warn(`
101
101
  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 _p(e){let n=Bwt[e].map((i)=>Vge[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await Kge(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:Wge(i.check)}));if(o.length===0)return;let s=[`
102
102
  Missing required tools:`];for(let i of o)s.push(` ${i.tool} not installed`),s.push(` Install: ${i.installInstruction}`);throw Error(s.join(`
103
- `))}var Vge,Bwt,zwt=4000;var Jw=G(()=>{Gt();Vge={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)"}}},Bwt={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 Xge;var Yge=G(()=>{Xge={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.37-PR2286.09be6aa",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var zs;var xp=G(()=>{Yge();zs=Xge.version});import{mkdirSync as Kwt,readdirSync as Jwt,unlinkSync as Ywt,writeFileSync as Xwt}from"fs";import{join as $M}from"path";function rye(){zg=!0}function jl(){return zg}function oye(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Xw(e){nye=e,Nn(`Step: ${e}`)}function Yo(){eye=!0}function sye(){return eye}function ue(){if(tye)return;CM=!0}function Qw(){CM=!1,tye=!0}function iye(){return CM}function Nn(e){if(zg)process.stderr.write(`[debug] ${e}
103
+ `))}var Vge,Bwt,zwt=4000;var Jw=G(()=>{Gt();Vge={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)"}}},Bwt={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 Xge;var Yge=G(()=>{Xge={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.37-PR2286.abb2a7d",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var zs;var xp=G(()=>{Yge();zs=Xge.version});import{mkdirSync as Kwt,readdirSync as Jwt,unlinkSync as Ywt,writeFileSync as Xwt}from"fs";import{join as $M}from"path";function rye(){zg=!0}function jl(){return zg}function oye(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Xw(e){nye=e,Nn(`Step: ${e}`)}function Yo(){eye=!0}function sye(){return eye}function ue(){if(tye)return;CM=!0}function Qw(){CM=!1,tye=!0}function iye(){return CM}function Nn(e){if(zg)process.stderr.write(`[debug] ${e}
104
104
  `)}function t_t(e){let t={};for(let[n,r]of Object.entries(e))t[n]=e_t.has(n.toLowerCase())?"[REDACTED]":r;return t}function cye(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function DM(e,t,n=0){if(n>r_t)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>DM(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=DM(o,s,n+1);return r}if(typeof t==="string"){if(n_t.test(e))return"[REDACTED]";return t.replace(aye,cye)}return t}function AM(e){return e.replace(o_t,"Bearer [REDACTED]").replace(s_t,"[REDACTED_AWS_KEY]").replace(i_t,"$1[REDACTED]").replace(a_t,"$1$2=[REDACTED]").replace(aye,cye)}function c_t(e){return AM(e)}function Qge(e,t=Zwt){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(DM("",r))}catch{}if(n=AM(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function s$(e){if(!zg)return;let t=c_t(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?t_t(e.requestHeaders):void 0,requestBody:Qge(e.requestBody),responseBody:Qge(e.responseBody)};o$.push(n),Nn(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=W(n);o$.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),Nn(`redaction failed for ${e.method} ${t}: ${r}`)}}async function l_t(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${zs}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${W(t)})`)}e.push(""),e.push("Active account:");try{let t=Yt();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${W(t)})`)}e.push(""),e.push("External tools:");try{let t=await Kw();for(let n of t){let r=n.available?n.version??"installed":n.timedOut?"(timed out)":"not installed";e.push(` ${n.name}: ${r}`)}}catch(t){e.push(` (could not probe external tools: ${W(t)})`)}return e}async function OM(){return(await l_t()).join(`
105
105
  `)}async function lye(){if(!zg||r$!==void 0)return;try{r$=await OM()}catch(e){let t=W(e);r$=`(could not build environment report: ${t})`,Nn(`environment snapshot failed: ${t}`)}}function uye(e){if(Zge.has(e))return{flag:e};for(let t of Zge){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 u_t(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=uye(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 d_t(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=uye(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function f_t(e){let t=[];for(let r of d_t(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 p_t(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${AM(u_t(e).join(" "))}`),n.push(""),n.push(r$??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),o$.length===0)n.push(" (none)");else o$.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: ${nye??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
106
106
  `)}
@@ -2267,7 +2267,7 @@ Examples:
2267
2267
  Read-only: nothing was copied. Add --apply to recover.`));else if(d.recoveredKeys>0)console.log(u.dim("\nThe location log still says nothing about these objects: run `nemar admin fleet key-registration <id> --apply` to record them."));if(d.tally.failed>0)process.exitCode=1});Fe.addCommand(Af);var BTe=new ie("reindex").description("Refresh dataset metadata: enrichment + first-class D1 columns");BTe.argument("[dataset-id]","Dataset ID to reindex (e.g., nm000103)").option("--all","Reindex every dataset with a GitHub repo").option("--missing-metadata","Reindex only datasets with NULL metadata columns").option("--stale","Reindex only datasets whose metadata is older than --older-than days").option("--older-than <days>","Threshold in days. Default 30 for --stale, 1 (24h) for --missing-metadata recency guard.").option("--skip-enrichment","Skip the LLM enrichment step").option("--skip-sync","Skip the D1 metadata-column refresh step").option("--ref <ref>","Ref to enrich from (single-dataset only; default: main)").option("--dry-run","List matched datasets without firing the reindex (bulk only)").option("--json","Print the raw JSON response instead of the summary").action(async(e,t)=>{if(!ke())return;let n=[t.all,t.missingMetadata,t.stale].filter(Boolean).length;if(e&&n>0)console.error(u.red("Provide either a dataset-id OR a bulk flag (--all/--missing-metadata/--stale), not both")),process.exit(1);if(!e&&n===0)console.error(u.red("Provide a dataset-id or one of: --all, --missing-metadata, --stale")),process.exit(1);if(n>1)console.error(u.red("Use only one of --all, --missing-metadata, --stale")),process.exit(1);if(t.skipEnrichment&&t.skipSync)console.error(u.red("--skip-enrichment and --skip-sync cannot both be set")),process.exit(1);if(e){let f=C(`Reindexing ${e}...`).start();try{let p={skip_enrichment:t.skipEnrichment===!0,skip_sync:t.skipSync===!0,...t.ref&&{ref:t.ref}},m=await ty(e,p),h=m.enrichment.status!=="failed"&&m.sync.status!=="failed";if(t.json){if(f.stop(),console.log(JSON.stringify(m,null,2)),!h)process.exit(1);return}if(h)f.succeed(`${e} reindexed`);else f.warn(`${e} reindexed with errors`);if(console.log(),ETe(m,{showRef:!0}),!h)process.exit(1)}catch(p){f.fail(`Failed to reindex ${e}`),console.error(u.red(W(p))),process.exit(1)}return}let r=t.all?"all":t.missingMetadata?"missing-metadata":"stale",o={skip_enrichment:t.skipEnrichment===!0,skip_sync:t.skipSync===!0,dry_run:t.dryRun===!0};if(t.olderThan!==void 0){let f=Number.parseInt(t.olderThan,10);if(!Number.isFinite(f)||f<0)console.error(u.red(`Invalid --older-than: "${t.olderThan}"`)),process.exit(1);o.older_than_days=f}else if(r==="missing-metadata")o.older_than_days=1;else if(r==="stale")o.older_than_days=30;let s=t.dryRun?`Listing ${r} datasets...`:`Reindexing ${r} datasets...`,i=C(s).start(),a;try{a=await lbe(r,o)}catch(f){i.fail("Bulk reindex failed"),console.error(u.red(W(f))),process.exit(1)}if(t.json){if(i.stop(),console.log(JSON.stringify(a,null,2)),(a.results??[]).some((p)=>p.enrichment.status==="failed"||p.sync.status==="failed"))process.exit(1);return}if(a.dry_run){if(i.succeed(`${a.total} datasets match filter=${r} (dry run, no changes)`),a.datasets)for(let f of a.datasets)console.log(u.dim(` - ${f}`));return}let c=a.results??[],l=c.filter((f)=>f.enrichment.status!=="failed"&&f.sync.status!=="failed").length,d=c.length-l;if(d===0)i.succeed(`${c.length}/${c.length} datasets reindexed in ${(a.elapsed_ms/1000).toFixed(1)}s`);else i.warn(`${l}/${c.length} ok; ${d} failed in ${(a.elapsed_ms/1000).toFixed(1)}s`);console.log();for(let f of c)ETe(f);if(d>0)process.exit(1)});Fe.addCommand(BTe);var GLt=new ie("availability-report").description("Report how much of a dataset's declared data is present in S3, and exactly which files are missing + why (#1000). Dry-run by default. --all backfills every non-sandbox dataset that has a version and no report yet (#1001).").argument("[dataset-id]","Dataset ID (e.g., nm000103)").option("--write","Commit the report to .nemar/availability-report.json on main (default: preview only)").option("--all","Backfill every non-sandbox dataset that has a version and no report yet, instead of a single one (#1001)").option("--missing-only","With --all, sweep only datasets already known incomplete (data_complete=0)").option("--limit <n>","With --all, datasets per batch (server clamps to [1,30])","10").option("--reset","With --all, clear every stamped sweep row so it re-sweeps from scratch").option("--verbose","With --all, print per-batch progress").option("--json","Output raw JSON").action(async(e,t)=>{if(!ke())return;if(!e&&!t.all)console.error(u.red("Provide a dataset-id or --all")),process.exit(1);if(e&&(t.all||t.reset||t.missingOnly))console.error(u.red("--all/--reset/--missing-only cannot be combined with a dataset id")),process.exit(1);if(e){let l=C(t.write?`Generating and writing availability report for ${e}...`:`Previewing availability report for ${e}...`).start(),d;try{d=await bbe(e,{write:t.write===!0})}catch(g){l.fail(`Failed to generate availability report for ${e}`),console.error(u.red(W(g))),process.exit(1)}let f="report"in d?d.report:d,p="report"in d;if(l.succeed(p?`${e}: availability report written to .nemar/availability-report.json`:`${e}: availability report (dry run, not written)`),t.json){console.log(JSON.stringify(d,null,2));return}if(console.log(),f.version===null)console.log(u.yellow(" No published version manifest to compare against; completeness unknown."));else console.log(` Version: ${f.version}`);console.log(` Complete: ${f.complete?u.green("yes"):u.red("no")}`),console.log(` Files: ${f.completeness.files_present}/${f.completeness.files_declared} present`);let m=`${Wt(f.completeness.bytes_present)}/${Wt(f.completeness.bytes_declared)}`,h=f.completeness.pct_bytes!=null?` (${(f.completeness.pct_bytes*100).toFixed(1)}%)`:"";if(console.log(` Bytes: ${m}${h}`),f.blocklist_reason)console.log(u.yellow(` Blocklisted: ${f.blocklist_reason}`));if(f.missing.length>0){console.log(),console.log(u.dim(` Missing (${f.missing.length}):`));for(let g of f.missing)console.log(u.dim(` - ${g.path} [${g.reason}]`))}return}if(t.reset){let l=C("Resetting availability-report sweep state...").start();try{let d=await _be();if(l.succeed(`Cleared ${d.reset} stamped row(s); eligible datasets are candidates again`),t.json)console.log(JSON.stringify(d,null,2))}catch(d){l.fail("Reset failed"),console.error(u.red(W(d))),process.exit(1)}return}let n=Number.parseInt(t.limit??"10",10)||10,r=t.missingOnly===!0,o={processed:0,written:0,errors:0},s=C("Sweeping datasets for availability reports...").start(),i=0,a=null,c=null;try{let l;do{if(l=await wbe({limit:n,missingOnly:r}),i++,o.processed+=l.processed,o.written+=l.written,o.errors+=l.errors.length,a=l.remaining,t.verbose){s.stop(),console.log(` [batch ${i}] processed=${l.processed} written=${l.written} errors=${l.errors.length} remaining=${a??"?"}`);for(let d of l.errors)console.log(` ${u.red(d.dataset_id)}: ${d.error}`);s.start("Sweeping datasets for availability reports...")}else s.text=`Sweeping datasets for availability reports... ${o.processed} processed, ${a??"?"} remaining`;if(a!=null&&c!=null&&a>=c){s.warn(`No progress (remaining stuck at ${a}); stopping - see errors`);break}if(c=a,(a??0)>0)await kb(1000)}while((a??0)>0);s.stop()}catch(l){s.fail("Availability-report sweep failed"),console.error(u.red(W(l))),process.exit(1)}if(t.json)console.log(JSON.stringify({...o,batches:i,remaining:a},null,2));else{if(console.log(),a===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(u.cyan(`Done in ${i} batch(es): processed=${o.processed} written=${o.written} errors=${o.errors} remaining=${a??"unknown"}`))}if(o.errors>0||a===null)process.exit(1)});Fe.addCommand(GLt);async function WU(e,t,n,r){let o=0,s=null,i=null;try{let a;do{if(a=await n(),o++,s=a.remaining,r(a,o,s),s!=null&&i!=null&&s>=i){e.warn(`No progress (remaining stuck at ${s}); stopping - see errors`);break}if(i=s,(s??0)>0)await kb(1000)}while((s??0)>0);e.stop()}catch(a){e.fail(t),console.error(u.red(W(a))),process.exit(1)}return{batches:o,remaining:s}}var HTe=new ie("hed-sweep").description("Backfill HED detection (has_hed / hed_version) for existing datasets (#869)");HTe.option("--limit <n>","Datasets per batch (server clamps to [1,30])","15").option("--reset","Clear every probed HED row so a corrected detector can re-sweep").option("--verbose","Print per-batch progress").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let i=C("Resetting HED sweep state...").start();try{let a=await dbe();if(i.succeed(`Cleared ${a.reset} probed HED row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(a,null,2))}catch(a){i.fail("Reset failed"),console.error(u.red(W(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,n={processed:0,withHed:0,withoutHed:0,unknown:0,errors:0},r=C("Sweeping datasets for HED...").start(),{batches:o,remaining:s}=await WU(r,"HED sweep failed",()=>ube({limit:t}),(i,a,c)=>{if(n.processed+=i.processed,n.withHed+=i.withHed,n.withoutHed+=i.withoutHed,n.unknown+=i.unknown,n.errors+=i.errors.length,e.verbose){r.stop(),console.log(` [batch ${a}] processed=${i.processed} hed=${i.withHed} no-hed=${i.withoutHed} unknown=${i.unknown} errors=${i.errors.length} remaining=${c??"?"}`);for(let l of i.errors)console.log(` ${u.red(l.dataset_id)}: ${l.error}`);r.start("Sweeping datasets for HED...")}else r.text=`Sweeping datasets for HED... ${n.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...n,batches:o,remaining:s},null,2));else{if(console.log(),s===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(u.cyan(`Done in ${o} batch(es): processed=${n.processed} hed=${n.withHed} no-hed=${n.withoutHed} unknown=${n.unknown} errors=${n.errors} remaining=${s??"unknown"}`))}if(n.errors>0||s===null)process.exit(1)});Fe.addCommand(HTe);var GTe=new ie("recording-stats-sweep").description("Backfill dataset-level recording duration/count/channel-range stats from each dataset's zarr index (migration 0070, #1146)");GTe.option("--limit <n>","Datasets per batch (server clamps to [1,200])","50").option("--reset","Clear every stamped recording-stats row so it re-sweeps from scratch").option("--verbose","Print per-batch progress").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let i=C("Resetting recording-stats sweep state...").start();try{let a=await pbe();if(i.succeed(`Cleared ${a.reset} stamped recording-stats row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(a,null,2))}catch(a){i.fail("Reset failed"),console.error(u.red(W(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"50",10)||50,n={processed:0,measured:0,unmeasured:0,errors:0},r=C("Sweeping datasets for recording stats...").start(),{batches:o,remaining:s}=await WU(r,"Recording-stats sweep failed",()=>fbe({limit:t}),(i,a,c)=>{if(n.processed+=i.processed,n.measured+=i.measured,n.unmeasured+=i.unmeasured,n.errors+=i.errors.length,e.verbose){r.stop(),console.log(` [batch ${a}] processed=${i.processed} measured=${i.measured} unmeasured=${i.unmeasured} errors=${i.errors.length} remaining=${c??"?"}`);for(let l of i.errors)console.log(` ${u.red(l.dataset_id)}: ${l.error}`);r.start("Sweeping datasets for recording stats...")}else r.text=`Sweeping datasets for recording stats... ${n.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...n,batches:o,remaining:s},null,2));else{if(console.log(),s===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(u.cyan(`Done in ${o} batch(es): processed=${n.processed} measured=${n.measured} unmeasured=${n.unmeasured} errors=${n.errors} remaining=${s??"unknown"}`))}if(n.errors>0||s===null)process.exit(1)});Fe.addCommand(GTe);var zTe=new ie("signal-defaults-sweep").description("Backfill BIDS signal defaults (sampling frequency, power line frequency, EEG reference, placement scheme) from each dataset's exemplar sidecar (migrations 0072/0073, #1153)");zTe.option("--limit <n>","Datasets per batch (server clamps to [1,30])","15").option("--reset","Clear every stamped signal-defaults row so it re-sweeps from scratch").option("--verbose","Print per-batch progress").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let i=C("Resetting signal-defaults sweep state...").start();try{let a=await hbe();if(i.succeed(`Cleared ${a.reset} stamped signal-defaults row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(a,null,2))}catch(a){i.fail("Reset failed"),console.error(u.red(W(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,n={processed:0,populated:0,noData:0,errors:0},r=C("Sweeping datasets for signal defaults...").start(),{batches:o,remaining:s}=await WU(r,"Signal-defaults sweep failed",()=>mbe({limit:t}),(i,a,c)=>{if(n.processed+=i.processed,n.populated+=i.populated,n.noData+=i.noData,n.errors+=i.errors.length,e.verbose){r.stop(),console.log(` [batch ${a}] processed=${i.processed} populated=${i.populated} no-data=${i.noData} errors=${i.errors.length} remaining=${c??"?"}`);for(let l of i.errors)console.log(` ${u.red(l.dataset_id)}: ${l.error}`);r.start("Sweeping datasets for signal defaults...")}else r.text=`Sweeping datasets for signal defaults... ${n.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...n,batches:o,remaining:s},null,2));else{if(console.log(),s===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(u.cyan(`Done in ${o} batch(es): processed=${n.processed} populated=${n.populated} no-data=${n.noData} errors=${n.errors} remaining=${s??"unknown"}`))}if(n.errors>0||s===null)process.exit(1)});Fe.addCommand(zTe);async function zLt(e,t,n){let r=e(),o={processed:0,complete:0,incomplete:0,unknown:0,errors:0},s=0,i=null,a=null,c=!1;do{let l=await t(r);if(s++,o.processed+=l.processed,o.complete+=l.complete,o.incomplete+=l.incomplete,o.unknown+=l.unknown,o.errors+=l.errors.length,i=l.remaining,n?.onBatch?.(l,o,s),i!=null&&a!=null&&i>=a){c=!0;break}if(a=i,(i??0)>0)await n?.sleepBetweenBatches?.()}while((i??0)>0);return{batches:s,totals:o,remaining:i,stalled:c}}var VTe=new ie("data-integrity-sweep").description("Audit datasets against their version manifest and backfill data_complete / bytes_present (epic #967 Phase 3, #970)");VTe.option("--limit <n>","Datasets per batch (server clamps to [1,30])","15").option("--older-than <days>","Also re-audit rows checked more than N days ago (periodic re-audit, not just the one-shot drain)").option("--reaudit","Re-verify every already-checked row using an anchored cutoff so the sweep fully converges to 0 (unlike --older-than's moving now()-relative window, which never reaches 0 on its own)").option("--reset","Clear every audited row so a corrected verifier can re-sweep").option("--verbose","Print per-batch progress").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let c=C("Resetting data-integrity sweep state...").start();try{let l=await ybe();if(c.succeed(`Cleared ${l.reset} audited row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(l,null,2))}catch(l){c.fail("Reset failed"),console.error(u.red(W(l))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,n=e.olderThan?Number.parseInt(e.olderThan,10):void 0,r=C("Sweeping datasets for data integrity...").start(),o;try{if(o=await zLt(()=>e.reaudit?new Date().toISOString():void 0,async(c)=>{let l=await gbe({limit:t,olderThan:n,before:c});return{processed:l.processed,complete:l.complete,incomplete:l.incomplete,unknown:l.unknown,errors:l.errors,remaining:l.remaining}},{onBatch:(c,l,d)=>{if(e.verbose){r.stop(),console.log(` [batch ${d}] processed=${c.processed} complete=${c.complete} incomplete=${c.incomplete} unknown=${c.unknown} errors=${c.errors.length} remaining=${c.remaining??"?"}`);for(let f of c.errors)console.log(` ${u.red(f.dataset_id)}: ${f.error}`);r.start("Sweeping datasets for data integrity...")}else r.text=`Sweeping datasets for data integrity... ${l.processed} processed, ${c.remaining??"?"} remaining`},sleepBetweenBatches:()=>kb(1000)}),o.stalled)r.warn(`No progress (remaining stuck at ${o.remaining}); stopping - see errors`);else r.stop()}catch(c){r.fail("Data-integrity sweep failed"),console.error(u.red(W(c))),process.exit(1)}let{batches:s,totals:i,remaining:a}=o;if(e.json)console.log(JSON.stringify({...i,batches:s,remaining:a},null,2));else{if(console.log(),a===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));if(console.log(u.cyan(`Done in ${s} batch(es): processed=${i.processed} complete=${i.complete} incomplete=${i.incomplete} unknown=${i.unknown} errors=${i.errors} remaining=${a??"unknown"}`)),i.incomplete>0)console.log(u.yellow(`${i.incomplete} dataset(s) verified incomplete -- see 'nemar dataset list --json' (data_complete=0) for details.`))}if(i.errors>0||a===null)process.exit(1)});Fe.addCommand(VTe);var WTe=new ie("zarr-fidelity-sweep").description("Re-verify published Zarr stores against their dataset's own BIDS metadata (#1068)");WTe.option("--limit <n>","Datasets per batch (server clamps to [1,25])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=C("Verifying Zarr store fidelity...").start(),r;try{r=await Nbe({limit:t}),n.stop()}catch(o){n.fail("Zarr fidelity sweep failed"),console.error(u.red(W(o))),process.exit(1);return}if(e.json)console.log(JSON.stringify(r,null,2));else{console.log(),console.log(u.cyan(`processed=${r.processed} verified=${r.verified} failed=${r.failed} unverifiable=${r.unverifiable} errors=${r.errors.length} remaining=${r.remaining??"unknown"}${r.budget_exhausted?" budget_exhausted=true":""}`));for(let o of r.results){let s=o.verdict==="verified"?u.green:o.verdict==="failed"?u.red:u.yellow;console.log(` ${s(o.verdict.padEnd(12))} ${o.dataset_id} (sampled=${o.sampled} checked=${o.checked})`);for(let i of o.examples)console.log(` ${u.red(i.code)}: ${i.path}`);if(o.examples_truncated)console.log(` ${u.dim(`(${o.mismatch_count} mismatches total; showing first ${o.examples.length})`)}`)}for(let o of r.errors)console.log(` ${u.red("error")} ${o.dataset_id}: ${o.error}`)}if(r.errors.length>0||r.remaining===null||r.budget_exhausted)process.exit(1)});Fe.addCommand(WTe);var VLt=250,KTe=new ie("upstream-backfill").description("Record which upstream snapshot each mirrored version came from (dry run unless --execute)");KTe.option("--execute","Write the results; without it nothing is recorded").option("--limit <n>","Version rows per batch (server clamps to [1,50])","25").option("--after <cursor>","Resume after this key, e.g. on000123@1.0.0 (skips a stuck row)").option("--max-batches <n>","Stop after this many batches","200").option("--json","Output one JSON summary instead of progress lines").action(async(e)=>{if(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=Number.parseInt(e.maxBatches??"200",10)||200,r=e.execute===!0,o=(m)=>{if(!e.json)console.log(m)};if(!r)o(u.yellow("Dry run: nothing is written. Pass --execute to record."));o(u.dim("A recorded 'unknown' is final: it is never examined again. A read that fails or whose 404 a control read does not confirm is not recorded."));let s={batches:0,scanned:0,recorded:{doi:0,unknown:0},not_examined:0,unparseable:0,absent:0,skipped_existing:0},i=[],a=e.after,c=null,l=null,d=!1;for(let m=0;m<n;m++){let h;try{h=await Fbe({execute:r,limit:t,after:a})}catch(g){l=W(g);break}c=h,s.batches++,s.scanned+=h.scanned,s.recorded.doi+=h.recorded.doi,s.recorded.unknown+=h.recorded.unknown,s.not_examined+=h.not_examined,s.unparseable+=h.unparseable,s.absent+=h.absent,s.skipped_existing+=h.skipped_existing,i.push(...h.errors),o(`${u.cyan(`batch ${s.batches}`)} scanned=${h.scanned} ${r?"recorded":"would record"} doi=${h.recorded.doi} unknown=${h.recorded.unknown} not_examined=${h.not_examined} remaining=${h.remaining}`);for(let g of h.unknown_samples)o(` ${u.dim("unknown")} ${g.dataset_id}@${g.version}: ${g.reason}`);for(let g of h.errors)o(` ${u.red("error")} ${g.dataset_id}@${g.version}${g.kind==="needs_admin"?" [needs admin]":""}: ${g.error}`);if(!h.ok){d=h.suspect_credential,l=h.error??"the batch failed",a=h.next_cursor??a;break}if(a=h.next_cursor??void 0,!h.next_cursor)break;await new Promise((g)=>setTimeout(g,VLt))}let f=l===null&&c!==null&&c.next_cursor===null,p=f?null:a??null;if(e.json)console.log(JSON.stringify({execute:r,done:f,failure:l,suspect_credential:d,...s,errors:i,next_cursor:p,counts:c?.counts??null},null,2));else{if(l)console.error(u.red(`Stopped: ${l}`));if(!f&&!l)console.log(u.yellow(`Stopped at --max-batches ${n}; the pass is not done.`));if(p)console.log(`Resume with: --after ${p}`);if(f&&s.not_examined>0){let m=i.filter((g)=>g.kind==="needs_admin"),h=s.not_examined-m.length;if(h>0)console.log(u.yellow(`${h} row(s) were not examined after a transient error: rerun without --after to try them again.`));if(m.length>0)console.log(u.yellow(`${m.length} row(s) have no description at the tag or at main (or the default branch is not main): a rerun will not fix them and they need an admin look. They are the 'error' lines above (${m.slice(0,3).map((g)=>`${g.dataset_id}@${g.version}`).join(", ")}${m.length>3?", ...":""}).`))}if(c)console.log(u.cyan(`On versions now: doi=${c.counts.doi} lineage=${c.counts.lineage} unknown=${c.counts.unknown} not_examined=${c.counts.not_examined}`));if(!r)console.log(u.yellow("Dry run, pass --execute to record."))}if(l!==null||i.length>0||!f)process.exit(1)});Fe.addCommand(KTe);Fe.addCommand(tTe);var JTe=new ie("anonymity-sweep").description("Re-check anonymous deposits against the identity-leak inventory (#1409)");JTe.option("--limit <n>","Datasets per batch (server clamps to [1,25])","10").option("--reset","Re-arm every anonymous deposit, then exit").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let o=C("Re-arming anonymous deposits...").start();try{let s=await Vbe();o.succeed(`Re-armed ${s.reset} anonymous deposit(s).`)}catch(s){o.fail("Reset failed"),console.error(u.red(W(s))),process.exit(1)}return}let t=Number.parseInt(e.limit??"10",10)||10,n=C("Checking anonymous deposits...").start(),r;try{r=await zbe({limit:t}),n.stop()}catch(o){n.fail("Anonymity sweep failed"),console.error(u.red(W(o))),process.exit(1);return}if(e.json)console.log(JSON.stringify(r,null,2));else{console.log(),console.log(u.cyan(`processed=${r.processed} verified=${r.verified} findings=${r.with_findings} unverifiable=${r.unverifiable} errors=${r.errors.length} mail_failures=${r.mail_failures.length} remaining=${r.remaining??"unknown"}${r.budget_exhausted?" budget_exhausted=true":""}`));for(let o of r.results){let s=o.status==="verified"?u.green:o.status==="findings"?u.red:u.yellow;console.log(` ${s(o.status.padEnd(13))} ${o.dataset_id} (files ${o.files_scanned}/${o.files_listed})`);for(let i of o.findings){let a=i.severity==="invariant"?u.red("NEMAR"):u.yellow("deposit");console.log(` ${a} ${i.check}: ${i.detail}`)}if(o.unchecked.length>0)console.log(` ${u.dim(`not checked: ${o.unchecked.join(", ")}`)}`)}for(let o of r.errors)console.log(` ${u.red("error")} ${o.dataset_id}: ${o.error}`);for(let o of r.mail_failures)console.log(` ${u.red("not mailed")} ${o.dataset_id} -> ${o.recipient}: ${o.error}`)}if(r.errors.length>0||r.mail_failures.length>0||r.remaining===null||r.budget_exhausted)process.exit(1)});Fe.addCommand(JTe);var $1=new ie("doctor").description("Diagnose and heal stuck-dataset patterns (e.g. missing S3 version manifests)");function WLt(e){let t=0;for(let[n,r]of Object.entries(e.results)){t+=r.count;let o=r.count>0?u.red(`${r.count} finding(s)`):u.green("clean");console.log(`${u.bold(n)}: ${o} \u2014 ${r.description}`);for(let s of r.findings)console.log(` ${s.dataset_id}${s.version?`@v${s.version}`:""}`)}return t}$1.command("scan").description("Run diagnostic checks (read-only)").argument("[dataset-id]","Narrow the scan to one dataset").option("--check <name>","Run a single check (default: all checks)").option("--json","Output raw JSON instead of the human summary").action(async(e,t)=>{if(!ke())return;let n=C("Running doctor checks (read-only; a full-catalog scan can take ~1 minute)...").start();try{let r=await e6({check:t.check,datasetId:e});if(n.stop(),t.json){console.log(JSON.stringify(r,null,2));return}let o=WLt(r);if(o>0)console.log(u.yellow(`
2268
2268
  ${o} finding(s). Preview the remediation with: nemar admin doctor fix <check> --dry-run`))}catch(r){n.fail("Doctor scan failed"),console.error(u.red(W(r))),process.exit(1)}});$1.command("fix").description("Apply a check's remediation (writes; use --dry-run first)").argument("<check>","Check name (see: nemar admin doctor scan)").argument("[dataset-id]","Narrow to one dataset").option("--dry-run","List what would be fixed without writing").option("--json","Output raw JSON instead of the human summary").action(async(e,t,n)=>{if(!ke())return;if(n.dryRun){let c=C(`Listing ${e} findings (dry run)...`).start();try{let l=await t6({check:e,datasetId:t,dryRun:!0});if(c.stop(),n.json){console.log(JSON.stringify(l,null,2));return}console.log(`Would fix ${l.would_fix} finding(s) for ${u.bold(e)}:`);for(let d of l.findings)console.log(` ${d.dataset_id}${d.version?`@v${d.version}`:""}`)}catch(l){c.fail("Dry run failed"),console.error(u.red(W(l))),process.exit(1)}return}let r=C(`Scanning for ${e} findings...`).start(),o;try{o=(await e6({check:e,datasetId:t})).results[e]?.findings??[]}catch(c){r.fail("Doctor scan failed"),console.error(u.red(W(c))),process.exit(1);return}if(o.length===0){if(r.succeed(`${e}: nothing to fix`),n.json)console.log(JSON.stringify({check:e,total:0,results:[]},null,2));return}r.stop(),console.log(`${u.bold(e)}: ${o.length} finding(s) to fix`);let s=[...new Set(o.map((c)=>c.dataset_id))];r.start();let{totals:i,results:a}=await KLt(s,(c,l)=>{let d=o.filter((f)=>f.dataset_id===c&&f.version).map((f)=>`v${f.version}`).join(", ");return r.text=`Fixing ${c}${d?` (${d})`:""} [${l+1}/${s.length}]...`,t6({check:e,datasetId:c})},{onDataset:(c,l)=>{if(r.stop(),l.length===0)console.log(` resolved ${c}: healed between the scan and its fix turn`);for(let d of l){let f=`${d.dataset_id}${d.version?`@v${d.version}`:""}`;if(d.status==="fixed")console.log(` ${u.green("fixed")} ${f}`);else if(d.status==="skipped")console.log(` skipped ${f}: ${d.message??"already healthy"}`);else console.log(` ${u.red("FAILED")} ${f}: ${d.message??"unknown error"}`)}r.start()}});if(r.stop(),n.json)console.log(JSON.stringify({check:e,total:o.length,...i,results:a},null,2));else{let c=i.resolved>0?`, ${i.resolved} already resolved`:"";console.log(`
2269
2269
  ${u.bold(e)}: ${u.green(`${i.fixed} fixed`)}, ${i.skipped} skipped, ${i.failed>0?u.red(`${i.failed} failed`):"0 failed"}${c}`)}if(i.failed>0)process.exit(1)});async function KLt(e,t,n){let r={fixed:0,skipped:0,failed:0,resolved:0},o=[];for(let[s,i]of e.entries()){let a;try{let c=await t(i,s);if(a=c.results,a.length===0)r.resolved++;else r.fixed+=c.fixed,r.skipped+=c.skipped,r.failed+=c.failed}catch(c){r.failed++,a=[{dataset_id:i,status:"failed",message:W(c)}]}o.push(...a),n?.onDataset?.(i,a)}return{totals:r,results:o}}$1.command("kinds").description("Check that operational accounts carry their expected account kind (read-only)").action(async()=>{if(!ke())return;let e=Object.entries(nne),t=C(`Checking ${e.length} operational account kind(s)...`).start(),n=[],r=[];try{for(let[o,s]of e)try{let{user:i}=await m$(o);if(i.account_kind!==s)n.push(`${o}: expected '${s}', found '${i.account_kind??"unknown"}'`)}catch(i){if(i instanceof U&&i.statusCode===404)r.push(o);else throw i}if(t.stop(),n.length===0&&r.length===0){console.log(u.green(`All ${e.length} operational account(s) carry their expected kind.`));return}for(let o of n)console.log(` ${u.yellow("kind mismatch")} ${o}`);for(let o of r)console.log(` ${u.yellow("account absent")} ${o}`);console.log(u.yellow(`
2270
- ${n.length+r.length} finding(s). Fix a mismatch with \`nemar admin kind <username> <kind>\`.`))}catch(o){t.fail("Doctor kinds check failed"),console.error(u.red(W(o))),process.exit(1)}});Fe.addCommand($1);var KU=new ie("email-preferences").description("Manage email notification preferences"),YTe=[{key:"user_approval",label:"User approval notifications"},{key:"publication_request",label:"Publication request notifications"},{key:"dataset_anonymity",label:"Anonymity sweep findings"},{key:"identifier_sweep",label:"Identifier sweep weekly report"},{key:"support_tickets",label:"Support tickets assigned to you"}];KU.command("show").description("Show email notification preferences").option("--user <username>","(owner or admin) show another user's preferences; an admin sees the community categories only").action(async(e)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let t=C("Fetching email preferences...").start();try{let n=await Rbe(e.user),r=n.username?`${n.username}'s`:"Your";t.succeed(`${r} email notification preferences:`),console.log();let o=(s)=>s?u.green("enabled"):u.dim("disabled");for(let s of YTe){let i=n[s.key];if(i===void 0)continue;console.log(` ${s.label.padEnd(40)} ${o(i)}`)}for(let s of Q0)console.log(` ${ew(s).padEnd(40)} ${o(n[s])}`);console.log(` ${ew("recall").padEnd(40)} ${u.green("always on")}`),console.log(u.dim(` ${Gne()}`)),console.log(),console.log(u.dim(" Use 'nemar admin email-preferences update' to change settings."))}catch(n){t.fail("Failed to fetch preferences"),console.error(u.red(W(n)))}});KU.command("update").description("Update email notification preferences").option("--user-approval <bool>","Enable/disable user approval notifications").option("--publication-request <bool>","Enable/disable publication request notifications").option("--news <bool>","Enable/disable news emails").option("--rfcs <bool>","Enable/disable requests-for-comments emails").option("--maintenance <bool>","Enable/disable maintenance emails").addOption(new Fs("--announcements <bool>","Retired: use --news, --rfcs and --maintenance").hideHelp()).option("--dataset-anonymity <bool>","Enable/disable anonymity sweep findings").option("--identifier-sweep <bool>","Enable/disable the identifier sweep weekly report").option("--support-tickets <bool>","Enable/disable support ticket notifications").option("--all <bool>","Enable/disable all notifications (recalls are always on)").option("--user <username>","(owner or admin) update another user's preferences; an admin may change news, rfcs and maintenance only").action(async(e)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.announcements!==void 0)console.error(u.red("--announcements was split into three categories. Use --news, --rfcs and --maintenance instead.")),process.exit(1);function t(o){if(o===void 0)return;let s=o.toLowerCase();if(s==="true"||s==="1"||s==="on"||s==="yes")return!0;if(s==="false"||s==="0"||s==="off"||s==="no")return!1;console.error(u.red(`Invalid boolean value: "${o}". Use true/false, on/off, yes/no.`)),process.exit(1)}let n={};if(e.all!==void 0){let o=t(e.all);n.user_approval=o,n.publication_request=o,n.dataset_anonymity=o,n.identifier_sweep=o,n.support_tickets=o;for(let s of Q0)n[s]=o}else{let o={user_approval:t(e.userApproval),publication_request:t(e.publicationRequest),news:t(e.news),rfcs:t(e.rfcs),maintenance:t(e.maintenance),dataset_anonymity:t(e.datasetAnonymity),identifier_sweep:t(e.identifierSweep),support_tickets:t(e.supportTickets)};if(Object.values(o).every((s)=>s===void 0))console.error(u.red("No preferences specified.")),console.log(" --user-approval <bool> User approval notifications"),console.log(" --publication-request <bool> Publication request notifications"),console.log(" --news <bool> News emails"),console.log(" --rfcs <bool> Requests-for-comments emails"),console.log(" --maintenance <bool> Maintenance emails"),console.log(" --dataset-anonymity <bool> Anonymity sweep findings"),console.log(" --identifier-sweep <bool> Identifier sweep weekly report"),console.log(" --support-tickets <bool> Support ticket notifications"),console.log(" --all <bool> All notifications"),process.exit(1);for(let[s,i]of Object.entries(o))if(i!==void 0)n[s]=i}let r=C("Updating email preferences...").start();try{let o=await $be(n,e.user),s=o.username?`${o.username}'s`:"Your";r.succeed(`${s} email preferences updated:`),console.log();let i=(c)=>c?u.green("enabled"):u.dim("disabled"),a={user_approval:"User approval: ",publication_request:"Publication request: ",dataset_anonymity:"Anonymity findings: ",identifier_sweep:"Identifier sweep: ",support_tickets:"Support tickets: "};for(let c of YTe){let l=o[c.key];if(l===void 0)continue;console.log(` ${a[c.key]} ${i(l)}`)}for(let c of Q0)console.log(` ${`${ew(c)}:`.padEnd(22)} ${i(o[c])}`);console.log(` ${`${ew("recall")}:`.padEnd(22)} ${u.green("always on")}`)}catch(o){r.fail("Failed to update preferences"),console.error(u.red(W(o)))}});Fe.addCommand(KU);var D1=new ie("notice").description("Manage system notices displayed to CLI users");D1.command("list").description("List all notices (including expired)").action(async()=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let e=C("Fetching notices...").start();try{let{notices:t}=await A0e();if(t.length===0){e.succeed("No notices found.");return}e.succeed(`${t.length} notice(s):`),console.log();for(let n of t){let o={critical:u.red.bold,warning:u.yellow,maintenance:u.magenta,announcement:u.green,tip:u.blue,info:u.blue}[n.level]||u.white,s=n.expires_at&&new Date(n.expires_at)<new Date?u.dim(" (expired)"):"";if(console.log(` ${u.dim(`#${n.id}`)} ${o(`[${n.level.toUpperCase()}]`)} ${u.dim(`scope:${n.scope}`)}${s}`),console.log(` ${n.message}`),console.log(` ${u.dim(`Created: ${n.created_at}`)}`),n.expires_at)console.log(` ${u.dim(`Expires: ${n.expires_at}`)}`);console.log()}}catch(t){qt(t,e,"Failed to fetch notices")}});D1.command("set").description("Create a new system notice").requiredOption("-m, --message <text>","Notice message text").option("-l, --level <level>","Notice level: tip, announcement, maintenance, warning, critical","tip").option("-s, --scope <scope>","Target scope: all, admins, members","all").option("-e, --expires <datetime>","Expiry datetime (ISO 8601)").action(async(e)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(![...l6,"info"].includes(e.level))console.error(u.red(`Invalid level: ${e.level}. Use ${l6.join(", ")}.`)),process.exit(1);if(!["all","admins","members"].includes(e.scope))console.error(u.red(`Invalid scope: ${e.scope}. Use all, admins, or members.`)),process.exit(1);let t=C("Creating notice...").start();try{let n=await O0e({message:e.message,level:e.level,scope:e.scope,expires_at:e.expires});if(t.succeed(`Notice created (ID: ${n.id})`),console.log(` Level: ${n.level}`),console.log(` Scope: ${n.scope}`),console.log(` Message: ${n.message}`),n.expires_at)console.log(` Expires: ${n.expires_at}`)}catch(n){qt(n,t,"Failed to create notice")}});D1.command("clear <id>").description("Delete a notice by ID").option(Ze,ct).option(Rt,kt).action(async(e,t)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let n=Number.parseInt(e,10);if(Number.isNaN(n))console.error(u.red("Invalid notice ID")),process.exit(1);if(await $e(`Delete notice #${n}?`,t,!1)!=="confirmed")return;let o=C("Deleting notice...").start();try{await T0e(n),o.succeed(`Notice #${n} deleted`)}catch(s){qt(s,o,"Failed to delete notice")}});Fe.addCommand(D1);function JLt(e){let t=[`${u.bold(`Announcement ${e.id}`)} ${u.cyan(e.status)}`,` Subject: ${e.subject}`,` To: ${e.recipient_group}`];if(e.category)t.push(` Category: ${e.category}`);if(e.recall_reference)t.push(` Recall reference: ${e.recall_reference}`);if(t.push(` Sent at: ${e.sent_at}`),e.status==="sent")t.push(` Delivered: ${e.queued_count>0?e.delivered_count:"n/a (sent inline)"}`),t.push(` Failed: ${e.failure_count}`);else{t.push(` Queued: ${e.queued_count}`),t.push(` Delivered: ${e.delivered_count}`),t.push(` Failed: ${e.failure_count}`),t.push(` Unconfirmed: ${e.unknown_count} (not retried; the provider never confirmed them)`);let n=e.skipped_count??0;if(n>0)t.push(` Skipped: ${n} (opted out or account changed after the send was queued)`);let r=e.queued_count-e.delivered_count-e.failure_count-e.unknown_count-n;if(r>0)t.push(` Pending: ${r}`)}if(e.failed_recipients.length>0){t.push(" Failed addresses are shown redacted and may not be unique:");for(let n of e.failed_recipients)t.push(u.red(` Failed: ${n}`))}return t}function YLt(e){let t=[];if(e.counts)t.push(` Audience by group: ${Object.entries(e.counts).map(([n,r])=>`${n} ${r}`).join(", ")}`);if(e.deliverable_count!==void 0&&e.deliverable_count!==e.recipient_count)t.push(u.yellow(` ${e.deliverable_count} of ${e.recipient_count} would be delivered; the rest are withheld by the non-production delivery fence`));if(e.would_refuse==="duplicate_send")t.push(u.yellow(` A real send would be refused as a repeat of announcement ${e.duplicate_of} (use --allow-repeat to send anyway)`));for(let n of e.blockers??[])t.push(u.red(` A real send would be refused now: ${n}`));if(e.recipients){t.push("");for(let n of e.recipients)t.push(` ${n}`)}else if(e.sample&&e.sample.length>0)t.push(` Sample (redacted): ${e.sample.join(", ")}`),t.push(" Addresses are listed in production only.");return t}async function XLt(e,t){if(t!==void 0)return t.trim()===e?e:void 0;if(!process.stdin.isTTY)return;try{let{typed:n}=await Ne.prompt([{type:"input",name:"typed",message:`A recall reaches every account and cannot be undone. Type the reference (${e}) to send it:`}]);return typeof n==="string"&&n.trim()===e?e:void 0}catch{return}}function QLt(e){if(e.notice_id!==void 0)return[u.green(` Site notice #${e.notice_id} published. Clear it when the recall is resolved: nemar admin notice clear ${e.notice_id}`)];if(e.notice_skipped==="nothing_queued")return[u.yellow(" No site notice was published because nothing was queued. Run the recall again; it publishes the notice once it goes out.")];return[u.yellow.bold(" OWNER STEP: a recall also needs a public site notice, and none was published."),u.yellow(' Publish one now: nemar admin notice set --level critical --message "NEMAR recall: <subject> (reference: <reference>). Check your email for what to do."')]}Fe.command("notify").description("Send a categorized email to a group, or an email to a single user").option("--to <group>","Recipient group: all, admins, members").option("--category <category>",`Category of a group send (required with --to): ${Z0.join(", ")}. Recipients who turned it off are skipped; a recall (owner only) ignores that`).option("--recall-ref <reference>","What a recall is about: a dataset id with optional version (nm000104@v1.2.0) or a nemarOrg issue, pull request or security advisory URL").option("--confirm-recall <reference>","Type the recall reference again to confirm sending a recall (--yes does not replace it)").option("--allow-repeat","Send even if the same category and subject went out in the last 24 hours").option("--user <username>","Send to a single user by username (direct contact, no category)").option("--subject <text>","Email subject line").option("--body <text>","Email body (markdown)").option("--body-file <path>","Read email body from file (markdown)").option("--dry-run","Preview recipients without sending").option("--status <id>","Show the progress of a queued announcement by its ID").option("--json","Output raw JSON (with --status)").option(Ze,ct).option(Rt,kt).action(async(e)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.status!==void 0){let f=Number(e.status);if(!Number.isInteger(f)||f<1)console.error(u.red(`Invalid announcement ID: ${e.status}`)),process.exit(1);let p=e.json?null:C("Fetching announcement status...").start();try{let m=await Dbe(f);if(e.json){console.log(JSON.stringify(m,null,2));return}p?.stop();for(let h of JLt(m))console.log(h)}catch(m){qt(m,p??C(),"Failed to fetch announcement status")}return}if(!e.subject)console.error(u.red("Email subject required. Use --subject.")),process.exit(1);let t=e.subject;if(e.to&&e.user)console.error(u.red("--to and --user are mutually exclusive. Provide exactly one.")),process.exit(1);if(!e.to&&!e.user)console.error(u.red("Provide either --to <group> or --user <username>.")),process.exit(1);if(e.to&&!["all","admins","members"].includes(e.to))console.error(u.red(`Invalid group: ${e.to}. Use all, admins, or members.`)),process.exit(1);if(e.user){if(e.category||e.recallRef||e.confirmRecall||e.allowRepeat)console.error(u.red("--user is direct contact and takes no --category, --recall-ref, --confirm-recall or --allow-repeat.")),process.exit(1)}else if(!e.category)console.error(u.red(`A group send needs --category <${Z0.join("|")}>. Use --user for direct contact.`)),process.exit(1);else if(!Hne(e.category))console.error(u.red(`Invalid category: ${e.category}. Use ${Z0.join(", ")}.`)),process.exit(1);let n=e.category===Bne;if(!n&&(e.recallRef||e.confirmRecall))console.error(u.red("--recall-ref and --confirm-recall belong to --category recall only.")),process.exit(1);let r=e.recallRef?.trim();if(n){if(!r||!Vne(r))console.error(u.red(`--recall-ref is required. ${Wne}`)),process.exit(1)}let o;if(e.bodyFile){if(!E1(e.bodyFile))console.error(u.red(`File not found: ${e.bodyFile}`)),process.exit(1);o=OLt(e.bodyFile,"utf-8")}else if(e.body)o=e.body;else console.error(u.red("Email body required. Use --body or --body-file.")),process.exit(1);if(n){let f=zne(o);if(f.length>0)console.error(u.red(`A recall body needs the headings ${FI.map((p)=>`"${p}"`).join(" and ")} (markdown, for example "## What is affected"). Missing: ${f.join(", ")}.`)),process.exit(1)}let s=e.user?`user:${e.user}`:`${e.to} (${e.category})`,i=e.user?{user:e.user,subject:t,body:o}:{to:e.to,category:e.category,...n?{recall_reference:r}:{},...e.allowRepeat?{allow_repeat:!0}:{},subject:t,body:o};if(e.dryRun){let f=C("Checking recipients...").start();try{let p=await ZM({...i,dry_run:!0});if("dry_run"in p){f.succeed(`Dry run: ${p.recipient_count} recipient(s) for "${p.recipient_group}"${p.category?` (${p.category})`:""}`);for(let m of YLt(p))console.log(m)}}catch(p){qt(p,f,"Failed to check recipients")}return}if(console.log(u.bold("Email preview:")),console.log(` To: ${u.cyan(s)}`),n)console.log(u.red.bold(" RECALL: reaches every account, ignores email preferences, cannot be unsubscribed from.")),console.log(` Reference: ${r}`);console.log(` Subject: ${t}`),console.log(` Body: ${o.length>100?`${o.substring(0,100)}...`:o}`),console.log();let a=e.user?`Send this email to ${e.user}?`:"Send this broadcast email?";if(await $e(a,e,!1)!=="confirmed")return;let l;if(n){if(l=await XLt(r,e.confirmRecall),l===void 0)console.error(u.red(`Recall not sent: the confirmation must be the reference exactly as given (${r}).`)),process.exit(1)}let d=C(e.user?`Sending to ${e.user}...`:"Sending broadcast...").start();try{let f=await ZM({...i,...l===void 0?{}:{confirm_recall:l}});if("broadcast_id"in f){if(f.error==="queue_enqueue_failed")d.warn(`Enqueue failed (ID ${f.broadcast_id}): ${f.recipient_count} queued, ${f.failure_count} not queued; check progress with: nemar admin notify --status ${f.broadcast_id}`);else if(f.status==="queued"&&f.failure_count===0)d.succeed(`Queued ${f.recipient_count} announcement(s) (ID ${f.broadcast_id}); check progress with: nemar admin notify --status ${f.broadcast_id}`);else if(f.failure_count>0){d.warn(`Email send: ${f.recipient_count} delivered, ${f.failure_count} failed`);for(let p of f.failed_recipients)console.log(u.red(` Failed: ${p}`))}else{let p=e.user?`Email sent to ${e.user}`:`Broadcast sent to ${f.recipient_count} recipient(s)`;d.succeed(`${p} (ID: ${f.broadcast_id})`)}if((f.suppressed_count??0)>0)console.log(u.yellow(` ${f.suppressed_count} recipient(s) withheld by the non-production delivery fence`));if(n)for(let p of QLt(f))console.log(p)}}catch(f){qt(f,d,"Failed to send email")}});var ZLt=1500;function e4t(e){switch(e.kind){case"ok":return u.green(`ok ${e.schema_version}`);case"stale":return u.yellow(`stale ${e.schema_version}`);case"missing":return u.red("missing");case"error":return u.red(`error ${e.status||"?"}: ${e.message}`)}}function t4t(e){return e.kind==="stale"||e.kind==="missing"}function n4t(e){let n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`)}var XTe=new ie("summary").description("summary.json coverage across published dataset versions");XTe.command("check").description("Report which (dataset_id, version) pairs have stale or missing summary.json").option("--fix","Dispatch generate-manifest for every stale/missing version").option("--id <id>","Limit to a single dataset_id (exact match)").option("--match <glob>","Limit to dataset_ids matching a glob pattern: `*` matches any run of chars, `?` matches one char. Examples: `on*`, `nm00010?`, `*99999`. Can be combined with --id (id wins if both passed).").option("--only-stale","Print only rows that are not ok (suppresses ok rows)").option("--json","Emit the full report as JSON instead of a table").option(Ze,ct).option(Rt,kt).action(async(e)=>{if(!ke())return;let t=C("Building coverage report...").start(),n;try{n=await Cbe()}catch(p){qt(p,t,"Failed to fetch coverage report");return}t.succeed(`Coverage: target=schema ${n.target_schema}, versions=${n.totals.versions}`);let r=n.versions,o=null;if(e.id){if(r=r.filter((p)=>p.dataset_id===e.id),o=`dataset_id=${e.id}`,r.length===0){console.log(u.yellow(`No rows for ${o}`));return}}else if(e.match){let p=n4t(e.match);if(r=r.filter((m)=>p.test(m.dataset_id)),o=`--match ${e.match}`,r.length===0){console.log(u.yellow(`No rows match ${o}`));return}console.log(u.dim(`Scoped to ${r.length} version(s) matching ${e.match}`))}if(e.json){console.log(JSON.stringify(o?{...n,versions:r,totals:RTe(r)}:n,null,2));return}let s=e.onlyStale?r.filter((p)=>p.state.kind!=="ok"):r;if(s.length===0)console.log(u.green("All versions at target schema \u2014 no drift."));else{let p=Math.max(...s.map((h)=>h.dataset_id.length),10),m=Math.max(...s.map((h)=>h.version.length),7);for(let h of s)console.log(` ${h.dataset_id.padEnd(p)} ${h.version.padEnd(m)} ${e4t(h.state)}`)}let i=o?RTe(r):n.totals;if(console.log(),console.log(` Total: ${i.versions} ${u.green(`ok=${i.ok}`)} ${u.yellow(`stale=${i.stale}`)} ${u.red(`missing=${i.missing}`)} ${u.red(`error=${i.error}`)}`),!e.fix){if(i.stale+i.missing>0)console.log(u.dim(`
2270
+ ${n.length+r.length} finding(s). Fix a mismatch with \`nemar admin kind <username> <kind>\`.`))}catch(o){t.fail("Doctor kinds check failed"),console.error(u.red(W(o))),process.exit(1)}});Fe.addCommand($1);var KU=new ie("email-preferences").description("Manage email notification preferences"),YTe=[{key:"user_approval",label:"User approval notifications"},{key:"publication_request",label:"Publication request notifications"},{key:"dataset_anonymity",label:"Anonymity sweep findings"},{key:"identifier_sweep",label:"Identifier sweep weekly report"},{key:"support_tickets",label:"Support tickets assigned to you"}];KU.command("show").description("Show email notification preferences").option("--user <username>","(owner or admin) show another user's preferences; an admin sees the community categories only").action(async(e)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let t=C("Fetching email preferences...").start();try{let n=await Rbe(e.user),r=n.username?`${n.username}'s`:"Your";t.succeed(`${r} email notification preferences:`),console.log();let o=(s)=>s?u.green("enabled"):u.dim("disabled");for(let s of YTe){let i=n[s.key];if(i===void 0)continue;console.log(` ${s.label.padEnd(40)} ${o(i)}`)}for(let s of Q0)console.log(` ${ew(s).padEnd(40)} ${o(n[s])}`);console.log(` ${ew("recall").padEnd(40)} ${u.green("always on")}`),console.log(u.dim(` ${Gne()}`)),console.log(),console.log(u.dim(" Use 'nemar admin email-preferences update' to change settings."))}catch(n){t.fail("Failed to fetch preferences"),console.error(u.red(W(n)))}});KU.command("update").description("Update email notification preferences").option("--user-approval <bool>","Enable/disable user approval notifications").option("--publication-request <bool>","Enable/disable publication request notifications").option("--news <bool>","Enable/disable news emails").option("--rfcs <bool>","Enable/disable requests-for-comments emails").option("--maintenance <bool>","Enable/disable maintenance emails").addOption(new Fs("--announcements <bool>","Retired: use --news, --rfcs and --maintenance").hideHelp()).option("--dataset-anonymity <bool>","Enable/disable anonymity sweep findings").option("--identifier-sweep <bool>","Enable/disable the identifier sweep weekly report").option("--support-tickets <bool>","Enable/disable support ticket notifications").option("--all <bool>","Enable/disable all notifications (recalls are always on)").option("--user <username>","(owner or admin) update another user's preferences; an admin may change news, rfcs and maintenance only").action(async(e)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.announcements!==void 0)console.error(u.red("--announcements was split into three categories. Use --news, --rfcs and --maintenance instead.")),process.exit(1);function t(o){if(o===void 0)return;let s=o.toLowerCase();if(s==="true"||s==="1"||s==="on"||s==="yes")return!0;if(s==="false"||s==="0"||s==="off"||s==="no")return!1;console.error(u.red(`Invalid boolean value: "${o}". Use true/false, on/off, yes/no.`)),process.exit(1)}let n={};if(e.all!==void 0){let o=t(e.all);n.user_approval=o,n.publication_request=o,n.dataset_anonymity=o,n.identifier_sweep=o,n.support_tickets=o;for(let s of Q0)n[s]=o}else{let o={user_approval:t(e.userApproval),publication_request:t(e.publicationRequest),news:t(e.news),rfcs:t(e.rfcs),maintenance:t(e.maintenance),dataset_anonymity:t(e.datasetAnonymity),identifier_sweep:t(e.identifierSweep),support_tickets:t(e.supportTickets)};if(Object.values(o).every((s)=>s===void 0))console.error(u.red("No preferences specified.")),console.log(" --user-approval <bool> User approval notifications"),console.log(" --publication-request <bool> Publication request notifications"),console.log(" --news <bool> News emails"),console.log(" --rfcs <bool> Requests-for-comments emails"),console.log(" --maintenance <bool> Maintenance emails"),console.log(" --dataset-anonymity <bool> Anonymity sweep findings"),console.log(" --identifier-sweep <bool> Identifier sweep weekly report"),console.log(" --support-tickets <bool> Support ticket notifications"),console.log(" --all <bool> All notifications"),process.exit(1);for(let[s,i]of Object.entries(o))if(i!==void 0)n[s]=i}let r=C("Updating email preferences...").start();try{let o=await $be(n,e.user),s=o.username?`${o.username}'s`:"Your";r.succeed(`${s} email preferences updated:`),console.log();let i=(c)=>c?u.green("enabled"):u.dim("disabled"),a={user_approval:"User approval: ",publication_request:"Publication request: ",dataset_anonymity:"Anonymity findings: ",identifier_sweep:"Identifier sweep: ",support_tickets:"Support tickets: "};for(let c of YTe){let l=o[c.key];if(l===void 0)continue;console.log(` ${a[c.key]} ${i(l)}`)}for(let c of Q0)console.log(` ${`${ew(c)}:`.padEnd(22)} ${i(o[c])}`);console.log(` ${`${ew("recall")}:`.padEnd(22)} ${u.green("always on")}`)}catch(o){r.fail("Failed to update preferences"),console.error(u.red(W(o)))}});Fe.addCommand(KU);var D1=new ie("notice").description("Manage system notices displayed to CLI users");D1.command("list").description("List all notices (including expired)").action(async()=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let e=C("Fetching notices...").start();try{let{notices:t}=await A0e();if(t.length===0){e.succeed("No notices found.");return}e.succeed(`${t.length} notice(s):`),console.log();for(let n of t){let o={critical:u.red.bold,warning:u.yellow,maintenance:u.magenta,announcement:u.green,tip:u.blue,info:u.blue}[n.level]||u.white,s=n.expires_at&&new Date(n.expires_at)<new Date?u.dim(" (expired)"):"";if(console.log(` ${u.dim(`#${n.id}`)} ${o(`[${n.level.toUpperCase()}]`)} ${u.dim(`scope:${n.scope}`)}${s}`),console.log(` ${n.message}`),console.log(` ${u.dim(`Created: ${n.created_at}`)}`),n.expires_at)console.log(` ${u.dim(`Expires: ${n.expires_at}`)}`);console.log()}}catch(t){qt(t,e,"Failed to fetch notices")}});D1.command("set").description("Create a new system notice").requiredOption("-m, --message <text>","Notice message text").option("-l, --level <level>","Notice level: tip, announcement, maintenance, warning, critical","tip").option("-s, --scope <scope>","Target scope: all, admins, members","all").option("-e, --expires <datetime>","Expiry datetime (ISO 8601)").action(async(e)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(![...l6,"info"].includes(e.level))console.error(u.red(`Invalid level: ${e.level}. Use ${l6.join(", ")}.`)),process.exit(1);if(!["all","admins","members"].includes(e.scope))console.error(u.red(`Invalid scope: ${e.scope}. Use all, admins, or members.`)),process.exit(1);let t=C("Creating notice...").start();try{let n=await O0e({message:e.message,level:e.level,scope:e.scope,expires_at:e.expires});if(t.succeed(`Notice created (ID: ${n.id})`),console.log(` Level: ${n.level}`),console.log(` Scope: ${n.scope}`),console.log(` Message: ${n.message}`),n.expires_at)console.log(` Expires: ${n.expires_at}`)}catch(n){qt(n,t,"Failed to create notice")}});D1.command("clear <id>").description("Delete a notice by ID").option(Ze,ct).option(Rt,kt).action(async(e,t)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let n=Number.parseInt(e,10);if(Number.isNaN(n))console.error(u.red("Invalid notice ID")),process.exit(1);if(await $e(`Delete notice #${n}?`,t,!1)!=="confirmed")return;let o=C("Deleting notice...").start();try{await T0e(n),o.succeed(`Notice #${n} deleted`)}catch(s){qt(s,o,"Failed to delete notice")}});Fe.addCommand(D1);function JLt(e){let t=[`${u.bold(`Announcement ${e.id}`)} ${u.cyan(e.status)}`,` Subject: ${e.subject}`,` To: ${e.recipient_group}`];if(e.category)t.push(` Category: ${e.category}`);if(e.recall_reference)t.push(` Recall reference: ${e.recall_reference}`);if(t.push(` Sent at: ${e.sent_at}`),e.status==="sent")t.push(` Delivered: ${e.queued_count>0?e.delivered_count:"n/a (sent inline)"}`),t.push(` Failed: ${e.failure_count}`);else{t.push(` Queued: ${e.queued_count}`),t.push(` Delivered: ${e.delivered_count}`),t.push(` Failed: ${e.failure_count}`),t.push(` Unconfirmed: ${e.unknown_count} (not retried; the provider never confirmed them)`);let n=e.skipped_count??0;if(n>0)t.push(` Skipped: ${n} (opted out or account changed after the send was queued)`);let r=e.queued_count-e.delivered_count-e.failure_count-e.unknown_count-n;if(r>0)t.push(` Pending: ${r}`)}if(e.failed_recipients.length>0){t.push(" Failed addresses are shown redacted and may not be unique:");for(let n of e.failed_recipients)t.push(u.red(` Failed: ${n}`))}return t}function YLt(e){let t=[];if(e.counts)t.push(` Audience by group: ${Object.entries(e.counts).map(([n,r])=>`${n} ${r}`).join(", ")}`);if(e.deliverable_count!==void 0&&e.deliverable_count!==e.recipient_count)t.push(u.yellow(` ${e.deliverable_count} of ${e.recipient_count} would be delivered; the rest are withheld by the non-production delivery fence`));if(e.would_refuse==="duplicate_send")t.push(u.yellow(` A real send would be refused as a repeat of announcement ${e.duplicate_of} (use --allow-repeat to send anyway)`));for(let n of e.blockers??[])t.push(u.red(` A real send would be refused now: ${n}`));if(e.recipients){t.push("");for(let n of e.recipients)t.push(` ${n}`)}else if(e.sample&&e.sample.length>0)t.push(` Sample (redacted): ${e.sample.join(", ")}`),t.push(" Addresses are listed in production only.");return t}async function XLt(e,t){if(t!==void 0)return t.trim()===e?e:void 0;if(!process.stdin.isTTY)return;try{let{typed:n}=await Ne.prompt([{type:"input",name:"typed",message:`A recall reaches every account in the selected group, ignores email preferences and cannot be undone. Type the reference (${e}) to send it:`}]);return typeof n==="string"&&n.trim()===e?e:void 0}catch{return}}function QLt(e){if(e.notice_id!==void 0)return[u.green(` Site notice #${e.notice_id} published. Clear it when the recall is resolved: nemar admin notice clear ${e.notice_id}`)];if(e.notice_skipped==="canary")return[u.yellow(" No site notice yet: this send went to part of the audience. The send to all publishes it.")];if(e.notice_skipped==="nothing_queued")return[u.yellow(" No site notice was published because nothing was queued. Run the recall again; it publishes the notice once it goes out.")];return[u.yellow.bold(" OWNER STEP: a recall also needs a public site notice, and none was published."),u.yellow(' Publish one now: nemar admin notice set --level critical --message "NEMAR recall: <subject> (reference: <reference>). Check your email for what to do."')]}Fe.command("notify").description("Send a categorized email to a group, or an email to a single user").option("--to <group>","Recipient group: all, admins, members").option("--category <category>",`Category of a group send (required with --to): ${Z0.join(", ")}. Recipients who turned it off are skipped; a recall (owner only) ignores that`).option("--recall-ref <reference>","What a recall is about: a dataset id with optional version (nm000104@v1.2.0) or a nemarOrg issue, pull request or security advisory URL").option("--confirm-recall <reference>","Type the recall reference again to confirm sending a recall (--yes does not replace it)").option("--allow-repeat","Send even if the same category, subject and group went out in the last 24 hours").option("--user <username>","Send to a single user by username (direct contact, no category)").option("--subject <text>","Email subject line").option("--body <text>","Email body (markdown)").option("--body-file <path>","Read email body from file (markdown)").option("--dry-run","Preview recipients without sending").option("--status <id>","Show the progress of a queued announcement by its ID").option("--json","Output raw JSON (with --status)").option(Ze,ct).option(Rt,kt).action(async(e)=>{if(!Je())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.status!==void 0){let f=Number(e.status);if(!Number.isInteger(f)||f<1)console.error(u.red(`Invalid announcement ID: ${e.status}`)),process.exit(1);let p=e.json?null:C("Fetching announcement status...").start();try{let m=await Dbe(f);if(e.json){console.log(JSON.stringify(m,null,2));return}p?.stop();for(let h of JLt(m))console.log(h)}catch(m){qt(m,p??C(),"Failed to fetch announcement status")}return}if(!e.subject)console.error(u.red("Email subject required. Use --subject.")),process.exit(1);let t=e.subject;if(e.to&&e.user)console.error(u.red("--to and --user are mutually exclusive. Provide exactly one.")),process.exit(1);if(!e.to&&!e.user)console.error(u.red("Provide either --to <group> or --user <username>.")),process.exit(1);if(e.to&&!["all","admins","members"].includes(e.to))console.error(u.red(`Invalid group: ${e.to}. Use all, admins, or members.`)),process.exit(1);if(e.user){if(e.category||e.recallRef||e.confirmRecall||e.allowRepeat)console.error(u.red("--user is direct contact and takes no --category, --recall-ref, --confirm-recall or --allow-repeat.")),process.exit(1)}else if(!e.category)console.error(u.red(`A group send needs --category <${Z0.join("|")}>. Use --user for direct contact.`)),process.exit(1);else if(!Hne(e.category))console.error(u.red(`Invalid category: ${e.category}. Use ${Z0.join(", ")}.`)),process.exit(1);let n=e.category===Bne;if(!n&&(e.recallRef||e.confirmRecall))console.error(u.red("--recall-ref and --confirm-recall belong to --category recall only.")),process.exit(1);let r=e.recallRef?.trim();if(n){if(!r||!Vne(r))console.error(u.red(`--recall-ref is required. ${Wne}`)),process.exit(1)}let o;if(e.bodyFile){if(!E1(e.bodyFile))console.error(u.red(`File not found: ${e.bodyFile}`)),process.exit(1);o=OLt(e.bodyFile,"utf-8")}else if(e.body)o=e.body;else console.error(u.red("Email body required. Use --body or --body-file.")),process.exit(1);if(n){let f=zne(o);if(f.length>0)console.error(u.red(`A recall body needs the headings ${FI.map((p)=>`"${p}"`).join(" and ")} (markdown, for example "## What is affected"). Missing: ${f.join(", ")}.`)),process.exit(1)}let s=e.user?`user:${e.user}`:`${e.to} (${e.category})`,i=e.user?{user:e.user,subject:t,body:o}:{to:e.to,category:e.category,...n?{recall_reference:r}:{},...e.allowRepeat?{allow_repeat:!0}:{},subject:t,body:o};if(e.dryRun){let f=C("Checking recipients...").start();try{let p=await ZM({...i,dry_run:!0});if("dry_run"in p){f.succeed(`Dry run: ${p.recipient_count} recipient(s) for "${p.recipient_group}"${p.category?` (${p.category})`:""}`);for(let m of YLt(p))console.log(m)}}catch(p){qt(p,f,"Failed to check recipients")}return}if(console.log(u.bold("Email preview:")),console.log(` To: ${u.cyan(s)}`),n)console.log(u.red.bold(" RECALL: reaches every account in this group, ignores email preferences, cannot be unsubscribed from.")),console.log(` Reference: ${r}`);console.log(` Subject: ${t}`),console.log(` Body: ${o.length>100?`${o.substring(0,100)}...`:o}`),console.log();let a=e.user?`Send this email to ${e.user}?`:"Send this broadcast email?";if(await $e(a,e,!1)!=="confirmed")return;let l;if(n){if(l=await XLt(r,e.confirmRecall),l===void 0)console.error(u.red(`Recall not sent: the confirmation must be the reference exactly as given (${r}).`)),process.exit(1)}let d=C(e.user?`Sending to ${e.user}...`:"Sending broadcast...").start();try{let f=await ZM({...i,...l===void 0?{}:{confirm_recall:l}});if("broadcast_id"in f){if(f.error==="queue_enqueue_failed")d.warn(`Enqueue failed (ID ${f.broadcast_id}): ${f.recipient_count} queued, ${f.failure_count} not queued; check progress with: nemar admin notify --status ${f.broadcast_id}`);else if(f.status==="queued"&&f.failure_count===0)d.succeed(`Queued ${f.recipient_count} announcement(s) (ID ${f.broadcast_id}); check progress with: nemar admin notify --status ${f.broadcast_id}`);else if(f.failure_count>0){d.warn(`Email send: ${f.recipient_count} delivered, ${f.failure_count} failed`);for(let p of f.failed_recipients)console.log(u.red(` Failed: ${p}`))}else{let p=e.user?`Email sent to ${e.user}`:`Broadcast sent to ${f.recipient_count} recipient(s)`;d.succeed(`${p} (ID: ${f.broadcast_id})`)}if((f.suppressed_count??0)>0)console.log(u.yellow(` ${f.suppressed_count} recipient(s) withheld by the non-production delivery fence`));if(n)for(let p of QLt(f))console.log(p)}}catch(f){qt(f,d,"Failed to send email")}});var ZLt=1500;function e4t(e){switch(e.kind){case"ok":return u.green(`ok ${e.schema_version}`);case"stale":return u.yellow(`stale ${e.schema_version}`);case"missing":return u.red("missing");case"error":return u.red(`error ${e.status||"?"}: ${e.message}`)}}function t4t(e){return e.kind==="stale"||e.kind==="missing"}function n4t(e){let n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`)}var XTe=new ie("summary").description("summary.json coverage across published dataset versions");XTe.command("check").description("Report which (dataset_id, version) pairs have stale or missing summary.json").option("--fix","Dispatch generate-manifest for every stale/missing version").option("--id <id>","Limit to a single dataset_id (exact match)").option("--match <glob>","Limit to dataset_ids matching a glob pattern: `*` matches any run of chars, `?` matches one char. Examples: `on*`, `nm00010?`, `*99999`. Can be combined with --id (id wins if both passed).").option("--only-stale","Print only rows that are not ok (suppresses ok rows)").option("--json","Emit the full report as JSON instead of a table").option(Ze,ct).option(Rt,kt).action(async(e)=>{if(!ke())return;let t=C("Building coverage report...").start(),n;try{n=await Cbe()}catch(p){qt(p,t,"Failed to fetch coverage report");return}t.succeed(`Coverage: target=schema ${n.target_schema}, versions=${n.totals.versions}`);let r=n.versions,o=null;if(e.id){if(r=r.filter((p)=>p.dataset_id===e.id),o=`dataset_id=${e.id}`,r.length===0){console.log(u.yellow(`No rows for ${o}`));return}}else if(e.match){let p=n4t(e.match);if(r=r.filter((m)=>p.test(m.dataset_id)),o=`--match ${e.match}`,r.length===0){console.log(u.yellow(`No rows match ${o}`));return}console.log(u.dim(`Scoped to ${r.length} version(s) matching ${e.match}`))}if(e.json){console.log(JSON.stringify(o?{...n,versions:r,totals:RTe(r)}:n,null,2));return}let s=e.onlyStale?r.filter((p)=>p.state.kind!=="ok"):r;if(s.length===0)console.log(u.green("All versions at target schema \u2014 no drift."));else{let p=Math.max(...s.map((h)=>h.dataset_id.length),10),m=Math.max(...s.map((h)=>h.version.length),7);for(let h of s)console.log(` ${h.dataset_id.padEnd(p)} ${h.version.padEnd(m)} ${e4t(h.state)}`)}let i=o?RTe(r):n.totals;if(console.log(),console.log(` Total: ${i.versions} ${u.green(`ok=${i.ok}`)} ${u.yellow(`stale=${i.stale}`)} ${u.red(`missing=${i.missing}`)} ${u.red(`error=${i.error}`)}`),!e.fix){if(i.stale+i.missing>0)console.log(u.dim(`
2271
2271
  Run with --fix to dispatch generate-manifest for the ${i.stale+i.missing} drifted version(s).`));return}let a=r.filter((p)=>t4t(p.state));if(a.length===0){console.log(u.green(`
2272
2272
  Nothing to dispatch.`));return}let c=o?` (scoped to ${o})`:"",l=await $e(`Dispatch generate-manifest for ${a.length} version(s)${c}? Each dispatch queues a runner job on nemarDatasets/.github.`,e);if(l!=="confirmed"){console.log(u.dim(l==="declined"?"Skipped":"Cancelled"));return}let d=0,f=0;console.log();for(let[p,m]of a.entries()){let h=`${m.dataset_id}@${m.version}`,g=C(`[${p+1}/${a.length}] dispatching ${h}...`).start();try{await Abe(m.dataset_id,m.version),g.succeed(`[${p+1}/${a.length}] dispatched ${h}`),d++}catch(y){g.fail(`[${p+1}/${a.length}] ${h}: ${W(y)}`),f++}if(p<a.length-1)await new Promise((y)=>setTimeout(y,ZLt))}if(console.log(),console.log(f===0?u.green(`All ${d} dispatches succeeded.`):u.yellow(`${d} succeeded, ${f} failed.`)),console.log(u.dim("Workflow runs will appear on https://github.com/nemarDatasets/.github/actions. Re-run `nemar admin summary check` once they complete to verify drift cleared.")),f>0)process.exitCode=1});function RTe(e){return{versions:e.length,ok:e.filter((t)=>t.state.kind==="ok").length,stale:e.filter((t)=>t.state.kind==="stale").length,missing:e.filter((t)=>t.state.kind==="missing").length,error:e.filter((t)=>t.state.kind==="error").length}}Fe.addCommand(XTe);var QTe=new ie("zarr-catalog").description("Top-level Zarr discovery catalog (zarr-catalog.json)");QTe.command("publish").description("Rebuild and republish zarr-catalog.json to this environment's bucket").action(async()=>{if(!ke())return;let e=C("Publishing zarr-catalog.json...").start();try{let t=await Obe();e.succeed(`Published zarr-catalog.json: ${t.count} dataset(s), ${t.bytes} bytes`)}catch(t){qt(t,e,"Failed to publish zarr catalog"),process.exit(1)}});Fe.addCommand(QTe);var ZTe=new ie("backfill-names").description("Fill missing researcher names from users' public ORCID records (dry run by default)");ZTe.option("--apply","Write the names (without this flag, only report what would change)").option("--limit <n>","Users per batch (server clamps to [1,100])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=e.apply===!0,r=C(n?"Backfilling names from ORCID...":"Checking ORCID for missing names...").start(),o;try{o=await Ube({apply:n,limit:t}),r.stop()}catch(s){r.fail("Name backfill failed"),console.error(u.red(W(s))),process.exit(1);return}if(o.lookup_failed>0||(o.write_failed??0)>0||o.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.apply)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(u.cyan(`scanned=${o.scanned} ${o.apply?"filled":"would_fill"}=${o.apply?o.filled:o.would_fill} no_public_name=${o.no_public_name} lookup_failed=${o.lookup_failed} write_failed=${o.write_failed??0} remaining=${o.remaining??"unknown"}`));for(let s of o.results){let i=s.username??`id ${s.id} <${s.email}>`;if(s.outcome==="filled"||s.outcome==="would_fill"){let a=s.outcome==="filled"?u.green("filled "):u.cyan("would fill");console.log(` ${a} ${i}: ${s.given_name} ${s.family_name} (${s.orcid})`)}else if(s.outcome==="no_public_name")console.log(` ${u.yellow("no name ")} ${i}: ORCID ${s.orcid} does not publish a full name`);else if(s.outcome==="write_failed")console.log(` ${u.red("write ")} ${i}: ${s.error}; retry the batch`);else console.log(` ${u.red("error ")} ${i}: ${s.error}`)}if(o.warning)console.log(u.yellow(` Warning: ${o.warning}`));if(o.no_public_name>0)console.log(),console.log(u.dim("These accounts must make their name public on their ORCID record and sign in again; NEMAR cannot type a name in for an ORCID-linked account, because the record is re-read on every sign-in and would overwrite it. An account with no verified ORCID can set its name in Settings (ADR 0042)."))});Fe.addCommand(ZTe);function r4t(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}function o4t(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}var x1=20,e2e=new ie("import-issue-triage").description("Close recovered import-failure issues and retire stale cause labels (dry run by default)");e2e.option("--apply","Perform the changes (without this flag, only report what would change)").option("--limit <n>","Issues per batch (server clamps to [1,30])","15").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=e.limit??"15",n=t.trim()===""?Number.NaN:Number(t);if(!Number.isInteger(n)||n<1){console.error(u.red(`Invalid --limit ${JSON.stringify(t)}: expected an integer >= 1.`)),process.exitCode=1;return}let r=e.apply===!0,o=C(r?"Triaging import-failure issues...":"Checking import-failure issues...").start(),s;try{s=await jbe({apply:r,limit:n}),o.stop()}catch(i){o.fail("Import-failure issue triage failed"),console.error(u.red(W(i)));let a=i instanceof U?i.details:void 0,c=r4t(a)?a.errors:[];if(e.json)console.log(JSON.stringify(i instanceof U?i.rawBody??{errors:c}:{errors:c},null,2));else for(let l of c)console.error(`${u.red("ERROR".padEnd(15))} #${l.issue} ${l.dataset_id??""} ${l.stage}: ${l.error}`);process.exitCode=1;return}if(s.errors.length>0)process.exitCode=1;if(e.json){console.log(JSON.stringify(s,null,2));return}if(console.log(),!s.applied)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));for(let i of s.plan){let a=i.failed?"FAILED ":s.applied?"":"WOULD ",c=`#${i.issueNumber} ${i.datasetId??"(unknown)"}`;if(i.kind==="close"){let l=`${a}CLOSE`.padEnd(15);console.log(`${i.failed?u.red(l):u.green(l)} ${c} ${u.dim(i.reason)}`)}else if(i.kind==="relabel"){let l=`${a}RELABEL`.padEnd(15);console.log(`${i.failed?u.red(l):u.yellow(l)} ${c} ${u.dim(i.reason)}`)}else console.log(`${u.dim("KEEP".padEnd(15))} ${c} ${u.dim(i.reason)}`)}for(let i of s.rollups){let c=(i.outcome==="failed"?"FAILED RELEASE":i.outcome==="released"?"RELEASE":s.mode==="per-dataset"?"WOULD RELEASE":"ROLLUP").padEnd(15);console.log(`${i.outcome==="failed"?u.red(c):u.magenta(c)} #${i.number} ${u.dim(i.title)}`)}for(let i of s.errors)console.log(`${u.red("ERROR".padEnd(15))} #${i.issue} ${i.dataset_id??""} ${i.stage}: ${i.error}`);if(console.log(),console.log(u.cyan(`open=${s.openIssues} mode=${s.mode} examined=${s.examined} attempted=${s.attempted} ${s.applied?"closed":"would_close"}=${s.closed} ${s.applied?"relabelled":"would_relabel"}=${s.relabelled} kept=${s.kept} errors=${s.errors.length} remaining=${s.remaining}`)),s.remaining>0)console.log(u.dim(` ${s.remaining} candidate(s) outside this run's window; the window rotates daily.`));if(s.mode==="rollup")console.log(u.dim(" Rollup mode: new failures with a cause that already has a rollup join it instead of opening their own issue."));if(s.rollupsReleased>0)console.log(u.dim(` ${s.applied?"Released":"Would release"} ${s.rollupsReleased} rollup(s): the backlog has drained, so per-dataset filing resumes.`));if(s.audit_failed)console.log(u.yellow(` Changes were applied but the audit row failed to write: ${s.audit_failed}`));if(!s.applied&&(s.closed>0||s.relabelled>0||s.rollupsReleased>0))console.log(u.dim(" Re-run with --apply to perform these changes."));if(s.reconcile==null)console.log(),console.log(u.yellow(`reconcile=unknown${s.reconcileError?`: ${s.reconcileError}`:""}`));else{let i=s.reconcile;console.log(),console.log(u.cyan(`reconcile rows_without_issue=${i.rowsWithoutIssue.length} issues_without_row=${i.issuesWithoutRow.length} parked=${i.parked} quarantined=${i.quarantined} rows_examined=${i.rowsExamined} issues_examined=${i.issuesExamined}`));for(let l of i.rowsWithoutIssue.slice(0,x1))console.log(`${u.yellow("UNTRACKED".padEnd(15))} ${l.datasetId} (${l.sourceId}) ${l.status} at ${l.stage} ${u.dim(l.cause)}`);let a=i.rowsWithoutIssue.length-x1;if(a>0)console.log(u.dim(` ... and ${a} more untracked`));for(let l of i.issuesWithoutRow.slice(0,x1))console.log(`${u.yellow("NO IMPORT ROW".padEnd(15))} #${l.number} ${l.datasetId}`);let c=i.issuesWithoutRow.length-x1;if(c>0)console.log(u.dim(` ... and ${c} more`));if(console.log(u.dim(` ${i.reason}`)),i.rowsWithoutIssue.length>0||i.issuesWithoutRow.length>0)console.log(u.dim(" Reported only: this command files and closes nothing for these."))}});Fe.addCommand(e2e);var t2e=new ie("import-coverage").description("Check whether the import pipeline is keeping up with OpenNeuro (dry run by default)"),v1=20,$Te=5,s4t={created:"create",refreshed:"refresh",relabelled:"relabel",closed:"close"};t2e.option("--apply","File, update or close the tracking issue (production only)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=e.apply===!0,n=C("Checking import coverage...").start(),r;try{r=await Lbe({apply:t}),n.stop()}catch(c){n.fail("Import coverage check failed"),console.error(u.red(W(c)));let l=c instanceof U?c.details:void 0,d=o4t(l)?l.errors:[];if(e.json)console.log(JSON.stringify(c instanceof U?c.rawBody??{errors:d}:{errors:d},null,2));else for(let f of d)console.error(`${u.red("ERROR".padEnd(12))} ${f.stage}: ${f.error}`);process.exitCode=c instanceof U&&c.statusCode===502?2:1;return}if(r.status==="unknown")process.exitCode=2;else if(r.status!=="healthy"||r.errors.length>0)process.exitCode=1;if(process.exitCode!==0)ue();if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.backlog,s=o.neverAttempted.length+o.untracked.length;console.log();let i=`${r.status.toUpperCase()}${r.kind?` (${r.kind})`:""}`;console.log(r.status==="healthy"?u.green(i):u.red(u.bold(i))),console.log(r.reason),console.log(),console.log(u.cyan(`auto_import=${r.enabled?"enabled":u.red("DISABLED")} last_dispatch=${r.dispatchAgeHours===null?"never":r.dispatchAgeHours<0?"dated in the future":`${r.dispatchAgeHours}h ago`}${r.lastDispatchSourceId?` (${r.lastDispatchSourceId})`:""} dispatch_lost=${r.dispatchLost}`));let a=r.importedInScan+r.inFlight+r.terminal+s+o.tracked.length+o.blocklisted.length;if(console.log(u.cyan(`discovered=${r.discovered} in_scan=${r.importedInScan} in_flight=${r.inFlight} terminal=${r.terminal} tracked=${o.tracked.length} blocklisted=${o.blocklisted.length}`)),console.log(u.cyan(`outstanding=${s} (never_attempted=${o.neverAttempted.length} untracked=${o.untracked.length})`)),r.importedNotInScan>0)console.log(u.dim(` ${r.importedNotInScan} of ${r.imported} mirror(s) are no longer in the scan (upstream removal, unreadable snapshot, or a modality retag). Drift, not a gap.`));if(a!==r.discovered)console.log(u.yellow(` Counts do not balance (${a} accounted for vs ${r.discovered} discovered): this run did not get a complete view, so treat the verdict as unreliable.`));if(o.neverAttempted.length>0){let c=o.neverAttempted.slice(0,v1).join(", "),l=o.neverAttempted.length-v1;console.log(u.dim(` never attempted: ${c}${l>0?` ... and ${l} more`:""}`))}if(o.untracked.length>0){let c=o.untracked.slice(0,v1).join(", "),l=o.untracked.length-v1;console.log(u.dim(` stale row nothing owns: ${c}${l>0?` ... and ${l} more`:""}`))}for(let c of r.errors){let l=`${c.stage}: ${c.error}`;console.log(c.stage==="anomaly"?`${u.yellow("ANOMALY".padEnd(12))} ${l}`:`${u.red("ERROR".padEnd(12))} ${l}`)}if(r.issue){let c=r.applied?r.issue.action:`would ${s4t[r.issue.action]??r.issue.action}`,l=r.issue.number===null?"":` #${r.issue.number}`;if(console.log(u.dim(` Issue: ${c}${l} on nemarDatasets/.github`)),r.issue.labelError)console.log(u.yellow(` The body was updated but its labels were not: ${r.issue.labelError}`));if(r.issue.commentError)console.log(u.yellow(` The issue changed but its comment failed: ${r.issue.commentError}`))}if(r.audit_failed)console.log(u.yellow(` Changes applied but the audit row failed to write: ${r.audit_failed}`));if(!r.applied&&r.issue)console.log(u.dim(" Re-run with --apply to perform this change."))});Fe.addCommand(t2e);var n2e=new ie("import-weekly").description("Read this week's import summary (dry run by default; the cron posts it on Mondays)");function i4t(e){return wN(e).attention}function bn(e){return e==null?u.yellow("unknown"):String(e)}n2e.option("--apply","Actually file the issue (production only; the cron normally does this)").option("--json","Output raw JSON instead of the human summary").option("--body","Also print the issue body exactly as it would be posted").action(async(e)=>{if(!ke())return;let t=e.apply===!0,n=C("Building the weekly import summary...").start(),r;try{r=await qbe({apply:t}),n.stop()}catch(a){n.fail("Weekly import summary failed"),console.error(u.red(W(a))),process.exitCode=1;return}let o=r.facts;if(o===null)process.exitCode=0;else if(o.errors.length>0)process.exitCode=2;else if(i4t(o))process.exitCode=1;if(process.exitCode!==0)ue();if(e.json){console.log(JSON.stringify(r,null,2));return}if(o===null){console.log(),console.log(u.yellow(`Nothing computed: ${r.gateReason}`)),console.log(u.dim(" The report is built once a week; --apply files it."));return}console.log(),console.log(u.bold(`Import summary ${o.week}`)),console.log(u.dim(`${o.windowStart} to ${o.windowEnd} (UTC)`)),console.log(),console.log(u.cyan(`imported_this_week=${bn(o.importedThisWeek)} total=${bn(o.importedTotal)} in_scope=${bn(o.discovered)} not_in_scope=${bn(o.importedNotInScan)}`));let s=o.coverageStatus===null?u.yellow("unknown"):o.coverageStatus==="healthy"?u.green(o.coverageStatus):u.red(o.coverageStatus);if(console.log(u.cyan(`coverage=${s} outstanding=${bn(o.outstanding)}`)),console.log(u.cyan(`auto_import=${o.autoImportEnabled===null?u.yellow("unknown"):o.autoImportEnabled?"enabled":u.red("DISABLED")} last_dispatch=${o.dispatchPhrase??u.yellow("unknown")} dispatch_lost=${o.dispatchLost===null?u.yellow("unknown"):o.dispatchLost}`)),console.log(u.cyan(`open_failures=${bn(o.openFailureTotal)} parked=${o.parked===null?u.yellow("unknown"):o.parked.length} closed_this_week=${bn(o.issuesClosed)} relabelled=${bn(o.issuesRelabelled)}`)),o.upstream==null)console.log(u.cyan(`upstream=${u.yellow("unknown")}`));else{let a=o.upstream.counts.states,c=o.upstream.truncated?` ${u.yellow("(did not reach every mirror)")}`:"",l=`upstream: stale=${bn(o.upstream.counts.stale)} current=${bn(a.current)} anomaly=${bn(a.anomaly)} unknown=${bn(a.unknown)} unchecked=${bn(a.unchecked)}`;console.log(u.cyan(`${l}${c}`))}if(o.repulls==null)console.log(u.cyan(`repulls=${u.yellow("unknown")}`));else{let a=o.repulls,c=a.switches,l=c.auto_repull_merge_enabled?"open+merge":c.auto_repull_enabled?"open":"off";console.log(u.cyan(`repulls: switches=${l} dispatched=${bn(a.dispatches.sent)} opened=${bn(a.dispatches.by_status.opened)} refused=${bn(a.dispatches.by_status.refused)} failed=${bn(a.dispatches.by_status.failed)} unreported=${bn(a.dispatches.by_status.unreported)} not_accepted=${bn(a.dispatches.by_status.dispatch_failed)}`)),console.log(u.cyan(`repulls: open=${bn(a.open_automatic.total)} held=${bn(a.open_automatic.held)} claims_held=${bn(a.held_claims)} ended_failed=${bn(a.ended_failed)} merged_worker=${bn(a.merged.worker)} merged_admin=${bn(a.merged.administrator)} merged_outside=${bn(a.merged.outside_tool)} merged_unattributed=${bn(a.merged.unattributed)}`))}if(o.failuresByCause!==null){let a=Object.entries(o.failuresByCause).filter(([,c])=>c>0);for(let[c,l]of a)console.log(u.dim(` ${c}: ${l}`))}if(o.parked!==null&&o.parked.length>0){for(let c of o.parked.slice(0,$Te))console.log(u.dim(` parked ${c.datasetId} (${c.reason??"unknown"}): ${c.parkedDays==null?"unknown":`${c.parkedDays} days`}`));let a=o.parked.length-$Te;if(a>0)console.log(u.dim(` ... and ${a} more parked`))}for(let a of o.errors)console.log(`${u.yellow("UNKNOWN".padEnd(10))} ${a.stage}: ${a.error}`);let i=wN(o);if(i.attention)console.log(u.yellow(`Needs attention: ${i.problems.join("; ")}.`));if(console.log(),!r.posted&&!t)console.log(u.dim("Dry run: nothing was filed.")),console.log(u.dim(" Re-run with --apply to file it (production only)."));else if(!r.posted)console.log(u.yellow(`Not posted: ${r.gateReason}`));else console.log(u.green(`Posted${r.issue?.number?` #${r.issue.number}`:""}${r.closedPrevious?`, closed #${r.closedPrevious}`:""}`));if(e.body)console.log(),console.log(u.dim("--- rendered issue body ---")),console.log(r.renderedBody??u.yellow("(no body was rendered)"))});Fe.addCommand(n2e);var r2e=new ie("backfill-usernames").description("Give username-less accounts a username from their name (dry run by default)");r2e.option("--apply","Write the usernames and send verification messages").option("--limit <n>","Users per batch (server clamps to [1,100])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=e.apply===!0,r=C(n?"Assigning usernames...":"Checking which accounts need a username...").start(),o;try{o=await Bbe({apply:n,limit:t}),r.stop()}catch(s){r.fail("Username backfill failed"),console.error(u.red(W(s))),process.exit(1);return}if(o.lookup_failed>0||o.conflict>0||(o.exhausted??0)>0||(o.write_failed??0)>0||(o.verify_failed??0)>0||(o.verify_rate_limited??0)>0||o.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.apply)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(u.cyan(`scanned=${o.scanned} ${o.apply?"assigned":"would_assign"}=${o.apply?o.assigned:o.would_assign} single_name=${o.single_name} no_name=${o.no_name} lookup_failed=${o.lookup_failed} conflict=${o.conflict} exhausted=${o.exhausted??0} write_failed=${o.write_failed??0} verify_sent=${o.verify_sent} verify_failed=${o.verify_failed??0} verify_rate_limited=${o.verify_rate_limited??0} remaining=${o.remaining??"unknown"}`));for(let s of o.results){let i=`id ${s.id} <${s.email}>`,a=[s.given_name,s.family_name].filter(Boolean).join(" ");if(s.outcome==="assigned"||s.outcome==="would_assign"){let c=s.outcome==="assigned"?u.green("assigned "):u.cyan("would give"),l=s.outcome==="assigned"?` [verify: ${s.verify}]`:"";console.log(` ${c} ${i}: ${u.cyan(s.username??"?")} (${a})${l}`)}else if(s.outcome==="single_name")console.log(` ${u.yellow("one name ")} ${i}: only "${a}" on record; pick a username by hand`);else if(s.outcome==="no_name")console.log(` ${u.yellow("no name ")} ${i}: run 'nemar admin backfill-names --apply' first`);else if(s.outcome==="conflict")console.log(` ${u.yellow("conflict ")} ${i}: ${s.error}`);else if(s.outcome==="exhausted")console.log(` ${u.yellow("exhausted ")} ${i}: ${s.error}; pick a username by hand`);else if(s.outcome==="write_failed")console.log(` ${u.red("write ")} ${i}: ${s.error}; retry the batch`);else console.log(` ${u.red("error ")} ${i}: ${s.error}`)}for(let s of o.verify_retries??[]){let i=s.verify==="sent"?u.green("re-sent "):s.verify==="not_attempted"?u.cyan("would send"):u.yellow(`verify ${s.verify}`);console.log(` ${i} id ${s.id} <${s.email}>`)}if(o.warning)console.log(u.yellow(` Warning: ${o.warning}`));if(o.single_name>0||o.no_name>0)console.log(),console.log(u.dim("Accounts with one name or none are listed, never guessed at: a username derived from an email address is a handle the person never chose."))});Fe.addCommand(r2e);var o2e=new ie("duplicates").description("Report live accounts sharing an ORCID iD, email, or GitHub handle");function a4t(e){let t=e.username??u.dim("(no username)"),n=[];if(e.canonical)n.push(u.green("canonical"));if(e.identity_conflict===1)n.push(u.yellow("flagged"));if(e.has_oauth_identity)n.push(u.dim("orcid-login"));let r=n.length>0?` [${n.join(", ")}]`:"",o=`created ${e.created_at} datasets=${e.dataset_count}`;console.log(` id ${String(e.id).padEnd(5)} ${t} <${e.email}> ${o}${r}`)}o2e.option("--json","Output raw JSON instead of the human report").option("--clear <id>","Clear one account's identity-conflict flag (refuses while the collision remains)").action(async(e)=>{if(!ke())return;if(e.clear!==void 0){let r=Number.parseInt(e.clear,10);if(!Number.isInteger(r)||r<=0){console.error(u.red(`Invalid user id: ${e.clear}`)),process.exit(1);return}let o=C(`Clearing identity-conflict flag on user ${r}...`).start();try{let s=await Gbe(r);if(o.stop(),e.json){console.log(JSON.stringify(s,null,2));return}console.log(s.cleared?u.green(`Cleared the identity-conflict flag on user ${r}.`):u.dim(`User ${r} was not flagged; nothing to clear.`))}catch(s){o.fail(s instanceof U&&s.statusCode===409?"Still colliding; flag not cleared":"Failed to clear the identity-conflict flag"),console.error(u.red(W(s))),process.exit(1)}return}let t=C("Checking for duplicate accounts...").start(),n;try{n=await Hbe(),t.stop()}catch(r){t.fail("Duplicate report failed"),console.error(u.red(W(r))),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.groups.length===0){if(console.log(u.green("No duplicate accounts.")),n.flagged_count>0)console.log(u.yellow(`${n.flagged_count} account(s) still carry an identity-conflict flag with no remaining collision.`)),console.log(u.dim(" Clear each with 'nemar admin duplicates --clear <id>'."));return}console.log(u.cyan(`${n.group_count} duplicate group(s); ${n.flagged_count} account(s) flagged`));for(let r of n.groups){console.log(),console.log(` ${u.bold(r.kind)} ${r.value}`);for(let o of r.accounts)a4t(o)}console.log(),console.log(u.dim("The fix is self-service on the surviving account: change its email or GitHub username, or unlink/re-link its ORCID iD, in Settings on nemar.org. Merging two accounts is manual.")),process.exitCode=1});Fe.addCommand(o2e);var C1=new ie("neurobagel").description("Neurobagel federation artifacts: regenerate and inspect the private store (epic #1586)"),Sa=(e)=>e===null?u.yellow("unknown"):String(e),BU=(e)=>e==="healthy"?u.green(e):e==="alarm"?u.red(e):e==="unknown"?u.yellow(e):u.dim(e);function s2e(e){console.log(`${u.bold("Verification")} ${BU(e.overall)} ${e.at} (${e.trigger})${e.failed?u.red(` the sweep itself failed: ${e.error??"no reason recorded"}`):""}`);for(let t of roe){let n=e.checks[t];console.log(` ${t.padEnd(13)}${BU(n.verdict)} ${n.reason}`)}for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`))}function c4t(e){if(console.log(),e.dry_run)console.log(u.yellow("DRY RUN: nothing was written. Re-run with --execute to write."));if(e.status!=="ok"){let t=e.status==="disabled"?"the writer is disabled (NEUROBAGEL_WRITER_ENABLED is not 1)":e.status==="store_unconfigured"?"no NEUROBAGEL bucket is bound":e.error??"the run failed";console.log(u.red(`status=${e.status}: ${t}`))}console.log(u.cyan(`eligible=${Sa(e.eligible)} examined=${e.examined} limit=${e.limit} unexamined=${e.unexamined} removed=${e.removed.length} removals_pending=${e.removals_pending} index_entries=${Sa(e.index.entries)} index_written=${e.index.written} index_patched=${e.index.patched??0} anonymity_findings=${e.anonymity_findings} ops=${e.ops.spent}/${e.ops.budget}`));for(let t of e.results)switch(t.outcome){case"written":console.log(` ${u.green("written ")} ${t.id}${t.flags.length>0?` needs review: ${t.flags.join(", ")}`:""}`);break;case"would_write":console.log(` ${u.cyan("would write")} ${t.id} (${t.reason})`);break;case"unchanged":console.log(` ${u.dim("unchanged ")} ${t.id}`);break;case"would_remove":console.log(` ${u.cyan("would remove")} ${t.id}`);break;case"removed":console.log(` ${u.green("removed ")} ${t.id}`);break;case"refused":console.log(` ${u.red("refused ")} ${t.id} ${t.code}${t.detail?`: ${t.detail}`:""}`);break;case"error":console.log(` ${u.red("error ")} ${t.id} ${t.error}`);break}if(e.stopped==="ops_budget")console.log(u.yellow(` the run spent its operation budget (${e.ops.spent} of ${e.ops.budget}, ${e.ops.reserved} of it held back to finish) with ${e.unexamined} dataset(s) not yet examined: run the same command again to continue`));else if(e.unexamined>0&&e.stopped===null)console.log(u.yellow(` ${e.unexamined} dataset(s) are still waiting beyond this call's limit: run the same command again to continue`));if(e.index.contended)console.log(u.red(" the index was replaced by another run during this one; re-run to settle it"));for(let t of e.index.problems??[])console.log(u.red(` index not written: ${t}`));for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`));if(e.anonymity_findings>0)console.log(u.red(` ${e.anonymity_findings} dataset(s) were refused because their data says anonymous. They are in the audit log (neurobagel_anonymity_finding); nothing was filed or mailed.`))}C1.command("regenerate").description("Examine datasets and write what changed to the Neurobagel artifact store (dry run unless --execute)").option("--execute","Write to the store (without it, only report what would change)").option("--dataset <ids...>","Examine exactly these dataset ids instead of the next ones due").option("--limit <n>",`Datasets to examine (default: the server's per-tick bound, at most ${QS}); run again to continue`).option("--force","Rewrite even when the fingerprint matches").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=e.limit===void 0?void 0:/^[1-9][0-9]*$/.test(e.limit)?Number(e.limit):Number.NaN;if(t!==void 0&&!Number.isInteger(t)){console.error(u.red("--limit must be a positive whole number")),process.exit(1);return}if(t!==void 0&&t>QS){console.error(u.red(`--limit is at most ${QS} per call (each call runs inside one request); run the command again to continue`)),process.exit(1);return}let n=e.execute===!0,r=C(n?"Regenerating Neurobagel artifacts...":"Checking what would change...").start(),o;try{o=await Tbe({...n?{execute:!0}:{},...e.dataset&&e.dataset.length>0?{datasets:e.dataset}:{},...t!==void 0?{limit:t}:{},...e.force?{force:!0}:{}}),r.stop()}catch(i){qt(i,r,"Neurobagel regenerate failed",{409:"Set NEUROBAGEL_WRITER_ENABLED=1 (and bind the bucket) to write. A dry run needs neither the switch nor --execute."}),process.exit(1);return}if(e.json)console.log(JSON.stringify(o,null,2));else c4t(o);let s=o.results.some((i)=>i.outcome==="error");if(o.status!=="ok"||s||o.index.contended||o.stopped==="index_patch"||(o.index.problems?.length??0)>0||o.anonymity_findings>0)process.exitCode=1});C1.command("status").description("What is eligible, written, stale and waiting on a person in the Neurobagel store, and the latest verification (exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=C("Reading the Neurobagel store...").start(),n;try{n=await Pbe(),t.stop()}catch(l){qt(l,t,"Neurobagel status failed"),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.writer.mode==="enabled"?u.green("enabled"):n.writer.mode==="disabled"?u.yellow("disabled (NEUROBAGEL_WRITER_ENABLED is not 1)"):u.red("store_unconfigured (no NEUROBAGEL bucket is bound)");console.log(),console.log(`${u.bold("Writer")} ${r}`),console.log(`${u.bold("Read route")} ${n.read_route.token_configured?u.green("token configured"):u.yellow("no NEUROBAGEL_READ_TOKEN: the route answers 404")}`),console.log(`${u.bold("Per tick")} ${n.limits.reconcile_max} datasets (hard limit ${n.limits.hard_max})`),console.log();let o=n.counts;console.log(`${u.bold("Datasets")} eligible=${Sa(o.eligible)} written=${Sa(o.written)} missing=${Sa(o.missing)} stale=${Sa(o.stale)} incomplete=${Sa(o.incomplete)} waiting to be removed=${Sa(o.residue)}`),console.log(`${u.bold("Store")} objects=${Sa(n.store.objects)} bytes=${Sa(n.store.total_bytes)}${n.store.over_loader_cap?u.red(" OVER the loader's total cap"):""}${(n.store.unexpected_objects??0)>0?u.yellow(` ${n.store.unexpected_objects} object(s) that are not the writer's`):""}`);let s=n.index.matches_store===null?u.yellow("unknown"):n.index.matches_store?u.green("matches the store"):u.yellow("differs from what the store and eligibility imply (the next run settles it)");console.log(`${u.bold("Index")} ${n.index.present===null?u.yellow("unknown"):n.index.present?`${Sa(n.index.entries)} entries, generated ${n.index.generated_at??"?"}`:u.dim("not written yet")} ${s}`);let i=n.last_reconcile;console.log(`${u.bold("Last reconcile")} ${i?`${i.at} (${JSON.stringify(i.summary)})`:u.dim("none recorded")}`),console.log(`${u.bold("Anonymity")} ${n.anonymity_findings===null?u.yellow("unknown"):n.anonymity_findings===0?"no findings":u.red(`${n.anonymity_findings} finding(s): see the audit log (neurobagel_anonymity_finding); ids are not shown here`)}`);let a=ooe({verification:n.verification,writerMode:n.writer.mode,now:new Date});if(n.verification)s2e(n.verification);if(a.note)console.log(`${u.bold("Verification")} ${BU(a.verdict)} ${a.note}`);else if(!n.verification)console.log(`${u.bold("Verification")} ${u.dim("none recorded; the writer is off, so none is expected")}`);if(n.needs_review.length>0){console.log(),console.log(u.bold(`Needs review (${n.needs_review.length})`));for(let l of n.needs_review)console.log(` ${l.id} ${l.source==="refusal"?u.red(`refused: ${l.code}${l.since?` (last confirmed ${l.since})`:""}`):u.yellow((l.flags??[]).join(", "))}`)}for(let l of n.warnings)console.log(u.yellow(`warning: ${l}`));let c=n.writer.mode==="store_unconfigured"||(n.anonymity_findings??0)>0||n.counts.eligible===null||a.verdict==="alarm";process.exitCode=c?1:bN(a.verdict)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined (no verification recorded while the writer is on, a record over 36 hours old, or an unknown verdict). The same as `verify`.");C1.command("verify").description("Run the verification sweep now: the store against eligibility, the node, registration and upstream drift (reports only; exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=C("Verifying the Neurobagel federation...").start(),n;try{n=await Ibe(),t.stop()}catch(r){qt(r,t,"Neurobagel verify failed"),process.exit(1);return}if(e.json)console.log(JSON.stringify(n,null,2));else if(console.log(),s2e(n),!n.heartbeat_written)console.log(u.yellow("The heartbeat could not be written: this run is not recorded."));process.exitCode=bN(n.overall)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined. The same as `status`.");Fe.addCommand(C1);Fe.addCommand(Ea);Fe.addCommand(bu);Fe.addCommand(yy);Fe.addCommand(Bve);Fe.addCommand(Pc);We();gi();Ro();rp();Bh();Mh();We();rp();Bh();var l4t=En["cli.gaps.section.title"];function i2e(e){if(e.gaps===void 0)return[e.unknownReason??En["cli.gaps.unknown"]];let t=OS(e.gaps,{orcidVerified:e.orcidVerified}).map(qne);if(e.sandboxCompleted===!1)t.push(TS());return t.length>0?t:[En["gaps.none"]]}function u4t(e){let t=i2e(e);return t.length===1&&t[0]===En["gaps.none"]}function nv(e){let t=e.gaps===void 0||u4t(e);console.log(),console.log(u.bold(l4t));for(let n of i2e(e))console.log(` ${t?u.dim(n):u.yellow(n)}`)}function A1(e,t,n={}){let r=n.indent??" ";console.log(),console.log(`${r}${e}`);for(let o of t)console.log(`${r} ${u.yellow(o.label)} ${NI(o)}`)}Ve();Xp();Pr();_n();We();CS();import{hostname as d4t}from"os";Ve();_n();function f4t(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").trim();return t?t.slice(0,Ane):TI}function p4t(){try{return f4t(d4t())}catch{return TI}}function m4t(e,t,n=OI){return e+(t+n)*1000}function l2e(e){switch(e.kind){case"cancelled":return{lines:["Sign-in canceled. Run `nemar auth login` to try again."],exitCode:130};case"denied":case"expired":case"invalid":return{lines:[e.message],exitCode:1};case"unreachable":return{lines:[`NEMAR could not be reached: ${e.detail}`,"Run `nemar auth login` again once you're back online."],exitCode:1};case"server_error":return{lines:[`NEMAR keeps answering with an error (${e.detail}). Try again in a few minutes; if it keeps happening, run \`nemar auth login --debug\` and report the log.`],exitCode:1};case"start_failed":return{lines:[`Could not start sign-in: ${e.detail}`],exitCode:1}}}var h4t=15000,a2e=1000,g4t=5000,c2e=3;function y4t(e){if(e instanceof U&&e.statusCode!==0)return`HTTP ${e.statusCode}`;return W(e)}function b4t(e){if(typeof AbortSignal.any==="function")return AbortSignal.any(e);let t=new AbortController;for(let n of e){if(n.aborted){t.abort();break}n.addEventListener("abort",()=>t.abort(),{once:!0})}return t.signal}function w4t(e,t){return new Promise((n)=>{if(t.aborted){n();return}let r=setTimeout(()=>{t.removeEventListener("abort",o),n()},e);function o(){clearTimeout(r),n()}t.addEventListener("abort",o,{once:!0})})}async function _4t(e,t={}){let n=Date.now(),r=m4t(n,e.expires_in,t.graceSeconds??OI),o=Math.max(e.interval*1000,a2e),s=new AbortController,i=()=>s.abort();process.on("SIGINT",i);let a=0;try{while(!0){if(s.signal.aborted)return{kind:"cancelled"};if(Date.now()>=r)return{kind:"unreachable",detail:"gave up waiting to reach NEMAR"};if(await w4t(o,s.signal),s.signal.aborted)return{kind:"cancelled"};let c=b4t([s.signal,AbortSignal.timeout(h4t)]),l;try{l=await z0e(e.device_code,c),a=0}catch(d){if(s.signal.aborted)return{kind:"cancelled"};if(d instanceof U&&d.statusCode===0){console.log(u.dim(" NEMAR is unreachable; retrying...")),a=0;continue}let f=y4t(d);if(a+=1,Nn(`poll error ${a}/${c2e}: ${f} -- ${W(d)}`),console.log(u.dim(` NEMAR answered with an error (${f}); retrying...`)),a>=c2e)return{kind:"server_error",detail:f};continue}if(l.status==="pending")continue;if(l.status==="slow_down"){o=Math.max(o+g4t,e.interval*1000,a2e);continue}if(l.status==="success")return{...l.data,kind:"success"};if(l.error==="expired_token")return{kind:"expired",message:l.message};if(l.error==="access_denied")return{kind:"denied",message:l.message};return{kind:"invalid",message:l.message}}}finally{process.off("SIGINT",i)}}async function JU(e={}){let t;try{t=await G0e(p4t())}catch(n){return{kind:"start_failed",detail:W(n)}}if(console.log(` ${t.verification_uri_complete}`),console.log(` Code: ${u.cyan(t.user_code)}`),console.log(u.dim(" (if the page asks for it)")),console.log(),e.open!==!1&&xy(t.verification_uri_complete))console.log(u.dim(" (trying to open your browser; use the link above if it doesn't)")),console.log();return _4t(t)}wr();var u2e="NEMAR_DATA_HOSTS",x4t="NEMAR_DATA_HOSTS_ONLY",v4t="https://private.nemar.org",E4t="https://private-test.nemar.org",S4t=/^[a-z]{2,3}[0-9]{6}$/;function O1(e){return S4t.test(e)}function k4t(e){return e}function d2e(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function f2e(e){let t=e.trim();if(t===""||/[?#@]/.test(t))return null;let n;try{n=new URL(t)}catch{return null}if(n.username!==""||n.password!=="")return null;if(n.pathname!=="/")return null;if(n.protocol==="https:")return n.origin;if(n.protocol==="http:"&&d2e(n.hostname))return n.origin;return null}function p2e(e){let t=[],n=[];for(let r of(e??"").split(",")){let o=r.trim();if(o==="")continue;let s=f2e(o);if(s===null)n.push(o);else if(!t.includes(s))t.push(s)}return{origins:t,rejected:n}}function m2e(e){return e.env??process.env}function T1(e={}){let t=m2e(e),n=e.isDevBuild??vp,r=t[x4t]==="1"?[]:[n?E4t:v4t],{origins:o}=p2e(t[u2e]);return[...r,...o.filter((s)=>!r.includes(s))].map(k4t)}function h2e(e={}){return p2e(m2e(e)[u2e]).rejected}function P1(e,t={}){let n=f2e(e);if(n===null)return null;return T1(t).find((r)=>r===n)??null}function I1(e,t={}){return P1(e,t)!==null}function g2e(e,t={}){let n;try{n=new URL(e)}catch{return null}if(n.username!==""||n.password!=="")return null;return P1(n.origin,t)}function Akn(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&d2e(e.hostname)&&new URL(t).protocol==="http:"}var R4t="NEMAR_DATA_HOST_TIMEOUT_MS";function y2e(e,t=process.env){let n=t[R4t];if(n===void 0||!/^[0-9]+$/.test(n))return e;let r=Number(n);return r>0&&r<e?r:e}function b2e(e){if(!(e instanceof Error))return"error";let t=e.code;return typeof t==="string"&&/^[A-Z][A-Z0-9_]+$/.test(t)?`${e.name} ${t}`:e.name}var $4t="nemar";function w2e(e){let t={};for(let n of e.split(`
2273
2273
  `)){let r=n.replace(/\r$/,"");if(r==="")break;let o=r.indexOf("=");if(o<=0)continue;t[r.slice(0,o)]=r.slice(o+1)}return t}function YU(e,t={}){let{protocol:n,host:r}=e;if(!n||!r)return!1;if(/[/?#@\s]/.test(r))return!1;return I1(`${n}://${r}`,t)}function _2e(e,t,n,r={}){if(e!=="get"||!n||!YU(t,r))return"";return`username=${$4t}
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.37-PR2286.09be6aa",
4
+ "version": "0.10.37-PR2286.abb2a7d",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",