@oalo-ai/cli 0.8.0 → 0.9.1

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.
package/src/help.js CHANGED
@@ -221,6 +221,10 @@ export const COMMANDS = [
221
221
  { flag: "--types", desc: "push, CSV only: turn plain numbers, true/false and empty cells into numbers, booleans and null. Off by default so ids like 007 stay text." },
222
222
  { flag: "--from N", desc: "push: skip the first N records, to resume a push that stopped." },
223
223
  { flag: "--new-ids", desc: "push: let the server make ids for records without one. A re-send then adds copies." },
224
+ { flag: "--anonymize", desc: "push: anonymize PII columns locally before upload (default mode: pseudonymize)." },
225
+ { flag: "--anonymize-mode <mode>", desc: "push: client-side PII mode: pseudonymize (deterministic HMAC), mask, drop, or scrub (inline free text)." },
226
+ { flag: "--anonymize-fields <a,b>", desc: "push: comma-separated fields to anonymize (defaults to standard PII columns like email, phone, ssn, dob, address)." },
227
+ { flag: "--salt-file <path>", desc: "push: local HMAC salt file for deterministic pseudonymize joins (default ~/.oalo/anonymize.salt, mode 0600)." },
224
228
  { flag: "--dry-run", desc: "push: parse, check the model exists, show the first row, write nothing." },
225
229
  { flag: "--fields a,b", desc: "vectorize: the fields (a model's) or columns (a plain table's) whose text bots search. Turns it on, and embeds the existing rows." },
226
230
  { flag: "--where <filter>", desc: "vectorize, models only: embed only matching rows. `status in active,draft`, `status not in archived`, `status = active`, `status != archived`, `cover present`, `cover absent`." },
@@ -930,18 +934,101 @@ export const COMMANDS = [
930
934
  },
931
935
  {
932
936
  name: "crm",
933
- summary: "Bulk-import CRM contacts from a CSV file with email/phone deduplication and optional tags.",
934
- usage: ["oalo crm import <file.csv> [--tags a,b] [--dry-run] [--json]"],
937
+ summary: "Bulk-import CRM contacts from a CSV file with email/phone deduplication, optional client-side PII anonymization, and tags.",
938
+ usage: ["oalo crm import <file.csv> [--tags a,b] [--anonymize] [--anonymize-mode pseudonymize|mask|drop|scrub] [--anonymize-fields a,b] [--salt-file <path>] [--dry-run] [--json]"],
935
939
  flags: [
936
940
  { flag: "--tags <a,b>", desc: "Comma-separated tags to apply to every imported contact." },
941
+ { flag: "--anonymize", desc: "Anonymize PII columns locally before upload (default mode: pseudonymize)." },
942
+ { flag: "--anonymize-mode <mode>", desc: "Client-side PII mode: pseudonymize (deterministic HMAC), mask, drop, or scrub (inline free text)." },
943
+ { flag: "--anonymize-fields <a,b>", desc: "Comma-separated fields to anonymize (defaults to standard PII columns like email, phone, ssn, dob, address)." },
944
+ { flag: "--salt-file <path>", desc: "Local HMAC salt file for deterministic pseudonymize joins (default ~/.oalo/anonymize.salt, mode 0600)." },
937
945
  { flag: "--dry-run", desc: "Parse the CSV locally and preview the first 5 rows without writing." },
938
946
  { flag: "--json", desc: "Print JSON output." },
939
947
  ],
940
948
  notes: [
941
949
  "Reads standard CSV headers (`email`, `phone`, `name`, `first_name`, `last_name`, `tags`, `company`, etc.) and upserts via `crm:import_contacts`, deduplicating by email/phone/external_ref.",
950
+ "With `--anonymize`, transformations happen in memory on your machine before any row is uploaded to Oalo.",
942
951
  ],
943
952
  exits: { 0: "done", 1: "refused or failed", 2: "bad arguments, unreadable file, or no CLI token" },
944
953
  },
954
+ {
955
+ name: "privacy",
956
+ summary: "View or set the workspace Privacy Mode (standard, zdr, local_only) and LLM-boundary PII Vault scrubbing.",
957
+ usage: [
958
+ "oalo privacy [--json]",
959
+ "oalo privacy set --mode standard|zdr|local_only [--scrub-pii on|off] [--cloud-embeddings on|off] [--cloud-jobs on|off] [--json]",
960
+ ],
961
+ flags: [
962
+ { flag: "--mode <mode>", desc: "set: workspace privacy tier: standard, zdr (Zero Data Retention: Bedrock and local byo-* only), or local_only (only local byo-* models, no cloud embeddings or cloud background jobs)." },
963
+ { flag: "--scrub-pii <on|off>", desc: "set: deterministically replace SSNs, Luhn credit cards, emails, phones, and IPv4 addresses with tokens before hosted LLM calls." },
964
+ { flag: "--cloud-embeddings <on|off>", desc: "set: allow or disable cloud embeddings (always off in local_only mode)." },
965
+ { flag: "--cloud-jobs <on|off>", desc: "set: allow or disable cloud background LLM jobs such as Whisper transcription and summaries (always off in local_only mode)." },
966
+ { flag: "--json", desc: "Print JSON output." },
967
+ ],
968
+ notes: [
969
+ "Workspace admins can change the policy; all members can inspect it.",
970
+ "Calls inherit the workspace privacy mode and can only raise privacy (never downgrade a zdr or local_only workspace).",
971
+ "For client-side anonymization before import, pass `--anonymize` to `oalo data push` or `oalo crm import`.",
972
+ ],
973
+ exits: { 0: "done", 1: "refused or failed", 2: "bad arguments or no CLI token" },
974
+ },
975
+ {
976
+ name: "calls",
977
+ summary: "Manage Oalo Calls (1-on-1 video rooms, live classes, and Forthwith sessions): list, inspect, share recordings, and verify SHA-256 notarization.",
978
+ usage: [
979
+ "oalo calls list [--kind external|one_on_one|live_class] [--status live|ended] [--json]",
980
+ "oalo calls show <call-id> [--json]",
981
+ "oalo calls share <call-id> --on | --off [--json]",
982
+ "oalo calls verify <call-id> [--json]",
983
+ ],
984
+ flags: [
985
+ { flag: "--kind <kind>", desc: "list: filter by call kind (external, one_on_one, live_class)." },
986
+ { flag: "--status <status>", desc: "list: filter by status (live, ended)." },
987
+ { flag: "--on", desc: "share: allow verified call participants to view the recording and notarized transcript." },
988
+ { flag: "--off", desc: "share: restrict the recording and transcript to the host only." },
989
+ { flag: "--json", desc: "Print JSON output." },
990
+ ],
991
+ notes: [
992
+ "Oalo Calls is the video room, recording, and SHA-256 notarization platform. For the live real-time assistant on external Zoom, Meet, or Teams calls, run `oalo forthwith`.",
993
+ "Note: `oalo call` (singular) calls a raw Base event; `oalo calls` (plural) manages video and external calls.",
994
+ ],
995
+ exits: { 0: "done", 1: "failed or verification mismatch", 2: "bad arguments or no CLI token" },
996
+ },
997
+ {
998
+ name: "forthwith",
999
+ summary: "Forthwith: Oalo's real-time call assistant for Zoom, Meet, Teams, or phone calls with Pre-Call Dossier, private whispers, and SHA-256 notarization.",
1000
+ usage: [
1001
+ "oalo forthwith start [--title <text>] [--contact <ref>] [--booking <id>] [--privacy standard|zdr|local_only] [--local] [--offline] [--stt-cmd <cmd>] [--speaker <name>] [--scrub-pii] [--no-telemetry] [--out <file>] [--json]",
1002
+ "oalo forthwith list [--kind external|one_on_one|live_class] [--status live|ended] [--json]",
1003
+ "oalo forthwith show <call-id> [--json]",
1004
+ "oalo forthwith share <call-id> --on | --off [--json]",
1005
+ "oalo forthwith verify <call-id> [--json]",
1006
+ ],
1007
+ flags: [
1008
+ { flag: "--title <text>", desc: "start: call title (default: External call)." },
1009
+ { flag: "--contact <ref>", desc: "start: contact email, phone, or external ref to preload into the minute-0 Pre-Call Dossier." },
1010
+ { flag: "--booking <id>", desc: "start: link the call to a calendar booking id." },
1011
+ { flag: "--privacy <mode>", desc: "start: call privacy tier (standard, zdr, local_only); cannot downgrade workspace policy." },
1012
+ { flag: "--local", desc: "start: shorthand for --privacy local_only (keeps AI evaluation on local byo-* models)." },
1013
+ { flag: "--offline", desc: "start: strictly local zero-egress capture with local SHA-256 notarization and no network calls." },
1014
+ { flag: "--stt-cmd <cmd>", desc: "start: local speech-to-text command whose stdout lines stream as live transcript turns (for example local whisper-stream)." },
1015
+ { flag: "--speaker <name>", desc: "start: default speaker label for stdin or STT lines without a `Name: text` prefix." },
1016
+ { flag: "--scrub-pii", desc: "start: scrub SSNs, Luhn cards, emails, phones, and IPs locally before sending transcript lines." },
1017
+ { flag: "--no-telemetry", desc: "Disable CLI update notices and telemetry (same as OALO_NO_TELEMETRY=1)." },
1018
+ { flag: "--out <file>", desc: "start with --offline: save the locally notarized transcript JSON file (mode 0600)." },
1019
+ { flag: "--kind <kind>", desc: "list: filter by call kind (external, one_on_one, live_class)." },
1020
+ { flag: "--status <status>", desc: "list: filter by status (live, ended)." },
1021
+ { flag: "--on", desc: "share: allow verified call participants to view the recording and notarized transcript." },
1022
+ { flag: "--off", desc: "share: restrict the recording and transcript to the host only." },
1023
+ { flag: "--json", desc: "Print JSON (or NDJSON event stream during start)." },
1024
+ ],
1025
+ notes: [
1026
+ "During a live session, type `/ask <question>` for an instant private whisper card, `/share <title> | <content> [| <url>]` to push an attendee card, `/brief` to re-print the Pre-Call Dossier, or `/end` to finish and notarize the call.",
1027
+ "Lines prefixed with `Name: utterance` automatically tag the speaker; other lines use `--speaker`.",
1028
+ "Use `--offline --scrub-pii --no-telemetry` for zero-egress local transcription and local SHA-256 notarization.",
1029
+ ],
1030
+ exits: { 0: "done", 1: "failed or verification mismatch", 2: "bad arguments or no CLI token" },
1031
+ },
945
1032
  {
946
1033
  name: "flows",
947
1034
  summary: "Turn a chat flow on or off, or delete it, by bot and flow name, without pulling and pushing it.",
@@ -1317,6 +1404,7 @@ export const ENV_VARS = [
1317
1404
  { name: "OALO_HOME", desc: "Relocate the credential store (CI, containers, tests)." },
1318
1405
  { name: "OALO_AGENT_HARNESS", desc: "Default headless agent harness for coord up, ralph, race, review, swarm, auto." },
1319
1406
  { name: "OALO_DEBUG", desc: "Log channel transport activity to stderr." },
1407
+ { name: "OALO_NO_TELEMETRY", desc: "Set to 1 to suppress CLI update notices and telemetry." },
1320
1408
  { name: "NO_COLOR", desc: "Disable colour in tail output." },
1321
1409
  ];
1322
1410
 
package/src/index.js CHANGED
@@ -41,6 +41,9 @@ import { serve } from "./commands/serve.js";
41
41
  import { usage } from "./commands/usage.js";
42
42
  import { inbox } from "./commands/inbox.js";
43
43
  import { crm } from "./commands/crm.js";
44
+ import { privacy } from "./commands/privacy.js";
45
+ import { calls } from "./commands/calls.js";
46
+ import { forthwith } from "./commands/forthwith.js";
44
47
  import { ralph } from "./commands/ralph.js";
45
48
  import { race } from "./commands/race.js";
46
49
  import { review } from "./commands/review.js";
@@ -89,10 +92,13 @@ if ((flags.version || cmd === "version") && !flags.help) {
89
92
  } else if (!COMMANDS.some((c) => c.name === cmd)) {
90
93
  finish(`unknown command: ${cmd}\n\n${overview()}`, 2, process.stderr);
91
94
  } else {
95
+ if (flags["no-telemetry"]) process.env.OALO_NO_TELEMETRY = "1";
96
+
92
97
  // A project whose installed skill is from another CLI version hears about
93
98
  // it once (stderr, so piped output and --json stay clean). Not under mcp,
94
- // whose stdio is the protocol, nor where the skill is being written.
95
- if (cmd && !["mcp", "skill", "link", "help"].includes(cmd)) {
99
+ // whose stdio is the protocol, nor where the skill is being written, nor
100
+ // when OALO_NO_TELEMETRY=1 is set.
101
+ if (cmd && !["mcp", "skill", "link", "help"].includes(cmd) && process.env.OALO_NO_TELEMETRY !== "1") {
96
102
  try {
97
103
  const notice = skillNotice();
98
104
  if (notice) console.error(dim(notice));
@@ -208,6 +214,15 @@ async function dispatch(cmd) {
208
214
  case "crm":
209
215
  await crm(flags, rest);
210
216
  break;
217
+ case "privacy":
218
+ await privacy(flags, rest);
219
+ break;
220
+ case "calls":
221
+ await calls(flags, rest);
222
+ break;
223
+ case "forthwith":
224
+ await forthwith(flags, rest);
225
+ break;
211
226
  case "ralph":
212
227
  await ralph(flags, rest);
213
228
  break;
@@ -0,0 +1,321 @@
1
+ import { createHmac, randomBytes } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+
6
+ /**
7
+ * Client-side PII anonymization and free-text scrubbing.
8
+ *
9
+ * Everything here runs locally in the CLI process BEFORE any record or
10
+ * transcript line leaves the user's machine.
11
+ *
12
+ * Modes:
13
+ * - pseudonymize (default): deterministic HMAC-SHA256 replacement using a
14
+ * local salt file (0600) so cross-table joins stay intact without raw PII.
15
+ * - mask: shape-preserving redaction (e.g. a***@clinic.org, ***-***-5309).
16
+ * - drop: remove matching PII columns completely before upload.
17
+ * - scrub: redact inline PII (SSN, Luhn credit cards, emails, phones, IPv4)
18
+ * inside free-text fields while leaving structure intact.
19
+ */
20
+
21
+ export const VALID_MODES = ["pseudonymize", "mask", "drop", "scrub"];
22
+
23
+ export const DEFAULT_PII_FIELDS = new Set([
24
+ "email",
25
+ "email_address",
26
+ "phone",
27
+ "phone_number",
28
+ "mobile",
29
+ "ssn",
30
+ "social_security",
31
+ "social_security_number",
32
+ "dob",
33
+ "date_of_birth",
34
+ "birth_date",
35
+ "address",
36
+ "street",
37
+ "street_address",
38
+ "postal_code",
39
+ "zip",
40
+ "zip_code",
41
+ "ip",
42
+ "ip_address",
43
+ "card_number",
44
+ "credit_card",
45
+ "tax_id",
46
+ "tin",
47
+ "ein",
48
+ "national_id",
49
+ "passport",
50
+ "drivers_license",
51
+ ]);
52
+
53
+ const EMAIL_RE = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
54
+ const SSN_RE = /\b\d{3}-\d{2}-\d{4}\b/g;
55
+ const CARD_RE = /\b(?:\d[ -]*?){13,19}\b/g;
56
+ const PHONE_RE = /(?<!\w)(?:\+?\d{1,3}[\s.-]?)?(?:\(\d{3}\)|\d{3})[\s.-]\d{3}[\s.-]\d{4}(?!\w)/g;
57
+ const IPV4_RE = /\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/g;
58
+
59
+ /** Standard Luhn checksum validation for credit card numbers. */
60
+ export function isLuhnValid(input) {
61
+ const digits = String(input || "").replace(/\D/g, "");
62
+ if (digits.length < 13 || digits.length > 19) return false;
63
+ let sum = 0;
64
+ let alt = false;
65
+ for (let i = digits.length - 1; i >= 0; i--) {
66
+ let n = digits.charCodeAt(i) - 48;
67
+ if (alt) {
68
+ n *= 2;
69
+ if (n > 9) n -= 9;
70
+ }
71
+ sum += n;
72
+ alt = !alt;
73
+ }
74
+ return sum % 10 === 0;
75
+ }
76
+
77
+ /**
78
+ * Deterministically scrub inline PII spans from free text.
79
+ * Passing the same `vault` across lines keeps token assignments consistent
80
+ * (`[EMAIL_1]` stays `[EMAIL_1]` for the whole call or import).
81
+ */
82
+ export function scrubText(text, vault = null) {
83
+ if (typeof text !== "string" || !text) {
84
+ return { text: text ?? "", vault: vault || createVault(), replacements: 0 };
85
+ }
86
+
87
+ const v = vault || createVault();
88
+ let replacements = 0;
89
+
90
+ const tokenFor = (prefix, raw) => {
91
+ const key = `${prefix}:${raw}`;
92
+ if (v.reverse.has(key)) return v.reverse.get(key);
93
+ const n = (v.counts[prefix] || 0) + 1;
94
+ v.counts[prefix] = n;
95
+ const tok = `[${prefix}_${n}]`;
96
+ v.reverse.set(key, tok);
97
+ v.tokens[tok] = raw;
98
+ return tok;
99
+ };
100
+
101
+ let out = text;
102
+
103
+ // 1. SSNs first (narrow pattern)
104
+ out = out.replace(SSN_RE, (m) => {
105
+ replacements++;
106
+ return tokenFor("SSN", m);
107
+ });
108
+
109
+ // 2. Credit cards (Luhn-validated to avoid redacting order IDs)
110
+ out = out.replace(CARD_RE, (m) => {
111
+ if (!isLuhnValid(m)) return m;
112
+ replacements++;
113
+ return tokenFor("CARD", m);
114
+ });
115
+
116
+ // 3. Emails
117
+ out = out.replace(EMAIL_RE, (m) => {
118
+ replacements++;
119
+ return tokenFor("EMAIL", m);
120
+ });
121
+
122
+ // 4. Phone numbers
123
+ out = out.replace(PHONE_RE, (m) => {
124
+ replacements++;
125
+ return tokenFor("PHONE", m);
126
+ });
127
+
128
+ // 5. IPv4 addresses
129
+ out = out.replace(IPV4_RE, (m) => {
130
+ replacements++;
131
+ return tokenFor("IP", m);
132
+ });
133
+
134
+ return { text: out, vault: v, replacements };
135
+ }
136
+
137
+ export function createVault() {
138
+ return { tokens: {}, reverse: new Map(), counts: {} };
139
+ }
140
+
141
+ /** Restore scrubbed tokens back into original text using a local vault. */
142
+ export function rehydrateText(text, vault) {
143
+ if (typeof text !== "string" || !vault?.tokens) return text;
144
+ let out = text;
145
+ for (const [tok, raw] of Object.entries(vault.tokens)) {
146
+ out = out.split(tok).join(raw);
147
+ }
148
+ return out;
149
+ }
150
+
151
+ /** Default path for the local-only anonymization HMAC salt. */
152
+ export function defaultSaltPath() {
153
+ const base = process.env.OALO_HOME || join(homedir(), ".oalo");
154
+ return join(base, "anonymize.salt");
155
+ }
156
+
157
+ /**
158
+ * Load an existing local HMAC salt, or generate a fresh 32-byte random salt
159
+ * with mode 0600 on disk. The salt never leaves the local machine.
160
+ */
161
+ export function loadOrCreateSalt(saltFile) {
162
+ const p = saltFile || defaultSaltPath();
163
+ if (existsSync(p)) {
164
+ const val = readFileSync(p, "utf8").trim();
165
+ if (val) return { salt: val, path: p, created: false };
166
+ }
167
+ mkdirSync(dirname(p), { recursive: true });
168
+ const salt = randomBytes(32).toString("hex");
169
+ writeFileSync(p, salt + "\n", { mode: 0o600 });
170
+ return { salt, path: p, created: true };
171
+ }
172
+
173
+ /** Deterministic HMAC-SHA256 pseudonym preserving email/phone shape when applicable. */
174
+ export function pseudonymizeValue(value, field, salt) {
175
+ if (value === null || value === undefined || value === "") return value;
176
+ const raw = String(value).trim();
177
+ const normalized = raw.toLowerCase();
178
+ const fieldKey = String(field || "").toLowerCase();
179
+ const digest = createHmac("sha256", salt).update(`${fieldKey}:${normalized}`).digest("hex").slice(0, 12);
180
+
181
+ if (fieldKey.includes("email") || raw.includes("@")) {
182
+ return `anon_${digest}@redacted.local`;
183
+ }
184
+ if (fieldKey.includes("phone") || fieldKey.includes("mobile")) {
185
+ return `phone_${digest}`;
186
+ }
187
+ return `anon_${digest}`;
188
+ }
189
+
190
+ /** Shape-preserving partial mask (irreversible). */
191
+ export function maskValue(value, field) {
192
+ if (value === null || value === undefined || value === "") return value;
193
+ const raw = String(value).trim();
194
+ const fieldKey = String(field || "").toLowerCase();
195
+
196
+ if (fieldKey.includes("email") || raw.includes("@")) {
197
+ const [local, domain] = raw.split("@");
198
+ if (domain) {
199
+ const head = local.length > 0 ? local[0] : "";
200
+ return `${head}***@${domain}`;
201
+ }
202
+ }
203
+ if (fieldKey.includes("phone") || fieldKey.includes("mobile")) {
204
+ const digits = raw.replace(/\D/g, "");
205
+ if (digits.length >= 4) return `***-***-${digits.slice(-4)}`;
206
+ }
207
+ if (raw.length <= 4) return "***";
208
+ return `***${raw.slice(-4)}`;
209
+ }
210
+
211
+ /**
212
+ * Anonymize an array of plain row objects in memory before upload.
213
+ * Supports flat records (`oalo crm import`) and `{ id, document }` rows (`oalo data push`).
214
+ */
215
+ export function anonymizeRows(rows, opts = {}) {
216
+ const mode = opts.mode || "pseudonymize";
217
+ if (!VALID_MODES.includes(mode)) {
218
+ throw new Error(`--anonymize-mode must be one of ${VALID_MODES.join(", ")} (got ${mode})`);
219
+ }
220
+
221
+ const explicitFields =
222
+ Array.isArray(opts.fields) && opts.fields.length > 0
223
+ ? new Set(opts.fields.map((f) => String(f).trim().toLowerCase()).filter(Boolean))
224
+ : null;
225
+
226
+ const salt = mode === "pseudonymize" ? opts.salt || loadOrCreateSalt(opts.saltFile).salt : null;
227
+ const vault = createVault();
228
+ const fieldsTouched = new Set();
229
+ let valuesTransformed = 0;
230
+
231
+ const shouldTransformKey = (key) => {
232
+ const k = key.toLowerCase();
233
+ if (explicitFields) return explicitFields.has(k);
234
+ return DEFAULT_PII_FIELDS.has(k);
235
+ };
236
+
237
+ const transformObj = (obj) => {
238
+ const next = {};
239
+ for (const [k, v] of Object.entries(obj)) {
240
+ if (mode === "scrub") {
241
+ const target = !explicitFields || explicitFields.has(k.toLowerCase());
242
+ if (target && typeof v === "string") {
243
+ const { text, replacements } = scrubText(v, vault);
244
+ if (replacements > 0) {
245
+ fieldsTouched.add(k);
246
+ valuesTransformed += replacements;
247
+ }
248
+ next[k] = text;
249
+ } else {
250
+ next[k] = v;
251
+ }
252
+ continue;
253
+ }
254
+
255
+ if (!shouldTransformKey(k)) {
256
+ next[k] = v;
257
+ continue;
258
+ }
259
+
260
+ if (mode === "drop") {
261
+ fieldsTouched.add(k);
262
+ valuesTransformed++;
263
+ continue;
264
+ }
265
+
266
+ if (mode === "mask") {
267
+ fieldsTouched.add(k);
268
+ valuesTransformed++;
269
+ next[k] = maskValue(v, k);
270
+ continue;
271
+ }
272
+
273
+ // pseudonymize
274
+ fieldsTouched.add(k);
275
+ valuesTransformed++;
276
+ next[k] = pseudonymizeValue(v, k, salt);
277
+ }
278
+ return next;
279
+ };
280
+
281
+ const out = rows.map((row) => {
282
+ if (row && typeof row === "object" && row.document && typeof row.document === "object" && "id" in row) {
283
+ return { ...row, document: transformObj(row.document) };
284
+ }
285
+ return transformObj(row);
286
+ });
287
+
288
+ return {
289
+ rows: out,
290
+ stats: {
291
+ mode,
292
+ rowsProcessed: out.length,
293
+ fieldsTouched: [...fieldsTouched].sort(),
294
+ valuesTransformed,
295
+ },
296
+ };
297
+ }
298
+
299
+ /** Parse `--anonymize`, `--anonymize-mode`, `--anonymize-fields`, `--salt-file` from CLI flags. */
300
+ export function parseAnonymizeFlags(flags) {
301
+ const enabled =
302
+ !!flags.anonymize ||
303
+ typeof flags["anonymize-mode"] === "string" ||
304
+ typeof flags["anonymize-fields"] === "string";
305
+
306
+ if (!enabled) return null;
307
+
308
+ const mode = typeof flags["anonymize-mode"] === "string" ? flags["anonymize-mode"].trim().toLowerCase() : "pseudonymize";
309
+ if (!VALID_MODES.includes(mode)) {
310
+ throw new Error(`--anonymize-mode must be one of ${VALID_MODES.join(", ")} (got ${mode})`);
311
+ }
312
+
313
+ const fields =
314
+ typeof flags["anonymize-fields"] === "string"
315
+ ? flags["anonymize-fields"].split(",").map((s) => s.trim()).filter(Boolean)
316
+ : [];
317
+
318
+ const saltFile = typeof flags["salt-file"] === "string" ? flags["salt-file"] : undefined;
319
+
320
+ return { mode, fields, saltFile };
321
+ }