nemar-cli 0.10.24-PR1920.3ae2b25 → 0.10.24-PR1920.a9fae0a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -99,7 +99,7 @@ ${t}`,S4e,$4e,k4e=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,i=E4e.bind(nul
99
99
  `)}var IC=!1;var{spawn:cZe}=globalThis.Bun;function lu(e,t=[]){let r=e.replace(lZe,'("$1","<redacted>")');for(let n of t)if(n.length>=uZe)r=r.split(n).join("<redacted>");return r}function Wx(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 i of t){let o=n[i];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function zne(e,t){let r=e.getReader(),n=new TextDecoder,i="";while(!0){let{done:o,value:s}=await r.read();if(o)break;if(s.byteLength===0)continue;t(),i+=n.decode(s,{stream:!0})}return i+n.decode()}async function k(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let b of t.unsetEnv??[])delete r[b];let n=cZe({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),i=!1,o,s,a=performance.now(),c=()=>{if(s!==void 0)clearTimeout(s),s=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),s=setTimeout(()=>{s=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??dZe)};if(u(),t.timeout)o=setTimeout(()=>{i=!0,c(),n.kill()},t.timeout);let d=Gx()?[...Wx(r),...t.redact??[]]:[];if(Gx()){let b=t.cwd?` (cwd=${t.cwd})`:"";Xc(l.dim(lu(`$ ${e.join(" ")}${b}`,d)))}let f=()=>{a=performance.now(),u()},p,m,h,g=n.exited.then((b)=>(c(),b));try{[p,m,h]=await Promise.all([zne(n.stdout,f),zne(n.stderr,f),g])}finally{if(c(),o)clearTimeout(o)}if(Gx()){if(t.sensitiveOutput)Xc(l.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())Xc(l.dim(lu(p.trimEnd(),d)));if(m.trim())Xc(l.yellow(lu(m.trimEnd(),d)))}Xc(l.dim(`(exit ${h})`))}if(i)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 lZe,uZe=8,dZe=120000;var Lt=N(()=>{je();lZe=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function pZe(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function Hne(e,t=pZe()){return e.installInstructions[t]}function mZe(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function gZe(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:hZe}async function Gne(e){try{let{exitCode:t,stdout:r,timedOut:n}=await k(e.cmd,{timeout:gZe()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:mZe(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 Wh(){let e=Object.entries(Vne);return Promise.all(e.map(async([t,r])=>{let{available:n,version:i,timedOut:o}=await Gne(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:i,timedOut:o,installInstruction:Hne(r)}}))}async function Wne(){let t=(await Wh()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
100
100
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let 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 uu(e){let r=fZe[e].map((s)=>Vne[s]).filter(Boolean),n=await Promise.all(r.map(async(s)=>{let a=await Gne(s);return{check:s,available:a.available,timedOut:a.timedOut}}));for(let s of n)if(s.timedOut&&s.check.required)console.warn(`Warning: ${s.check.name} did not respond to a version check in time; continuing anyway.`);let i=n.filter((s)=>!s.available&&!s.timedOut&&s.check.required).map((s)=>({tool:s.check.name,installInstruction:Hne(s.check)}));if(i.length===0)return;let o=[`
101
101
  Missing required tools:`];for(let s of i)o.push(` ${s.tool} not installed`),o.push(` Install: ${s.installInstruction}`);throw Error(o.join(`
102
- `))}var Vne,fZe,hZe=4000;var Kh=N(()=>{Lt();Vne={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)"}}},fZe={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 Yne;var Kne=N(()=>{Yne={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.24-PR1920.3ae2b25",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var co;var ep=N(()=>{Kne();co=Yne.version});import{mkdirSync as bZe,readdirSync as wZe,unlinkSync as xZe,writeFileSync as vZe}from"fs";import{join as NC}from"path";function tie(){tp=!0}function du(){return tp}function rie(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Jh(e){eie=e,rr(`Step: ${e}`)}function Qc(){Qne=!0}function nie(){return Qne}function Re(){if(Zne)return;jC=!0}function MC(){jC=!1,Zne=!0}function iie(){return jC}function rr(e){if(tp)process.stderr.write(`[debug] ${e}
102
+ `))}var Vne,fZe,hZe=4000;var Kh=N(()=>{Lt();Vne={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)"}}},fZe={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 Yne;var Kne=N(()=>{Yne={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.24-PR1920.a9fae0a",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var co;var ep=N(()=>{Kne();co=Yne.version});import{mkdirSync as bZe,readdirSync as wZe,unlinkSync as xZe,writeFileSync as vZe}from"fs";import{join as NC}from"path";function tie(){tp=!0}function du(){return tp}function rie(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Jh(e){eie=e,rr(`Step: ${e}`)}function Qc(){Qne=!0}function nie(){return Qne}function Re(){if(Zne)return;jC=!0}function MC(){jC=!1,Zne=!0}function iie(){return jC}function rr(e){if(tp)process.stderr.write(`[debug] ${e}
103
103
  `)}function SZe(e){let t={};for(let[r,n]of Object.entries(e))t[r]=EZe.has(r.toLowerCase())?"[REDACTED]":n;return t}function sie(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function FC(e,t,r=0){if(r>kZe)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>FC(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[i,o]of Object.entries(t))n[i]=FC(i,o,r+1);return n}if(typeof t==="string"){if($Ze.test(e))return"[REDACTED]";return t.replace(oie,sie)}return t}function qC(e){return e.replace(RZe,"Bearer [REDACTED]").replace(CZe,"[REDACTED_AWS_KEY]").replace(AZe,"$1[REDACTED]").replace(OZe,"$1$2=[REDACTED]").replace(oie,sie)}function TZe(e){return qC(e)}function Jne(e,t=DZe){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(FC("",n))}catch{}if(r=qC(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function Jx(e){if(!tp)return;let t=TZe(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?SZe(e.requestHeaders):void 0,requestBody:Jne(e.requestBody),responseBody:Jne(e.responseBody)};Yx.push(r),rr(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=q(r);Yx.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),rr(`redaction failed for ${e.method} ${t}: ${n}`)}}async function PZe(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${co}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${q(t)})`)}e.push(""),e.push("Active account:");try{let t=jt();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: ${q(t)})`)}e.push(""),e.push("External tools:");try{let t=await Wh();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: ${q(t)})`)}return e}async function LC(){return(await PZe()).join(`
104
104
  `)}async function aie(){if(!tp||Kx!==void 0)return;try{Kx=await LC()}catch(e){let t=q(e);Kx=`(could not build environment report: ${t})`,rr(`environment snapshot failed: ${t}`)}}function cie(e){if(Xne.has(e))return{flag:e};for(let t of Xne){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 IZe(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=cie(n);if(!i){t.push(n);continue}if(i.kind==="long-eq")t.push(`${i.flag}=[REDACTED]`);else if(i.kind==="short-attached")t.push(`${i.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function NZe(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=cie(n);if(!i){t.push(n);continue}if(!i.kind&&r+1<e.length)r++}return t}function FZe(e){let t=[];for(let n of NZe(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 jZe(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${qC(IZe(e).join(" "))}`),r.push(""),r.push(Kx??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),Yx.length===0)r.push(" (none)");else Yx.forEach((n,i)=>{if(r.push(` [${i+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: ${eie??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
105
105
  `)}
@@ -1214,7 +1214,7 @@ Examples:
1214
1214
  `).action(async(e,t)=>{if(!he())return;await Promise.resolve().then(() => s0());await Promise.resolve().then(() => sme());await Promise.resolve().then(() => hv());let o=e;if(o.length===0){console.log(l.yellow("Name the datasets to act on."));return}let s=o.filter((f)=>ua.has(f));if(s.length>0&&!t.force)console.log(l.red(`Refusing to touch live dataset(s): ${s.join(", ")}`)),console.log(l.dim(" --force to override.")),process.exit(1);if(t.apply){let f=await Ce(`Copy missing content into s3://nemar for ${o.length} dataset(s)?`,t);if(f!=="confirmed"){console.log(l.yellow(`${f}; nothing was changed.`));return}}let a;if(t.limit!==void 0){if(a=Number(t.limit),!Number.isInteger(a)||a<1)console.log(l.red(`Error: --limit must be a positive integer (got ${t.limit})`)),process.exit(1)}let c=t.dir??oT(Ea(sT(),"nemar-content-recovery-"));mme(c,{recursive:!0}),console.log();let u=[],d=await ome(o,fD(),{workRoot:c,apply:Boolean(t.apply),limit:a,concurrency:Number(t.concurrency)||8,onDataset:(f,p,m)=>{let h=(w)=>`${(w/1073741824).toFixed(1)} GiB`,g=f.action==="failed"?l.red(f.datasetId):f.action==="recovered"?l.green(f.datasetId):l.dim(f.datasetId);for(let w of f.keys)if(w.leftInBucket)u.push({datasetId:f.datasetId,key:w.key});let b=f.error?f.error:!f.measured?"not measured":`${f.missing} missing (${h(f.missingBytes)}), ${f.recovered} recovered (${h(f.recoveredBytes)}), ${f.unrecoverable} unrecoverable (${h(f.unrecoverableBytes)}), ${f.failed} failed`;console.log(`${l.dim(`[${p}/${m}]`)} ${g} ${l.dim(b)}`)}});console.log();for(let[f,p]of Object.entries(d.tally))if(p>0)console.log(` ${f.padEnd(20)} ${p}`);if(console.log(` ${"keys recovered".padEnd(20)} ${d.recoveredKeys} (${(d.recoveredBytes/1073741824).toFixed(1)} GiB)`),u.length>0){console.log(l.red(`
1215
1215
  ${u.length} object(s) FAILED verification and could not be deleted.`)),console.log(l.red(" They will be advertised as real content by the next registration sweep."));for(let{datasetId:f,key:p}of u.slice(0,20))console.log(l.red(` ${f} ${p}`));if(u.length>20)console.log(l.red(` ... and ${u.length-20} more (see --json)`));console.log(l.dim(" Remove each with: aws s3api delete-object --bucket nemar --key ..."))}if(t.json)a0(t.json,JSON.stringify(d,null,2)),console.log(l.dim(`
1216
1216
  Report written to ${t.json}`));if(!t.apply)console.log(l.dim(`
1217
- Read-only: nothing was copied. Add --apply to recover.`));else if(d.recoveredKeys>0)console.log(l.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});ke.addCommand(El);var Rme=new ve("reindex").description("Refresh dataset metadata: enrichment + first-class D1 columns");Rme.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(!he())return;let r=[t.all,t.missingMetadata,t.stale].filter(Boolean).length;if(e&&r>0)console.error(l.red("Provide either a dataset-id OR a bulk flag (--all/--missing-metadata/--stale), not both")),process.exit(1);if(!e&&r===0)console.error(l.red("Provide a dataset-id or one of: --all, --missing-metadata, --stale")),process.exit(1);if(r>1)console.error(l.red("Use only one of --all, --missing-metadata, --stale")),process.exit(1);if(t.skipEnrichment&&t.skipSync)console.error(l.red("--skip-enrichment and --skip-sync cannot both be set")),process.exit(1);if(e){let f=S(`Reindexing ${e}...`).start();try{let p={skip_enrichment:t.skipEnrichment===!0,skip_sync:t.skipSync===!0,...t.ref&&{ref:t.ref}},m=await dp(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(),lme(m,{showRef:!0}),!h)process.exit(1)}catch(p){f.fail(`Failed to reindex ${e}`),console.error(l.red(q(p))),process.exit(1)}return}let n=t.all?"all":t.missingMetadata?"missing-metadata":"stale",i={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(l.red(`Invalid --older-than: "${t.olderThan}"`)),process.exit(1);i.older_than_days=f}else if(n==="missing-metadata")i.older_than_days=1;else if(n==="stale")i.older_than_days=30;let o=t.dryRun?`Listing ${n} datasets...`:`Reindexing ${n} datasets...`,s=S(o).start(),a;try{a=await aoe(n,i)}catch(f){s.fail("Bulk reindex failed"),console.error(l.red(q(f))),process.exit(1)}if(t.json){if(s.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(s.succeed(`${a.total} datasets match filter=${n} (dry run, no changes)`),a.datasets)for(let f of a.datasets)console.log(l.dim(` - ${f}`));return}let c=a.results??[],u=c.filter((f)=>f.enrichment.status!=="failed"&&f.sync.status!=="failed").length,d=c.length-u;if(d===0)s.succeed(`${c.length}/${c.length} datasets reindexed in ${(a.elapsed_ms/1000).toFixed(1)}s`);else s.warn(`${u}/${c.length} ok; ${d} failed in ${(a.elapsed_ms/1000).toFixed(1)}s`);console.log();for(let f of c)lme(f);if(d>0)process.exit(1)});ke.addCommand(Rme);var Lft=new ve("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(!he())return;if(!e&&!t.all)console.error(l.red("Provide a dataset-id or --all")),process.exit(1);if(e&&(t.all||t.reset||t.missingOnly))console.error(l.red("--all/--reset/--missing-only cannot be combined with a dataset id")),process.exit(1);if(e){let u=S(t.write?`Generating and writing availability report for ${e}...`:`Previewing availability report for ${e}...`).start(),d;try{d=await goe(e,{write:t.write===!0})}catch(g){u.fail(`Failed to generate availability report for ${e}`),console.error(l.red(q(g))),process.exit(1)}let f="report"in d?d.report:d,p="report"in d;if(u.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(l.yellow(" No published version manifest to compare against; completeness unknown."));else console.log(` Version: ${f.version}`);console.log(` Complete: ${f.complete?l.green("yes"):l.red("no")}`),console.log(` Files: ${f.completeness.files_present}/${f.completeness.files_declared} present`);let m=`${St(f.completeness.bytes_present)}/${St(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(l.yellow(` Blocklisted: ${f.blocklist_reason}`));if(f.missing.length>0){console.log(),console.log(l.dim(` Missing (${f.missing.length}):`));for(let g of f.missing)console.log(l.dim(` - ${g.path} [${g.reason}]`))}return}if(t.reset){let u=S("Resetting availability-report sweep state...").start();try{let d=await boe();if(u.succeed(`Cleared ${d.reset} stamped row(s); eligible datasets are candidates again`),t.json)console.log(JSON.stringify(d,null,2))}catch(d){u.fail("Reset failed"),console.error(l.red(q(d))),process.exit(1)}return}let r=Number.parseInt(t.limit??"10",10)||10,n=t.missingOnly===!0,i={processed:0,written:0,errors:0},o=S("Sweeping datasets for availability reports...").start(),s=0,a=null,c=null;try{let u;do{if(u=await yoe({limit:r,missingOnly:n}),s++,i.processed+=u.processed,i.written+=u.written,i.errors+=u.errors.length,a=u.remaining,t.verbose){o.stop(),console.log(` [batch ${s}] processed=${u.processed} written=${u.written} errors=${u.errors.length} remaining=${a??"?"}`);for(let d of u.errors)console.log(` ${l.red(d.dataset_id)}: ${d.error}`);o.start("Sweeping datasets for availability reports...")}else o.text=`Sweeping datasets for availability reports... ${i.processed} processed, ${a??"?"} remaining`;if(a!=null&&c!=null&&a>=c){o.warn(`No progress (remaining stuck at ${a}); stopping - see errors`);break}if(c=a,(a??0)>0)await qp(1000)}while((a??0)>0);o.stop()}catch(u){o.fail("Availability-report sweep failed"),console.error(l.red(q(u))),process.exit(1)}if(t.json)console.log(JSON.stringify({...i,batches:s,remaining:a},null,2));else{if(console.log(),a===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(l.cyan(`Done in ${s} batch(es): processed=${i.processed} written=${i.written} errors=${i.errors} remaining=${a??"unknown"}`))}if(i.errors>0||a===null)process.exit(1)});ke.addCommand(Lft);async function uT(e,t,r,n){let i=0,o=null,s=null;try{let a;do{if(a=await r(),i++,o=a.remaining,n(a,i,o),o!=null&&s!=null&&o>=s){e.warn(`No progress (remaining stuck at ${o}); stopping - see errors`);break}if(s=o,(o??0)>0)await qp(1000)}while((o??0)>0);e.stop()}catch(a){e.fail(t),console.error(l.red(q(a))),process.exit(1)}return{batches:i,remaining:o}}var Cme=new ve("hed-sweep").description("Backfill HED detection (has_hed / hed_version) for existing datasets (#869)");Cme.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(!he())return;if(e.reset){let s=S("Resetting HED sweep state...").start();try{let a=await loe();if(s.succeed(`Cleared ${a.reset} probed HED row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(a,null,2))}catch(a){s.fail("Reset failed"),console.error(l.red(q(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,r={processed:0,withHed:0,withoutHed:0,unknown:0,errors:0},n=S("Sweeping datasets for HED...").start(),{batches:i,remaining:o}=await uT(n,"HED sweep failed",()=>coe({limit:t}),(s,a,c)=>{if(r.processed+=s.processed,r.withHed+=s.withHed,r.withoutHed+=s.withoutHed,r.unknown+=s.unknown,r.errors+=s.errors.length,e.verbose){n.stop(),console.log(` [batch ${a}] processed=${s.processed} hed=${s.withHed} no-hed=${s.withoutHed} unknown=${s.unknown} errors=${s.errors.length} remaining=${c??"?"}`);for(let u of s.errors)console.log(` ${l.red(u.dataset_id)}: ${u.error}`);n.start("Sweeping datasets for HED...")}else n.text=`Sweeping datasets for HED... ${r.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...r,batches:i,remaining:o},null,2));else{if(console.log(),o===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(l.cyan(`Done in ${i} batch(es): processed=${r.processed} hed=${r.withHed} no-hed=${r.withoutHed} unknown=${r.unknown} errors=${r.errors} remaining=${o??"unknown"}`))}if(r.errors>0||o===null)process.exit(1)});ke.addCommand(Cme);var Ame=new ve("recording-stats-sweep").description("Backfill dataset-level recording duration/count/channel-range stats from each dataset's zarr index (migration 0070, #1146)");Ame.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(!he())return;if(e.reset){let s=S("Resetting recording-stats sweep state...").start();try{let a=await doe();if(s.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){s.fail("Reset failed"),console.error(l.red(q(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"50",10)||50,r={processed:0,measured:0,unmeasured:0,errors:0},n=S("Sweeping datasets for recording stats...").start(),{batches:i,remaining:o}=await uT(n,"Recording-stats sweep failed",()=>uoe({limit:t}),(s,a,c)=>{if(r.processed+=s.processed,r.measured+=s.measured,r.unmeasured+=s.unmeasured,r.errors+=s.errors.length,e.verbose){n.stop(),console.log(` [batch ${a}] processed=${s.processed} measured=${s.measured} unmeasured=${s.unmeasured} errors=${s.errors.length} remaining=${c??"?"}`);for(let u of s.errors)console.log(` ${l.red(u.dataset_id)}: ${u.error}`);n.start("Sweeping datasets for recording stats...")}else n.text=`Sweeping datasets for recording stats... ${r.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...r,batches:i,remaining:o},null,2));else{if(console.log(),o===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(l.cyan(`Done in ${i} batch(es): processed=${r.processed} measured=${r.measured} unmeasured=${r.unmeasured} errors=${r.errors} remaining=${o??"unknown"}`))}if(r.errors>0||o===null)process.exit(1)});ke.addCommand(Ame);var Ome=new ve("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)");Ome.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(!he())return;if(e.reset){let s=S("Resetting signal-defaults sweep state...").start();try{let a=await poe();if(s.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){s.fail("Reset failed"),console.error(l.red(q(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,r={processed:0,populated:0,noData:0,errors:0},n=S("Sweeping datasets for signal defaults...").start(),{batches:i,remaining:o}=await uT(n,"Signal-defaults sweep failed",()=>foe({limit:t}),(s,a,c)=>{if(r.processed+=s.processed,r.populated+=s.populated,r.noData+=s.noData,r.errors+=s.errors.length,e.verbose){n.stop(),console.log(` [batch ${a}] processed=${s.processed} populated=${s.populated} no-data=${s.noData} errors=${s.errors.length} remaining=${c??"?"}`);for(let u of s.errors)console.log(` ${l.red(u.dataset_id)}: ${u.error}`);n.start("Sweeping datasets for signal defaults...")}else n.text=`Sweeping datasets for signal defaults... ${r.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...r,batches:i,remaining:o},null,2));else{if(console.log(),o===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(l.cyan(`Done in ${i} batch(es): processed=${r.processed} populated=${r.populated} no-data=${r.noData} errors=${r.errors} remaining=${o??"unknown"}`))}if(r.errors>0||o===null)process.exit(1)});ke.addCommand(Ome);async function Bft(e,t,r){let n=e(),i={processed:0,complete:0,incomplete:0,unknown:0,errors:0},o=0,s=null,a=null,c=!1;do{let u=await t(n);if(o++,i.processed+=u.processed,i.complete+=u.complete,i.incomplete+=u.incomplete,i.unknown+=u.unknown,i.errors+=u.errors.length,s=u.remaining,r?.onBatch?.(u,i,o),s!=null&&a!=null&&s>=a){c=!0;break}if(a=s,(s??0)>0)await r?.sleepBetweenBatches?.()}while((s??0)>0);return{batches:o,totals:i,remaining:s,stalled:c}}var Tme=new ve("data-integrity-sweep").description("Audit datasets against their version manifest and backfill data_complete / bytes_present (epic #967 Phase 3, #970)");Tme.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(!he())return;if(e.reset){let c=S("Resetting data-integrity sweep state...").start();try{let u=await hoe();if(c.succeed(`Cleared ${u.reset} audited row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(u,null,2))}catch(u){c.fail("Reset failed"),console.error(l.red(q(u))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,r=e.olderThan?Number.parseInt(e.olderThan,10):void 0,n=S("Sweeping datasets for data integrity...").start(),i;try{if(i=await Bft(()=>e.reaudit?new Date().toISOString():void 0,async(c)=>{let u=await moe({limit:t,olderThan:r,before:c});return{processed:u.processed,complete:u.complete,incomplete:u.incomplete,unknown:u.unknown,errors:u.errors,remaining:u.remaining}},{onBatch:(c,u,d)=>{if(e.verbose){n.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(` ${l.red(f.dataset_id)}: ${f.error}`);n.start("Sweeping datasets for data integrity...")}else n.text=`Sweeping datasets for data integrity... ${u.processed} processed, ${c.remaining??"?"} remaining`},sleepBetweenBatches:()=>qp(1000)}),i.stalled)n.warn(`No progress (remaining stuck at ${i.remaining}); stopping - see errors`);else n.stop()}catch(c){n.fail("Data-integrity sweep failed"),console.error(l.red(q(c))),process.exit(1)}let{batches:o,totals:s,remaining:a}=i;if(e.json)console.log(JSON.stringify({...s,batches:o,remaining:a},null,2));else{if(console.log(),a===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));if(console.log(l.cyan(`Done in ${o} batch(es): processed=${s.processed} complete=${s.complete} incomplete=${s.incomplete} unknown=${s.unknown} errors=${s.errors} remaining=${a??"unknown"}`)),s.incomplete>0)console.log(l.yellow(`${s.incomplete} dataset(s) verified incomplete -- see 'nemar dataset list --json' (data_complete=0) for details.`))}if(s.errors>0||a===null)process.exit(1)});ke.addCommand(Tme);var Pme=new ve("zarr-fidelity-sweep").description("Re-verify published Zarr stores against their dataset's own BIDS metadata (#1068)");Pme.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(!he())return;let t=Number.parseInt(e.limit??"25",10)||25,r=S("Verifying Zarr store fidelity...").start(),n;try{n=await Toe({limit:t}),r.stop()}catch(i){r.fail("Zarr fidelity sweep failed"),console.error(l.red(q(i))),process.exit(1);return}if(e.json)console.log(JSON.stringify(n,null,2));else{console.log(),console.log(l.cyan(`processed=${n.processed} verified=${n.verified} failed=${n.failed} unverifiable=${n.unverifiable} errors=${n.errors.length} remaining=${n.remaining??"unknown"}${n.budget_exhausted?" budget_exhausted=true":""}`));for(let i of n.results){let o=i.verdict==="verified"?l.green:i.verdict==="failed"?l.red:l.yellow;console.log(` ${o(i.verdict.padEnd(12))} ${i.dataset_id} (sampled=${i.sampled} checked=${i.checked})`);for(let s of i.examples)console.log(` ${l.red(s.code)}: ${s.path}`);if(i.examples_truncated)console.log(` ${l.dim(`(${i.mismatch_count} mismatches total; showing first ${i.examples.length})`)}`)}for(let i of n.errors)console.log(` ${l.red("error")} ${i.dataset_id}: ${i.error}`)}if(n.errors.length>0||n.remaining===null||n.budget_exhausted)process.exit(1)});ke.addCommand(Pme);var Uft=250,Ime=new ve("upstream-backfill").description("Record which upstream snapshot each mirrored version came from (dry run unless --execute)");Ime.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(!he())return;let t=Number.parseInt(e.limit??"25",10)||25,r=Number.parseInt(e.maxBatches??"200",10)||200,n=e.execute===!0,i=(m)=>{if(!e.json)console.log(m)};if(!n)i(l.yellow("Dry run: nothing is written. Pass --execute to record."));i(l.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 o={batches:0,scanned:0,recorded:{doi:0,unknown:0},not_examined:0,unparseable:0,absent:0,skipped_existing:0},s=[],a=e.after,c=null,u=null,d=!1;for(let m=0;m<r;m++){let h;try{h=await Poe({execute:n,limit:t,after:a})}catch(g){u=q(g);break}c=h,o.batches++,o.scanned+=h.scanned,o.recorded.doi+=h.recorded.doi,o.recorded.unknown+=h.recorded.unknown,o.not_examined+=h.not_examined,o.unparseable+=h.unparseable,o.absent+=h.absent,o.skipped_existing+=h.skipped_existing,s.push(...h.errors),i(`${l.cyan(`batch ${o.batches}`)} scanned=${h.scanned} ${n?"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)i(` ${l.dim("unknown")} ${g.dataset_id}@${g.version}: ${g.reason}`);for(let g of h.errors)i(` ${l.red("error")} ${g.dataset_id}@${g.version}${g.kind==="needs_admin"?" [needs admin]":""}: ${g.error}`);if(!h.ok){d=h.suspect_credential,u=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,Uft))}let f=u===null&&c!==null&&c.next_cursor===null,p=f?null:a??null;if(e.json)console.log(JSON.stringify({execute:n,done:f,failure:u,suspect_credential:d,...o,errors:s,next_cursor:p,counts:c?.counts??null},null,2));else{if(u)console.error(l.red(`Stopped: ${u}`));if(!f&&!u)console.log(l.yellow(`Stopped at --max-batches ${r}; the pass is not done.`));if(p)console.log(`Resume with: --after ${p}`);if(f&&o.not_examined>0){let m=s.filter((g)=>g.kind==="needs_admin"),h=o.not_examined-m.length;if(h>0)console.log(l.yellow(`${h} row(s) were not examined after a transient error: rerun without --after to try them again.`));if(m.length>0)console.log(l.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(l.cyan(`On versions now: doi=${c.counts.doi} lineage=${c.counts.lineage} unknown=${c.counts.unknown} not_examined=${c.counts.not_examined}`));if(!n)console.log(l.yellow("Dry run, pass --execute to record."))}if(u!==null||s.length>0||!f)process.exit(1)});ke.addCommand(Ime);var Nme=new ve("anonymity-sweep").description("Re-check anonymous deposits against the identity-leak inventory (#1409)");Nme.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(!he())return;if(e.reset){let i=S("Re-arming anonymous deposits...").start();try{let o=await Uoe();i.succeed(`Re-armed ${o.reset} anonymous deposit(s).`)}catch(o){i.fail("Reset failed"),console.error(l.red(q(o))),process.exit(1)}return}let t=Number.parseInt(e.limit??"10",10)||10,r=S("Checking anonymous deposits...").start(),n;try{n=await Boe({limit:t}),r.stop()}catch(i){r.fail("Anonymity sweep failed"),console.error(l.red(q(i))),process.exit(1);return}if(e.json)console.log(JSON.stringify(n,null,2));else{console.log(),console.log(l.cyan(`processed=${n.processed} verified=${n.verified} findings=${n.with_findings} unverifiable=${n.unverifiable} errors=${n.errors.length} mail_failures=${n.mail_failures.length} remaining=${n.remaining??"unknown"}${n.budget_exhausted?" budget_exhausted=true":""}`));for(let i of n.results){let o=i.status==="verified"?l.green:i.status==="findings"?l.red:l.yellow;console.log(` ${o(i.status.padEnd(13))} ${i.dataset_id} (files ${i.files_scanned}/${i.files_listed})`);for(let s of i.findings){let a=s.severity==="invariant"?l.red("NEMAR"):l.yellow("deposit");console.log(` ${a} ${s.check}: ${s.detail}`)}if(i.unchecked.length>0)console.log(` ${l.dim(`not checked: ${i.unchecked.join(", ")}`)}`)}for(let i of n.errors)console.log(` ${l.red("error")} ${i.dataset_id}: ${i.error}`);for(let i of n.mail_failures)console.log(` ${l.red("not mailed")} ${i.dataset_id} -> ${i.recipient}: ${i.error}`)}if(n.errors.length>0||n.mail_failures.length>0||n.remaining===null||n.budget_exhausted)process.exit(1)});ke.addCommand(Nme);var xD=new ve("doctor").description("Diagnose and heal stuck-dataset patterns (e.g. missing S3 version manifests)");function zft(e){let t=0;for(let[r,n]of Object.entries(e.results)){t+=n.count;let i=n.count>0?l.red(`${n.count} finding(s)`):l.green("clean");console.log(`${l.bold(r)}: ${i} \u2014 ${n.description}`);for(let o of n.findings)console.log(` ${o.dataset_id}${o.version?`@v${o.version}`:""}`)}return t}xD.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(!he())return;let r=S("Running doctor checks (read-only; a full-catalog scan can take ~1 minute)...").start();try{let n=await d2({check:t.check,datasetId:e});if(r.stop(),t.json){console.log(JSON.stringify(n,null,2));return}let i=zft(n);if(i>0)console.log(l.yellow(`
1217
+ Read-only: nothing was copied. Add --apply to recover.`));else if(d.recoveredKeys>0)console.log(l.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});ke.addCommand(El);var Rme=new ve("reindex").description("Refresh dataset metadata: enrichment + first-class D1 columns");Rme.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(!he())return;let r=[t.all,t.missingMetadata,t.stale].filter(Boolean).length;if(e&&r>0)console.error(l.red("Provide either a dataset-id OR a bulk flag (--all/--missing-metadata/--stale), not both")),process.exit(1);if(!e&&r===0)console.error(l.red("Provide a dataset-id or one of: --all, --missing-metadata, --stale")),process.exit(1);if(r>1)console.error(l.red("Use only one of --all, --missing-metadata, --stale")),process.exit(1);if(t.skipEnrichment&&t.skipSync)console.error(l.red("--skip-enrichment and --skip-sync cannot both be set")),process.exit(1);if(e){let f=S(`Reindexing ${e}...`).start();try{let p={skip_enrichment:t.skipEnrichment===!0,skip_sync:t.skipSync===!0,...t.ref&&{ref:t.ref}},m=await dp(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(),lme(m,{showRef:!0}),!h)process.exit(1)}catch(p){f.fail(`Failed to reindex ${e}`),console.error(l.red(q(p))),process.exit(1)}return}let n=t.all?"all":t.missingMetadata?"missing-metadata":"stale",i={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(l.red(`Invalid --older-than: "${t.olderThan}"`)),process.exit(1);i.older_than_days=f}else if(n==="missing-metadata")i.older_than_days=1;else if(n==="stale")i.older_than_days=30;let o=t.dryRun?`Listing ${n} datasets...`:`Reindexing ${n} datasets...`,s=S(o).start(),a;try{a=await aoe(n,i)}catch(f){s.fail("Bulk reindex failed"),console.error(l.red(q(f))),process.exit(1)}if(t.json){if(s.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(s.succeed(`${a.total} datasets match filter=${n} (dry run, no changes)`),a.datasets)for(let f of a.datasets)console.log(l.dim(` - ${f}`));return}let c=a.results??[],u=c.filter((f)=>f.enrichment.status!=="failed"&&f.sync.status!=="failed").length,d=c.length-u;if(d===0)s.succeed(`${c.length}/${c.length} datasets reindexed in ${(a.elapsed_ms/1000).toFixed(1)}s`);else s.warn(`${u}/${c.length} ok; ${d} failed in ${(a.elapsed_ms/1000).toFixed(1)}s`);console.log();for(let f of c)lme(f);if(d>0)process.exit(1)});ke.addCommand(Rme);var Lft=new ve("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(!he())return;if(!e&&!t.all)console.error(l.red("Provide a dataset-id or --all")),process.exit(1);if(e&&(t.all||t.reset||t.missingOnly))console.error(l.red("--all/--reset/--missing-only cannot be combined with a dataset id")),process.exit(1);if(e){let u=S(t.write?`Generating and writing availability report for ${e}...`:`Previewing availability report for ${e}...`).start(),d;try{d=await goe(e,{write:t.write===!0})}catch(g){u.fail(`Failed to generate availability report for ${e}`),console.error(l.red(q(g))),process.exit(1)}let f="report"in d?d.report:d,p="report"in d;if(u.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(l.yellow(" No published version manifest to compare against; completeness unknown."));else console.log(` Version: ${f.version}`);console.log(` Complete: ${f.complete?l.green("yes"):l.red("no")}`),console.log(` Files: ${f.completeness.files_present}/${f.completeness.files_declared} present`);let m=`${St(f.completeness.bytes_present)}/${St(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(l.yellow(` Blocklisted: ${f.blocklist_reason}`));if(f.missing.length>0){console.log(),console.log(l.dim(` Missing (${f.missing.length}):`));for(let g of f.missing)console.log(l.dim(` - ${g.path} [${g.reason}]`))}return}if(t.reset){let u=S("Resetting availability-report sweep state...").start();try{let d=await boe();if(u.succeed(`Cleared ${d.reset} stamped row(s); eligible datasets are candidates again`),t.json)console.log(JSON.stringify(d,null,2))}catch(d){u.fail("Reset failed"),console.error(l.red(q(d))),process.exit(1)}return}let r=Number.parseInt(t.limit??"10",10)||10,n=t.missingOnly===!0,i={processed:0,written:0,errors:0},o=S("Sweeping datasets for availability reports...").start(),s=0,a=null,c=null;try{let u;do{if(u=await yoe({limit:r,missingOnly:n}),s++,i.processed+=u.processed,i.written+=u.written,i.errors+=u.errors.length,a=u.remaining,t.verbose){o.stop(),console.log(` [batch ${s}] processed=${u.processed} written=${u.written} errors=${u.errors.length} remaining=${a??"?"}`);for(let d of u.errors)console.log(` ${l.red(d.dataset_id)}: ${d.error}`);o.start("Sweeping datasets for availability reports...")}else o.text=`Sweeping datasets for availability reports... ${i.processed} processed, ${a??"?"} remaining`;if(a!=null&&c!=null&&a>=c){o.warn(`No progress (remaining stuck at ${a}); stopping - see errors`);break}if(c=a,(a??0)>0)await qp(1000)}while((a??0)>0);o.stop()}catch(u){o.fail("Availability-report sweep failed"),console.error(l.red(q(u))),process.exit(1)}if(t.json)console.log(JSON.stringify({...i,batches:s,remaining:a},null,2));else{if(console.log(),a===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(l.cyan(`Done in ${s} batch(es): processed=${i.processed} written=${i.written} errors=${i.errors} remaining=${a??"unknown"}`))}if(i.errors>0||a===null)process.exit(1)});ke.addCommand(Lft);async function uT(e,t,r,n){let i=0,o=null,s=null;try{let a;do{if(a=await r(),i++,o=a.remaining,n(a,i,o),o!=null&&s!=null&&o>=s){e.warn(`No progress (remaining stuck at ${o}); stopping - see errors`);break}if(s=o,(o??0)>0)await qp(1000)}while((o??0)>0);e.stop()}catch(a){e.fail(t),console.error(l.red(q(a))),process.exit(1)}return{batches:i,remaining:o}}var Cme=new ve("hed-sweep").description("Backfill HED detection (has_hed / hed_version) for existing datasets (#869)");Cme.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(!he())return;if(e.reset){let s=S("Resetting HED sweep state...").start();try{let a=await loe();if(s.succeed(`Cleared ${a.reset} probed HED row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(a,null,2))}catch(a){s.fail("Reset failed"),console.error(l.red(q(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,r={processed:0,withHed:0,withoutHed:0,unknown:0,errors:0},n=S("Sweeping datasets for HED...").start(),{batches:i,remaining:o}=await uT(n,"HED sweep failed",()=>coe({limit:t}),(s,a,c)=>{if(r.processed+=s.processed,r.withHed+=s.withHed,r.withoutHed+=s.withoutHed,r.unknown+=s.unknown,r.errors+=s.errors.length,e.verbose){n.stop(),console.log(` [batch ${a}] processed=${s.processed} hed=${s.withHed} no-hed=${s.withoutHed} unknown=${s.unknown} errors=${s.errors.length} remaining=${c??"?"}`);for(let u of s.errors)console.log(` ${l.red(u.dataset_id)}: ${u.error}`);n.start("Sweeping datasets for HED...")}else n.text=`Sweeping datasets for HED... ${r.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...r,batches:i,remaining:o},null,2));else{if(console.log(),o===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(l.cyan(`Done in ${i} batch(es): processed=${r.processed} hed=${r.withHed} no-hed=${r.withoutHed} unknown=${r.unknown} errors=${r.errors} remaining=${o??"unknown"}`))}if(r.errors>0||o===null)process.exit(1)});ke.addCommand(Cme);var Ame=new ve("recording-stats-sweep").description("Backfill dataset-level recording duration/count/channel-range stats from each dataset's zarr index (migration 0070, #1146)");Ame.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(!he())return;if(e.reset){let s=S("Resetting recording-stats sweep state...").start();try{let a=await doe();if(s.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){s.fail("Reset failed"),console.error(l.red(q(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"50",10)||50,r={processed:0,measured:0,unmeasured:0,errors:0},n=S("Sweeping datasets for recording stats...").start(),{batches:i,remaining:o}=await uT(n,"Recording-stats sweep failed",()=>uoe({limit:t}),(s,a,c)=>{if(r.processed+=s.processed,r.measured+=s.measured,r.unmeasured+=s.unmeasured,r.errors+=s.errors.length,e.verbose){n.stop(),console.log(` [batch ${a}] processed=${s.processed} measured=${s.measured} unmeasured=${s.unmeasured} errors=${s.errors.length} remaining=${c??"?"}`);for(let u of s.errors)console.log(` ${l.red(u.dataset_id)}: ${u.error}`);n.start("Sweeping datasets for recording stats...")}else n.text=`Sweeping datasets for recording stats... ${r.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...r,batches:i,remaining:o},null,2));else{if(console.log(),o===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(l.cyan(`Done in ${i} batch(es): processed=${r.processed} measured=${r.measured} unmeasured=${r.unmeasured} errors=${r.errors} remaining=${o??"unknown"}`))}if(r.errors>0||o===null)process.exit(1)});ke.addCommand(Ame);var Ome=new ve("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)");Ome.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(!he())return;if(e.reset){let s=S("Resetting signal-defaults sweep state...").start();try{let a=await poe();if(s.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){s.fail("Reset failed"),console.error(l.red(q(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,r={processed:0,populated:0,noData:0,errors:0},n=S("Sweeping datasets for signal defaults...").start(),{batches:i,remaining:o}=await uT(n,"Signal-defaults sweep failed",()=>foe({limit:t}),(s,a,c)=>{if(r.processed+=s.processed,r.populated+=s.populated,r.noData+=s.noData,r.errors+=s.errors.length,e.verbose){n.stop(),console.log(` [batch ${a}] processed=${s.processed} populated=${s.populated} no-data=${s.noData} errors=${s.errors.length} remaining=${c??"?"}`);for(let u of s.errors)console.log(` ${l.red(u.dataset_id)}: ${u.error}`);n.start("Sweeping datasets for signal defaults...")}else n.text=`Sweeping datasets for signal defaults... ${r.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...r,batches:i,remaining:o},null,2));else{if(console.log(),o===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(l.cyan(`Done in ${i} batch(es): processed=${r.processed} populated=${r.populated} no-data=${r.noData} errors=${r.errors} remaining=${o??"unknown"}`))}if(r.errors>0||o===null)process.exit(1)});ke.addCommand(Ome);async function Bft(e,t,r){let n=e(),i={processed:0,complete:0,incomplete:0,unknown:0,errors:0},o=0,s=null,a=null,c=!1;do{let u=await t(n);if(o++,i.processed+=u.processed,i.complete+=u.complete,i.incomplete+=u.incomplete,i.unknown+=u.unknown,i.errors+=u.errors.length,s=u.remaining,r?.onBatch?.(u,i,o),s!=null&&a!=null&&s>=a){c=!0;break}if(a=s,(s??0)>0)await r?.sleepBetweenBatches?.()}while((s??0)>0);return{batches:o,totals:i,remaining:s,stalled:c}}var Tme=new ve("data-integrity-sweep").description("Audit datasets against their version manifest and backfill data_complete / bytes_present (epic #967 Phase 3, #970)");Tme.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(!he())return;if(e.reset){let c=S("Resetting data-integrity sweep state...").start();try{let u=await hoe();if(c.succeed(`Cleared ${u.reset} audited row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(u,null,2))}catch(u){c.fail("Reset failed"),console.error(l.red(q(u))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,r=e.olderThan?Number.parseInt(e.olderThan,10):void 0,n=S("Sweeping datasets for data integrity...").start(),i;try{if(i=await Bft(()=>e.reaudit?new Date().toISOString():void 0,async(c)=>{let u=await moe({limit:t,olderThan:r,before:c});return{processed:u.processed,complete:u.complete,incomplete:u.incomplete,unknown:u.unknown,errors:u.errors,remaining:u.remaining}},{onBatch:(c,u,d)=>{if(e.verbose){n.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(` ${l.red(f.dataset_id)}: ${f.error}`);n.start("Sweeping datasets for data integrity...")}else n.text=`Sweeping datasets for data integrity... ${u.processed} processed, ${c.remaining??"?"} remaining`},sleepBetweenBatches:()=>qp(1000)}),i.stalled)n.warn(`No progress (remaining stuck at ${i.remaining}); stopping - see errors`);else n.stop()}catch(c){n.fail("Data-integrity sweep failed"),console.error(l.red(q(c))),process.exit(1)}let{batches:o,totals:s,remaining:a}=i;if(e.json)console.log(JSON.stringify({...s,batches:o,remaining:a},null,2));else{if(console.log(),a===null)console.log(l.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));if(console.log(l.cyan(`Done in ${o} batch(es): processed=${s.processed} complete=${s.complete} incomplete=${s.incomplete} unknown=${s.unknown} errors=${s.errors} remaining=${a??"unknown"}`)),s.incomplete>0)console.log(l.yellow(`${s.incomplete} dataset(s) verified incomplete -- see 'nemar dataset list --json' (data_complete=0) for details.`))}if(s.errors>0||a===null)process.exit(1)});ke.addCommand(Tme);var Pme=new ve("zarr-fidelity-sweep").description("Re-verify published Zarr stores against their dataset's own BIDS metadata (#1068)");Pme.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(!he())return;let t=Number.parseInt(e.limit??"25",10)||25,r=S("Verifying Zarr store fidelity...").start(),n;try{n=await Toe({limit:t}),r.stop()}catch(i){r.fail("Zarr fidelity sweep failed"),console.error(l.red(q(i))),process.exit(1);return}if(e.json)console.log(JSON.stringify(n,null,2));else{console.log(),console.log(l.cyan(`processed=${n.processed} verified=${n.verified} failed=${n.failed} unverifiable=${n.unverifiable} errors=${n.errors.length} remaining=${n.remaining??"unknown"}${n.budget_exhausted?" budget_exhausted=true":""}`));for(let i of n.results){let o=i.verdict==="verified"?l.green:i.verdict==="failed"?l.red:l.yellow;console.log(` ${o(i.verdict.padEnd(12))} ${i.dataset_id} (sampled=${i.sampled} checked=${i.checked})`);for(let s of i.examples)console.log(` ${l.red(s.code)}: ${s.path}`);if(i.examples_truncated)console.log(` ${l.dim(`(${i.mismatch_count} mismatches total; showing first ${i.examples.length})`)}`)}for(let i of n.errors)console.log(` ${l.red("error")} ${i.dataset_id}: ${i.error}`)}if(n.errors.length>0||n.remaining===null||n.budget_exhausted)process.exit(1)});ke.addCommand(Pme);var Uft=250,Ime=new ve("upstream-backfill").description("Record which upstream snapshot each mirrored version came from (dry run unless --execute)");Ime.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(!he())return;let t=Number.parseInt(e.limit??"25",10)||25,r=Number.parseInt(e.maxBatches??"200",10)||200,n=e.execute===!0,i=(m)=>{if(!e.json)console.log(m)};if(!n)i(l.yellow("Dry run: nothing is written. Pass --execute to record."));i(l.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 o={batches:0,scanned:0,recorded:{doi:0,unknown:0},not_examined:0,unparseable:0,absent:0,skipped_existing:0},s=[],a=e.after,c=null,u=null,d=!1;for(let m=0;m<r;m++){let h;try{h=await Poe({execute:n,limit:t,after:a})}catch(g){u=q(g);break}c=h,o.batches++,o.scanned+=h.scanned,o.recorded.doi+=h.recorded.doi,o.recorded.unknown+=h.recorded.unknown,o.not_examined+=h.not_examined,o.unparseable+=h.unparseable,o.absent+=h.absent,o.skipped_existing+=h.skipped_existing,s.push(...h.errors),i(`${l.cyan(`batch ${o.batches}`)} scanned=${h.scanned} ${n?"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)i(` ${l.dim("unknown")} ${g.dataset_id}@${g.version}: ${g.reason}`);for(let g of h.errors)i(` ${l.red("error")} ${g.dataset_id}@${g.version}: ${g.error}`);if(!h.ok){d=h.suspect_credential,u=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,Uft))}let f=u===null&&c!==null&&c.next_cursor===null,p=f?null:a??null;if(e.json)console.log(JSON.stringify({execute:n,done:f,failure:u,suspect_credential:d,...o,errors:s,next_cursor:p,counts:c?.counts??null},null,2));else{if(u)console.error(l.red(`Stopped: ${u}`));if(!f&&!u)console.log(l.yellow(`Stopped at --max-batches ${r}; the pass is not done.`));if(p)console.log(`Resume with: --after ${p}`);if(f&&o.not_examined>0)console.log(l.yellow(`${o.not_examined} row(s) were not examined and are still retryable: rerun without --after to try them again.`));if(c)console.log(l.cyan(`On versions now: doi=${c.counts.doi} lineage=${c.counts.lineage} unknown=${c.counts.unknown} not_examined=${c.counts.not_examined}`));if(!n)console.log(l.yellow("Dry run, pass --execute to record."))}if(u!==null||s.length>0||!f)process.exit(1)});ke.addCommand(Ime);var Nme=new ve("anonymity-sweep").description("Re-check anonymous deposits against the identity-leak inventory (#1409)");Nme.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(!he())return;if(e.reset){let i=S("Re-arming anonymous deposits...").start();try{let o=await Uoe();i.succeed(`Re-armed ${o.reset} anonymous deposit(s).`)}catch(o){i.fail("Reset failed"),console.error(l.red(q(o))),process.exit(1)}return}let t=Number.parseInt(e.limit??"10",10)||10,r=S("Checking anonymous deposits...").start(),n;try{n=await Boe({limit:t}),r.stop()}catch(i){r.fail("Anonymity sweep failed"),console.error(l.red(q(i))),process.exit(1);return}if(e.json)console.log(JSON.stringify(n,null,2));else{console.log(),console.log(l.cyan(`processed=${n.processed} verified=${n.verified} findings=${n.with_findings} unverifiable=${n.unverifiable} errors=${n.errors.length} mail_failures=${n.mail_failures.length} remaining=${n.remaining??"unknown"}${n.budget_exhausted?" budget_exhausted=true":""}`));for(let i of n.results){let o=i.status==="verified"?l.green:i.status==="findings"?l.red:l.yellow;console.log(` ${o(i.status.padEnd(13))} ${i.dataset_id} (files ${i.files_scanned}/${i.files_listed})`);for(let s of i.findings){let a=s.severity==="invariant"?l.red("NEMAR"):l.yellow("deposit");console.log(` ${a} ${s.check}: ${s.detail}`)}if(i.unchecked.length>0)console.log(` ${l.dim(`not checked: ${i.unchecked.join(", ")}`)}`)}for(let i of n.errors)console.log(` ${l.red("error")} ${i.dataset_id}: ${i.error}`);for(let i of n.mail_failures)console.log(` ${l.red("not mailed")} ${i.dataset_id} -> ${i.recipient}: ${i.error}`)}if(n.errors.length>0||n.mail_failures.length>0||n.remaining===null||n.budget_exhausted)process.exit(1)});ke.addCommand(Nme);var xD=new ve("doctor").description("Diagnose and heal stuck-dataset patterns (e.g. missing S3 version manifests)");function zft(e){let t=0;for(let[r,n]of Object.entries(e.results)){t+=n.count;let i=n.count>0?l.red(`${n.count} finding(s)`):l.green("clean");console.log(`${l.bold(r)}: ${i} \u2014 ${n.description}`);for(let o of n.findings)console.log(` ${o.dataset_id}${o.version?`@v${o.version}`:""}`)}return t}xD.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(!he())return;let r=S("Running doctor checks (read-only; a full-catalog scan can take ~1 minute)...").start();try{let n=await d2({check:t.check,datasetId:e});if(r.stop(),t.json){console.log(JSON.stringify(n,null,2));return}let i=zft(n);if(i>0)console.log(l.yellow(`
1218
1218
  ${i} finding(s). Preview the remediation with: nemar admin doctor fix <check> --dry-run`))}catch(n){r.fail("Doctor scan failed"),console.error(l.red(q(n))),process.exit(1)}});xD.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,r)=>{if(!he())return;if(r.dryRun){let c=S(`Listing ${e} findings (dry run)...`).start();try{let u=await f2({check:e,datasetId:t,dryRun:!0});if(c.stop(),r.json){console.log(JSON.stringify(u,null,2));return}console.log(`Would fix ${u.would_fix} finding(s) for ${l.bold(e)}:`);for(let d of u.findings)console.log(` ${d.dataset_id}${d.version?`@v${d.version}`:""}`)}catch(u){c.fail("Dry run failed"),console.error(l.red(q(u))),process.exit(1)}return}let n=S(`Scanning for ${e} findings...`).start(),i;try{i=(await d2({check:e,datasetId:t})).results[e]?.findings??[]}catch(c){n.fail("Doctor scan failed"),console.error(l.red(q(c))),process.exit(1);return}if(i.length===0){if(n.succeed(`${e}: nothing to fix`),r.json)console.log(JSON.stringify({check:e,total:0,results:[]},null,2));return}n.stop(),console.log(`${l.bold(e)}: ${i.length} finding(s) to fix`);let o=[...new Set(i.map((c)=>c.dataset_id))];n.start();let{totals:s,results:a}=await Vft(o,(c,u)=>{let d=i.filter((f)=>f.dataset_id===c&&f.version).map((f)=>`v${f.version}`).join(", ");return n.text=`Fixing ${c}${d?` (${d})`:""} [${u+1}/${o.length}]...`,f2({check:e,datasetId:c})},{onDataset:(c,u)=>{if(n.stop(),u.length===0)console.log(` resolved ${c}: healed between the scan and its fix turn`);for(let d of u){let f=`${d.dataset_id}${d.version?`@v${d.version}`:""}`;if(d.status==="fixed")console.log(` ${l.green("fixed")} ${f}`);else if(d.status==="skipped")console.log(` skipped ${f}: ${d.message??"already healthy"}`);else console.log(` ${l.red("FAILED")} ${f}: ${d.message??"unknown error"}`)}n.start()}});if(n.stop(),r.json)console.log(JSON.stringify({check:e,total:i.length,...s,results:a},null,2));else{let c=s.resolved>0?`, ${s.resolved} already resolved`:"";console.log(`
1219
1219
  ${l.bold(e)}: ${l.green(`${s.fixed} fixed`)}, ${s.skipped} skipped, ${s.failed>0?l.red(`${s.failed} failed`):"0 failed"}${c}`)}if(s.failed>0)process.exit(1)});async function Vft(e,t,r){let n={fixed:0,skipped:0,failed:0,resolved:0},i=[];for(let[o,s]of e.entries()){let a;try{let c=await t(s,o);if(a=c.results,a.length===0)n.resolved++;else n.fixed+=c.fixed,n.skipped+=c.skipped,n.failed+=c.failed}catch(c){n.failed++,a=[{dataset_id:s,status:"failed",message:q(c)}]}i.push(...a),r?.onDataset?.(s,a)}return{totals:n,results:i}}xD.command("kinds").description("Check that operational accounts carry their expected account kind (read-only)").action(async()=>{if(!he())return;let e=Object.entries(oV),t=S(`Checking ${e.length} operational account kind(s)...`).start(),r=[],n=[];try{for(let[i,o]of e)try{let{user:s}=await zie(i);if(s.account_kind!==o)r.push(`${i}: expected '${o}', found '${s.account_kind??"unknown"}'`)}catch(s){if(s instanceof M&&s.statusCode===404)n.push(i);else throw s}if(t.stop(),r.length===0&&n.length===0){console.log(l.green(`All ${e.length} operational account(s) carry their expected kind.`));return}for(let i of r)console.log(` ${l.yellow("kind mismatch")} ${i}`);for(let i of n)console.log(` ${l.yellow("account absent")} ${i}`);console.log(l.yellow(`
1220
1220
  ${r.length+n.length} finding(s). Fix a mismatch with \`nemar admin kind <username> <kind>\`.`))}catch(i){t.fail("Doctor kinds check failed"),console.error(l.red(q(i))),process.exit(1)}});ke.addCommand(xD);var dT=new ve("email-preferences").description("Manage email notification preferences");dT.command("show").description("Show email notification preferences").option("--user <username>","(owner only) show another user's preferences").action(async(e)=>{if(!tt())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);let t=S("Fetching email preferences...").start();try{let r=await Eoe(e.user),n=r.username?`${r.username}'s`:"Your";t.succeed(`${n} email notification preferences:`),console.log();let i=[{key:"user_approval",label:"User approval notifications"},{key:"publication_request",label:"Publication request notifications"},{key:"announcements",label:"Announcement emails"},{key:"dataset_anonymity",label:"Anonymity sweep findings"},{key:"identifier_sweep",label:"Identifier sweep weekly report"}];for(let o of i){let a=r[o.key]?l.green("enabled"):l.dim("disabled");console.log(` ${o.label.padEnd(40)} ${a}`)}console.log(),console.log(l.dim(" Use 'nemar admin email-preferences update' to change settings."))}catch(r){t.fail("Failed to fetch preferences"),console.error(l.red(q(r)))}});dT.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("--announcements <bool>","Enable/disable announcement emails").option("--dataset-anonymity <bool>","Enable/disable anonymity sweep findings").option("--identifier-sweep <bool>","Enable/disable the identifier sweep weekly report").option("--all <bool>","Enable/disable all notifications").option("--user <username>","(owner only) update another user's preferences").action(async(e)=>{if(!tt())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);function t(i){if(i===void 0)return;let o=i.toLowerCase();if(o==="true"||o==="1"||o==="on"||o==="yes")return!0;if(o==="false"||o==="0"||o==="off"||o==="no")return!1;console.error(l.red(`Invalid boolean value: "${i}". Use true/false, on/off, yes/no.`)),process.exit(1)}let r={};if(e.all!==void 0){let i=t(e.all);r.user_approval=i,r.publication_request=i,r.announcements=i,r.dataset_anonymity=i,r.identifier_sweep=i}else{let i=t(e.userApproval),o=t(e.publicationRequest),s=t(e.announcements),a=t(e.datasetAnonymity),c=t(e.identifierSweep);if(i===void 0&&o===void 0&&s===void 0&&a===void 0&&c===void 0)console.error(l.red("No preferences specified.")),console.log(" --user-approval <bool> User approval notifications"),console.log(" --publication-request <bool> Publication request notifications"),console.log(" --announcements <bool> Announcement emails"),console.log(" --dataset-anonymity <bool> Anonymity sweep findings"),console.log(" --identifier-sweep <bool> Identifier sweep weekly report"),console.log(" --all <bool> All notifications"),process.exit(1);if(i!==void 0)r.user_approval=i;if(o!==void 0)r.publication_request=o;if(s!==void 0)r.announcements=s;if(a!==void 0)r.dataset_anonymity=a;if(c!==void 0)r.identifier_sweep=c}let n=S("Updating email preferences...").start();try{let i=await Soe(r,e.user),o=i.username?`${i.username}'s`:"Your";n.succeed(`${o} email preferences updated:`),console.log(),console.log(` User approval: ${i.user_approval?l.green("enabled"):l.dim("disabled")}`),console.log(` Publication request: ${i.publication_request?l.green("enabled"):l.dim("disabled")}`),console.log(` Announcements: ${i.announcements?l.green("enabled"):l.dim("disabled")}`),console.log(` Anonymity findings: ${i.dataset_anonymity?l.green("enabled"):l.dim("disabled")}`),console.log(` Identifier sweep: ${i.identifier_sweep?l.green("enabled"):l.dim("disabled")}`)}catch(i){n.fail("Failed to update preferences"),console.error(l.red(q(i)))}});ke.addCommand(dT);var vD=new ve("notice").description("Manage system notices displayed to CLI users");vD.command("list").description("List all notices (including expired)").action(async()=>{if(!tt())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);let e=S("Fetching notices...").start();try{let{notices:t}=await lse();if(t.length===0){e.succeed("No notices found.");return}e.succeed(`${t.length} notice(s):`),console.log();for(let r of t){let i={critical:l.red.bold,warning:l.yellow,maintenance:l.magenta,announcement:l.green,tip:l.blue,info:l.blue}[r.level]||l.white,o=r.expires_at&&new Date(r.expires_at)<new Date?l.dim(" (expired)"):"";if(console.log(` ${l.dim(`#${r.id}`)} ${i(`[${r.level.toUpperCase()}]`)} ${l.dim(`scope:${r.scope}`)}${o}`),console.log(` ${r.message}`),console.log(` ${l.dim(`Created: ${r.created_at}`)}`),r.expires_at)console.log(` ${l.dim(`Expires: ${r.expires_at}`)}`);console.log()}}catch(t){wt(t,e,"Failed to fetch notices")}});vD.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(!tt())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(![...y2,"info"].includes(e.level))console.error(l.red(`Invalid level: ${e.level}. Use ${y2.join(", ")}.`)),process.exit(1);if(!["all","admins","members"].includes(e.scope))console.error(l.red(`Invalid scope: ${e.scope}. Use all, admins, or members.`)),process.exit(1);let t=S("Creating notice...").start();try{let r=await use({message:e.message,level:e.level,scope:e.scope,expires_at:e.expires});if(t.succeed(`Notice created (ID: ${r.id})`),console.log(` Level: ${r.level}`),console.log(` Scope: ${r.scope}`),console.log(` Message: ${r.message}`),r.expires_at)console.log(` Expires: ${r.expires_at}`)}catch(r){wt(r,t,"Failed to create notice")}});vD.command("clear <id>").description("Delete a notice by ID").option(qe,Ve).option(rt,Ze).action(async(e,t)=>{if(!tt())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);let r=Number.parseInt(e,10);if(Number.isNaN(r))console.error(l.red("Invalid notice ID")),process.exit(1);if(!await Ce(`Delete notice #${r}?`,t,!1))return;let i=S("Deleting notice...").start();try{await dse(r),i.succeed(`Notice #${r} deleted`)}catch(o){wt(o,i,"Failed to delete notice")}});ke.addCommand(vD);ke.command("notify").description("Send an email to a group or a single user").option("--to <group>","Recipient group: all, admins, members").option("--user <username>","Send to a single user by username").requiredOption("--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(qe,Ve).option(rt,Ze).action(async(e)=>{if(!tt())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.to&&e.user)console.error(l.red("--to and --user are mutually exclusive. Provide exactly one.")),process.exit(1);if(!e.to&&!e.user)console.error(l.red("Provide either --to <group> or --user <username>.")),process.exit(1);if(e.to&&!["all","admins","members"].includes(e.to))console.error(l.red(`Invalid group: ${e.to}. Use all, admins, or members.`)),process.exit(1);let t;if(e.bodyFile){if(!gD(e.bodyFile))console.error(l.red(`File not found: ${e.bodyFile}`)),process.exit(1);t=Aft(e.bodyFile,"utf-8")}else if(e.body)t=e.body;else console.error(l.red("Email body required. Use --body or --body-file.")),process.exit(1);let r=e.user?`user:${e.user}`:e.to,n=e.user?{user:e.user,subject:e.subject,body:t}:{to:e.to,subject:e.subject,body:t};if(e.dryRun){let a=S("Checking recipients...").start();try{let c=await u2({...n,dry_run:!0});if("dry_run"in c){a.succeed(`Dry run: ${c.recipient_count} recipient(s) for "${c.recipient_group}"`),console.log();for(let u of c.recipients)console.log(` ${u}`)}}catch(c){wt(c,a,"Failed to check recipients")}return}console.log(l.bold("Email preview:")),console.log(` To: ${l.cyan(r)}`),console.log(` Subject: ${e.subject}`),console.log(` Body: ${t.length>100?`${t.substring(0,100)}...`:t}`),console.log();let i=e.user?`Send this email to ${e.user}?`:"Send this broadcast email?";if(!await Ce(i,e,!1))return;let s=S(e.user?`Sending to ${e.user}...`:"Sending broadcast...").start();try{let a=await u2(n);if("broadcast_id"in a)if(a.failure_count>0){s.warn(`Email send: ${a.recipient_count} delivered, ${a.failure_count} failed`);for(let c of a.failed_recipients)console.log(l.red(` Failed: ${c}`))}else{let c=e.user?`Email sent to ${e.user}`:`Broadcast sent to ${a.recipient_count} recipient(s)`;s.succeed(`${c} (ID: ${a.broadcast_id})`)}}catch(a){wt(a,s,"Failed to send email")}});var Hft=1500;function Gft(e){switch(e.kind){case"ok":return l.green(`ok ${e.schema_version}`);case"stale":return l.yellow(`stale ${e.schema_version}`);case"missing":return l.red("missing");case"error":return l.red(`error ${e.status||"?"}: ${e.message}`)}}function Wft(e){return e.kind==="stale"||e.kind==="missing"}function Kft(e){let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}var Fme=new ve("summary").description("summary.json coverage across published dataset versions");Fme.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(qe,Ve).option(rt,Ze).action(async(e)=>{if(!he())return;let t=S("Building coverage report...").start(),r;try{r=await $oe()}catch(p){wt(p,t,"Failed to fetch coverage report");return}t.succeed(`Coverage: target=schema ${r.target_schema}, versions=${r.totals.versions}`);let n=r.versions,i=null;if(e.id){if(n=n.filter((p)=>p.dataset_id===e.id),i=`dataset_id=${e.id}`,n.length===0){console.log(l.yellow(`No rows for ${i}`));return}}else if(e.match){let p=Kft(e.match);if(n=n.filter((m)=>p.test(m.dataset_id)),i=`--match ${e.match}`,n.length===0){console.log(l.yellow(`No rows match ${i}`));return}console.log(l.dim(`Scoped to ${n.length} version(s) matching ${e.match}`))}if(e.json){console.log(JSON.stringify(i?{...r,versions:n,totals:fme(n)}:r,null,2));return}let o=e.onlyStale?n.filter((p)=>p.state.kind!=="ok"):n;if(o.length===0)console.log(l.green("All versions at target schema \u2014 no drift."));else{let p=Math.max(...o.map((h)=>h.dataset_id.length),10),m=Math.max(...o.map((h)=>h.version.length),7);for(let h of o)console.log(` ${h.dataset_id.padEnd(p)} ${h.version.padEnd(m)} ${Gft(h.state)}`)}let s=i?fme(n):r.totals;if(console.log(),console.log(` Total: ${s.versions} ${l.green(`ok=${s.ok}`)} ${l.yellow(`stale=${s.stale}`)} ${l.red(`missing=${s.missing}`)} ${l.red(`error=${s.error}`)}`),!e.fix){if(s.stale+s.missing>0)console.log(l.dim(`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nemar-cli",
3
3
  "packageManager": "bun@1.4.3",
4
- "version": "0.10.24-PR1920.3ae2b25",
4
+ "version": "0.10.24-PR1920.a9fae0a",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",