maximem-synap-cli 0.3.5__py3-none-any.whl

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.
@@ -0,0 +1,677 @@
1
+ """`maximem-synap privacy ...` — the sensitive-data controls.
2
+
3
+ Read the policy, change it, approve it, see what is actually being protected,
4
+ and read the audit trail. Backed by `/api/v1/management/privacy/*`, which is the
5
+ same code the dashboard's Sensitive Data page runs.
6
+
7
+ Two things about this surface are worth knowing before using it:
8
+
9
+ - **Saving is not turning on.** `policy set` writes a draft and changes nothing.
10
+ `policy approve` is the only command that makes a policy live. That is the
11
+ server's design, not a CLI convention, and the commands say so as they go.
12
+ - **`preset standard` protects no identity.** It leaves raw identity and contact
13
+ info as "not sensitive", so names, dates of birth and phone numbers are
14
+ detected and never aliased. Only `regulated` protects them. `preset` prints
15
+ what a preset does before applying it, because picking it from a name is how
16
+ people end up with a policy that reads as protective and is not.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from pathlib import Path
22
+ from typing import Dict, List, Optional
23
+
24
+ import typer
25
+
26
+ from synap.cli import interactive, render
27
+ from synap.cli.api import CliError
28
+ from synap.cli.validate import json_object, one_of
29
+
30
+ app = typer.Typer(no_args_is_help=True)
31
+ policy_app = typer.Typer(no_args_is_help=True)
32
+ field_types_app = typer.Typer(no_args_is_help=True)
33
+ suggestions_app = typer.Typer(no_args_is_help=True)
34
+ activity_app = typer.Typer(no_args_is_help=True)
35
+ app.add_typer(policy_app, name="policy", help="Read, edit and approve the policy.")
36
+ app.add_typer(field_types_app, name="field-types", help="The things we can find.")
37
+ app.add_typer(suggestions_app, name="suggestions", help="Field types you have not decided about.")
38
+ app.add_typer(activity_app, name="activity", help="The audit trail.")
39
+
40
+ # Mirrors synap/cloud/privacy/policy.py. Client-side only so a typo fails
41
+ # instantly with the list, instead of coming back as a 400 from the server.
42
+ _SETTINGS = (
43
+ "not_sensitive",
44
+ "hide_from_model",
45
+ "protect_at_rest",
46
+ "protect_fully",
47
+ "never_store",
48
+ "client_vault",
49
+ )
50
+ _PRESETS = ("minimal", "standard", "regulated", "store_nothing")
51
+ _GRANTS = ("full", "masked", "none")
52
+ _OUTCOMES = ("protect", "ignore", "undecided")
53
+
54
+
55
+ def _pairs(values: Optional[List[str]], *, flag: str) -> Dict[str, str]:
56
+ """Parse repeated ``key=value`` options into a dict."""
57
+ out: Dict[str, str] = {}
58
+ for raw in values or []:
59
+ key, sep, value = raw.partition("=")
60
+ if not sep or not key.strip() or not value.strip():
61
+ raise CliError(f"{flag} must look like key=value (got '{raw}').")
62
+ out[key.strip()] = value.strip()
63
+ return out
64
+
65
+
66
+ def _scope_params(instance: Optional[str]) -> dict:
67
+ return {"instance_id": instance} if instance else {}
68
+
69
+
70
+ # ── Policy ───────────────────────────────────────────────────────────────────
71
+
72
+ _CATEGORY_COLUMNS = [
73
+ ("category", "CATEGORY"),
74
+ ("live", "LIVE"),
75
+ ("draft", "DRAFT"),
76
+ ("detectable", "DETECTABLE"),
77
+ ]
78
+
79
+
80
+ @policy_app.command(name="get")
81
+ def policy_get(
82
+ ctx: typer.Context,
83
+ instance: Optional[str] = typer.Option(
84
+ None, "--instance", "-i", help="Read one instance's policy (default: the account).",
85
+ ),
86
+ ) -> None:
87
+ """Show the live policy, any waiting draft, and what each category covers."""
88
+ resp = ctx.obj.client().get("/privacy/policy", params=_scope_params(instance))
89
+ if render.is_json():
90
+ render.print_json(resp)
91
+ return
92
+
93
+ live = resp.get("live") or {}
94
+ draft = resp.get("draft")
95
+ coverage = {c.get("key"): c for c in (resp.get("categories") or [])}
96
+ live_cats = live.get("categories") or {}
97
+ draft_cats = (draft or {}).get("categories") or {}
98
+
99
+ rows = []
100
+ for key in sorted(set(live_cats) | set(draft_cats) | set(coverage)):
101
+ drafted = draft_cats.get(key)
102
+ rows.append({
103
+ "category": coverage.get(key, {}).get("label") or key,
104
+ "live": live_cats.get(key, "—"),
105
+ # Only show a draft value where it differs, so a draft that changes
106
+ # one row does not look like a draft that changed everything.
107
+ "draft": drafted if drafted and drafted != live_cats.get(key) else "",
108
+ "detectable": coverage.get(key, {}).get("how") or "",
109
+ })
110
+ render.print_table(rows, _CATEGORY_COLUMNS, title="Categories")
111
+
112
+ scope = resp.get("scope") or {}
113
+ header = {
114
+ "scope": "account" if scope.get("is_account") else scope.get("instance_id"),
115
+ "version": live.get("version"),
116
+ "approved": live.get("approved"),
117
+ "approved_by": live.get("approved_by"),
118
+ "approved_at": live.get("approved_at"),
119
+ "is_configured": live.get("is_configured"),
120
+ }
121
+ if scope.get("inherits_account"):
122
+ header["inherits_account"] = True
123
+ render.print_detail(header, title="Live policy")
124
+
125
+ if draft:
126
+ render.warn(
127
+ f"A draft (version {draft.get('version')}) is waiting and is not in "
128
+ f"effect. Run `maximem-synap privacy policy approve` to make it live."
129
+ )
130
+ if not live.get("is_configured"):
131
+ render.warn("Nothing is configured yet, so nothing is being protected.")
132
+
133
+
134
+ @policy_app.command(name="set")
135
+ def policy_set(
136
+ ctx: typer.Context,
137
+ category: Optional[List[str]] = typer.Option(
138
+ None, "--set", "-s", metavar="CATEGORY=SETTING",
139
+ help=f"Repeatable. SETTING is one of: {' | '.join(_SETTINGS)}.",
140
+ ),
141
+ exception: Optional[List[str]] = typer.Option(
142
+ None, "--exception", "-e", metavar="FIELD_TYPE=SETTING",
143
+ help="Repeatable. Override one field type against its category.",
144
+ ),
145
+ from_file: Optional[str] = typer.Option(
146
+ None, "--from-file",
147
+ help="Send a whole policy body as JSON, replacing everything. Skips the merge.",
148
+ ),
149
+ instance: Optional[str] = typer.Option(None, "--instance", "-i"),
150
+ ) -> None:
151
+ """Save a draft. This never turns anything on; `policy approve` does that.
152
+
153
+ Changes are merged onto what is already there. The server's PUT replaces the
154
+ whole category map, so sending one changed row on its own would silently
155
+ reset the other ten to the default: this reads the current policy first and
156
+ sends it back with your edits applied. `--from-file` is the escape hatch that
157
+ sends exactly what you give it.
158
+ """
159
+ cc = ctx.obj
160
+ client = cc.client()
161
+ params = _scope_params(instance)
162
+
163
+ if from_file is not None:
164
+ if category or exception:
165
+ raise CliError("--from-file cannot be combined with --set/--exception.")
166
+ path = Path(from_file)
167
+ if not path.is_file():
168
+ raise CliError(f"--from-file: no such file '{from_file}'.")
169
+ body = json_object(path.read_text(encoding="utf-8"), flag="--from-file")
170
+ else:
171
+ wanted = _pairs(category, flag="--set")
172
+ wanted_exceptions = _pairs(exception, flag="--exception")
173
+ if not wanted and not wanted_exceptions:
174
+ raise CliError(
175
+ "Nothing to change. Pass --set CATEGORY=SETTING, --exception "
176
+ "FIELD_TYPE=SETTING, or --from-file."
177
+ )
178
+ for flag, values in (("--set", wanted), ("--exception", wanted_exceptions)):
179
+ for value in values.values():
180
+ one_of(value, _SETTINGS, flag=flag)
181
+
182
+ current = client.get("/privacy/policy", params=params)
183
+ # Build on the draft when there is one: the alternative discards
184
+ # somebody's unapproved work the moment a second edit is made.
185
+ base = current.get("draft") or current.get("live") or {}
186
+ known = {c.get("key") for c in (current.get("categories") or [])}
187
+ unknown = sorted(k for k in wanted if known and k not in known)
188
+ if unknown:
189
+ raise CliError(
190
+ f"Unknown categor{'y' if len(unknown) == 1 else 'ies'}: "
191
+ f"{', '.join(unknown)}. Run `maximem-synap privacy policy get` "
192
+ f"to see the list."
193
+ )
194
+
195
+ categories = dict(base.get("categories") or {})
196
+ categories.update(wanted)
197
+ exceptions = dict(base.get("field_type_exceptions") or {})
198
+ exceptions.update(wanted_exceptions)
199
+ body = {
200
+ "categories": categories,
201
+ "field_type_exceptions": exceptions,
202
+ "destination_exceptions": base.get("destination_exceptions") or [],
203
+ }
204
+
205
+ resp = client.put("/privacy/policy", json=body, params=params)
206
+ render.success(f"Saved as draft (version {resp.get('version')}). Nothing is live yet.")
207
+ render.info("[dim]Run `maximem-synap privacy policy approve` to turn it on.[/dim]")
208
+ if render.is_json():
209
+ render.print_json(resp)
210
+
211
+
212
+ @policy_app.command(name="approve")
213
+ def policy_approve(
214
+ ctx: typer.Context,
215
+ instance: Optional[str] = typer.Option(None, "--instance", "-i"),
216
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt (required without a terminal)."),
217
+ ) -> None:
218
+ """Approve the waiting draft. This is what turns a policy on."""
219
+ cc = ctx.obj
220
+ client = cc.client()
221
+ params = _scope_params(instance)
222
+
223
+ if not yes:
224
+ current = client.get("/privacy/policy", params=params)
225
+ draft = current.get("draft")
226
+ if not draft:
227
+ raise CliError("No draft is waiting. Nothing to approve.")
228
+ live_cats = (current.get("live") or {}).get("categories") or {}
229
+ changed = [
230
+ f" {k}: {live_cats.get(k, '—')} -> {v}"
231
+ for k, v in sorted((draft.get("categories") or {}).items())
232
+ if live_cats.get(k) != v
233
+ ]
234
+ render.info(
235
+ f"Draft version {draft.get('version')} changes "
236
+ f"{len(changed)} categor{'y' if len(changed) == 1 else 'ies'}:"
237
+ )
238
+ for line in changed:
239
+ render.info(f"[dim]{line}[/dim]")
240
+ interactive.confirm("Approve and make this live?")
241
+
242
+ resp = client.post("/privacy/policy/approve", params=params)
243
+ render.success(f"Approved. Policy version {resp.get('version')} is live.")
244
+ if render.is_json():
245
+ render.print_json(resp)
246
+
247
+
248
+ @policy_app.command(name="preset")
249
+ def policy_preset(
250
+ ctx: typer.Context,
251
+ name: str = typer.Argument(..., help=f"One of: {' | '.join(_PRESETS)}."),
252
+ instance: Optional[str] = typer.Option(None, "--instance", "-i"),
253
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt (required without a terminal)."),
254
+ ) -> None:
255
+ """Set every category at once from a starting point, and turn it on.
256
+
257
+ Unlike `policy set`, a preset goes live immediately. What each one actually
258
+ does is printed first, because `standard` in particular reads as protective
259
+ and leaves names, dates of birth and phone numbers unprotected.
260
+ """
261
+ one_of(name, _PRESETS, flag="preset")
262
+ cc = ctx.obj
263
+ client = cc.client()
264
+ params = _scope_params(instance)
265
+
266
+ if not yes:
267
+ current = client.get("/privacy/policy", params=params)
268
+ chosen = next(
269
+ (p for p in (current.get("presets") or []) if p.get("key") == name), None,
270
+ )
271
+ if chosen:
272
+ render.info(f"[bold]{chosen.get('label')}[/bold]: {chosen.get('blurb')}")
273
+ render.info(f"[dim]For: {chosen.get('who')}[/dim]")
274
+ unprotected = sorted(
275
+ k for k, v in (chosen.get("categories") or {}).items()
276
+ if v == "not_sensitive"
277
+ )
278
+ if unprotected:
279
+ render.warn(
280
+ f"This preset leaves {len(unprotected)} categor"
281
+ f"{'y' if len(unprotected) == 1 else 'ies'} unprotected: "
282
+ f"{', '.join(unprotected)}."
283
+ )
284
+ interactive.confirm(f"Apply '{name}' and make it live?")
285
+
286
+ resp = client.post(f"/privacy/policy/preset/{name}", params=params)
287
+ render.success(f"Applied '{name}'. Policy version {resp.get('version')} is live.")
288
+ if render.is_json():
289
+ render.print_json(resp)
290
+
291
+
292
+ @policy_app.command(name="history")
293
+ def policy_history(
294
+ ctx: typer.Context,
295
+ instance: Optional[str] = typer.Option(None, "--instance", "-i"),
296
+ ) -> None:
297
+ """Every version of this policy, newest first, and who made it."""
298
+ resp = ctx.obj.client().get("/privacy/policy/history", params=_scope_params(instance))
299
+ if render.is_json():
300
+ render.print_json(resp)
301
+ return
302
+ render.print_table(
303
+ resp.get("versions") or [],
304
+ [
305
+ ("version", "VERSION"),
306
+ ("created_at", "WHEN"),
307
+ ("created_by", "BY"),
308
+ ("actor_type", "ACTOR"),
309
+ ("approved", "APPROVED"),
310
+ ("source", "SOURCE"),
311
+ ],
312
+ empty="No policy versions yet.",
313
+ )
314
+ by_staff = resp.get("changed_by_staff") or 0
315
+ if by_staff:
316
+ render.warn(f"{by_staff} of these were made by Synap staff.")
317
+
318
+
319
+ @policy_app.command(name="use-account-settings")
320
+ def policy_use_account(
321
+ ctx: typer.Context,
322
+ instance: str = typer.Option(..., "--instance", "-i", help="Instance to hand back."),
323
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt (required without a terminal)."),
324
+ ) -> None:
325
+ """Drop an instance's own rules so it follows the account policy again."""
326
+ if not yes:
327
+ interactive.confirm(
328
+ f"Discard {instance}'s own privacy rules and follow the account?",
329
+ )
330
+ resp = ctx.obj.client().post(
331
+ "/privacy/policy/use-account-settings", params={"instance_id": instance},
332
+ )
333
+ render.success(f"{instance} now follows the account policy.")
334
+ if render.is_json():
335
+ render.print_json(resp)
336
+
337
+
338
+ # ── The test box ─────────────────────────────────────────────────────────────
339
+
340
+
341
+ @app.command()
342
+ def preview(
343
+ ctx: typer.Context,
344
+ text: Optional[str] = typer.Option(None, "--text", "-t", help="Text to run detection over."),
345
+ from_file: Optional[str] = typer.Option(None, "--from-file", help="Read the text from a file."),
346
+ use_draft: bool = typer.Option(
347
+ False, "--use-draft", help="Score against the waiting draft instead of the live policy.",
348
+ ),
349
+ instance: Optional[str] = typer.Option(None, "--instance", "-i"),
350
+ ) -> None:
351
+ """See what would be detected in some text, and what would happen to it.
352
+
353
+ Nothing sent here is stored. The reply carries offsets and field-type names,
354
+ never the matched substrings.
355
+ """
356
+ if (text is None) == (from_file is None):
357
+ raise CliError("Pass exactly one of --text or --from-file.")
358
+ if from_file is not None:
359
+ path = Path(from_file)
360
+ if not path.is_file():
361
+ raise CliError(f"--from-file: no such file '{from_file}'.")
362
+ text = path.read_text(encoding="utf-8")
363
+ if not (text or "").strip():
364
+ raise CliError("Nothing to preview: the text is empty.")
365
+
366
+ resp = ctx.obj.client().post(
367
+ "/privacy/preview",
368
+ json={"text": text, "use_draft": use_draft},
369
+ params=_scope_params(instance),
370
+ )
371
+ if render.is_json():
372
+ render.print_json(resp)
373
+ return
374
+ findings = resp.get("findings") or resp.get("detections") or []
375
+ render.print_table(
376
+ findings,
377
+ [
378
+ ("field_type", "FIELD TYPE"),
379
+ ("category", "CATEGORY"),
380
+ ("setting", "SETTING"),
381
+ ("treatment", "TREATMENT"),
382
+ ("start", "START"),
383
+ ("end", "END"),
384
+ ],
385
+ empty="Nothing detected in this text.",
386
+ )
387
+ summary = {k: v for k, v in resp.items() if not isinstance(v, (list, dict))}
388
+ if summary:
389
+ render.print_detail(summary)
390
+
391
+
392
+ # ── What is actually happening ───────────────────────────────────────────────
393
+
394
+
395
+ @app.command()
396
+ def status(ctx: typer.Context) -> None:
397
+ """Is anything actually protected right now."""
398
+ resp = ctx.obj.client().get("/privacy/protection")
399
+ render.print_detail(resp if isinstance(resp, dict) else {"protection": resp},
400
+ title="Protection")
401
+
402
+
403
+ @app.command()
404
+ def report(
405
+ ctx: typer.Context,
406
+ instance: Optional[str] = typer.Option(None, "--instance", "-i"),
407
+ window_days: int = typer.Option(30, "--window-days", min=1, max=365),
408
+ ) -> None:
409
+ """What we found in your data over a window. Counts only, never values."""
410
+ params = {"window_days": window_days, **_scope_params(instance)}
411
+ resp = ctx.obj.client().get("/privacy/report", params=params)
412
+ render.print_detail(resp if isinstance(resp, dict) else {"report": resp},
413
+ title=f"Privacy report · {window_days}d")
414
+
415
+
416
+ @app.command()
417
+ def aliases(ctx: typer.Context) -> None:
418
+ """How many protected values we hold, by field type. Counts only."""
419
+ resp = ctx.obj.client().get("/privacy/aliases")
420
+ render.print_detail(resp if isinstance(resp, dict) else {"aliases": resp},
421
+ title="Aliases")
422
+
423
+
424
+ @app.command()
425
+ def floor(
426
+ ctx: typer.Context,
427
+ instance: Optional[str] = typer.Option(None, "--instance", "-i"),
428
+ days: int = typer.Option(30, "--days", min=1, max=365),
429
+ ) -> None:
430
+ """What the floor removed from your data. The floor cannot be switched off."""
431
+ params = {"days": days, **_scope_params(instance)}
432
+ resp = ctx.obj.client().get("/privacy/floor", params=params)
433
+ render.print_detail(resp if isinstance(resp, dict) else {"floor": resp},
434
+ title=f"Floor · {days}d")
435
+
436
+
437
+ # ── Activity ─────────────────────────────────────────────────────────────────
438
+
439
+ _ACTIVITY_COLUMNS = [
440
+ ("occurred_at", "WHEN"),
441
+ ("action", "ACTION"),
442
+ ("field_type", "FIELD TYPE"),
443
+ ("actor", "ACTOR"),
444
+ ("actor_type", "ACTOR TYPE"),
445
+ ("reason", "REASON"),
446
+ ]
447
+
448
+
449
+ @activity_app.command(name="list")
450
+ def activity_list(
451
+ ctx: typer.Context,
452
+ days: int = typer.Option(90, "--days", min=1, max=400),
453
+ action: Optional[str] = typer.Option(None, "--action", help="Filter to one action."),
454
+ actor: Optional[str] = typer.Option(None, "--actor", help="Filter to one actor."),
455
+ ) -> None:
456
+ """Everything that happened to your sensitive data, ours and yours."""
457
+ params = {k: v for k, v in {
458
+ "days": days, "action": action, "actor": actor,
459
+ }.items() if v is not None}
460
+ resp = ctx.obj.client().get("/privacy/activity", params=params)
461
+ if render.is_json():
462
+ render.print_json(resp)
463
+ return
464
+ rows = resp.get("events") or resp.get("rows") or resp.get("activity") or []
465
+ render.print_table(rows, _ACTIVITY_COLUMNS, empty="No activity in this window.")
466
+
467
+
468
+ @activity_app.command(name="export")
469
+ def activity_export(
470
+ ctx: typer.Context,
471
+ days: int = typer.Option(365, "--days", min=1, max=400),
472
+ out: Optional[str] = typer.Option(
473
+ None, "--out", "-o", help="Write the CSV here instead of standard output.",
474
+ ),
475
+ ) -> None:
476
+ """The same list as CSV, for somebody who has to hand it to an auditor."""
477
+ csv_text = ctx.obj.client().get("/privacy/activity/export", params={"days": days})
478
+ if not isinstance(csv_text, str):
479
+ raise CliError("The server did not return CSV. Try --output json on `activity list`.")
480
+ if out:
481
+ Path(out).write_text(csv_text, encoding="utf-8")
482
+ render.success(f"Wrote {len(csv_text.splitlines()) - 1} rows to {out}.")
483
+ return
484
+ print(csv_text)
485
+
486
+
487
+ # ── Reveal ───────────────────────────────────────────────────────────────────
488
+
489
+
490
+ @app.command()
491
+ def reveal(
492
+ ctx: typer.Context,
493
+ label: List[str] = typer.Option(
494
+ ..., "--label", "-l", help="Repeatable. The alias label to read in the clear.",
495
+ ),
496
+ reason: str = typer.Option(
497
+ ..., "--reason",
498
+ help="Why you need these. Stored, and read later by somebody who was not here.",
499
+ ),
500
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt (required without a terminal)."),
501
+ ) -> None:
502
+ """Read protected values in the clear. Writes one audit row per value.
503
+
504
+ The audit row names the API key, not a person, because a key is what made
505
+ the request. If you need a human's name against this, do it in the dashboard.
506
+ """
507
+ if not (reason or "").strip():
508
+ raise CliError("--reason cannot be blank.")
509
+ if not yes:
510
+ render.info(
511
+ f"About to reveal {len(label)} value(s). This is audited and appears "
512
+ f"on your Activity tab."
513
+ )
514
+ interactive.confirm("Continue?")
515
+
516
+ resp = ctx.obj.client().post(
517
+ "/privacy/reveal", json={"labels": list(label), "reason": reason},
518
+ )
519
+ if render.is_json():
520
+ render.print_json(resp)
521
+ return
522
+ render.print_table(
523
+ resp.get("revealed") or [],
524
+ [("label", "LABEL"), ("field_type", "FIELD TYPE"), ("value", "VALUE")],
525
+ empty="Nothing was revealed.",
526
+ )
527
+ render.info("[dim]This was written to your activity log.[/dim]")
528
+
529
+
530
+ @app.command(name="credential-grant")
531
+ def credential_grant(
532
+ ctx: typer.Context,
533
+ credential_id: str = typer.Option(..., "--credential-id", help="The key to narrow."),
534
+ grant: str = typer.Option(..., "--grant", help=f"One of: {' | '.join(_GRANTS)}."),
535
+ ) -> None:
536
+ """Narrow what one of your own keys receives. Narrowing only, never widening."""
537
+ one_of(grant, _GRANTS, flag="--grant")
538
+ resp = ctx.obj.client().put(
539
+ "/privacy/credential-grant",
540
+ json={"credential_id": credential_id, "grant": grant},
541
+ )
542
+ render.success(f"Key {credential_id} now receives: {grant}.")
543
+ if render.is_json():
544
+ render.print_json(resp)
545
+
546
+
547
+ # ── Field types ──────────────────────────────────────────────────────────────
548
+
549
+
550
+ @field_types_app.command(name="list")
551
+ def field_types_list(ctx: typer.Context) -> None:
552
+ """The field types we can find and the categories they sit in."""
553
+ resp = ctx.obj.client().get("/privacy/field-types")
554
+ if render.is_json():
555
+ render.print_json(resp)
556
+ return
557
+ rows = resp.get("field_types") if isinstance(resp, dict) else resp
558
+ render.print_table(
559
+ rows or [],
560
+ [
561
+ ("key", "KEY"),
562
+ ("label", "LABEL"),
563
+ ("category", "CATEGORY"),
564
+ ("mechanism", "HOW FOUND"),
565
+ ("is_floor", "NEVER STORED"),
566
+ ],
567
+ empty="No field types reported.",
568
+ )
569
+
570
+
571
+ @field_types_app.command(name="create")
572
+ def field_types_create(
573
+ ctx: typer.Context,
574
+ key: str = typer.Option(..., "--key", help="Stable identifier, e.g. 'policy_number'."),
575
+ label: str = typer.Option(..., "--label", help="What a person calls it."),
576
+ category: str = typer.Option(..., "--category", help="The category it belongs to."),
577
+ description: str = typer.Option("", "--description"),
578
+ example: Optional[List[str]] = typer.Option(
579
+ None, "--example", help="Repeatable, max 20. Real-shaped samples.",
580
+ ),
581
+ ) -> None:
582
+ """Define a field type of your own. It reaches the detector without a deploy."""
583
+ body = {
584
+ "key": key,
585
+ "label": label,
586
+ "category": category,
587
+ "description": description,
588
+ "examples": list(example or []),
589
+ }
590
+ resp = ctx.obj.client().post("/privacy/field-types/custom", json=body)
591
+ render.success(f"Created field type '{key}'.")
592
+ if render.is_json():
593
+ render.print_json(resp)
594
+
595
+
596
+ @field_types_app.command(name="delete")
597
+ def field_types_delete(
598
+ ctx: typer.Context,
599
+ key: str = typer.Argument(...),
600
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt (required without a terminal)."),
601
+ ) -> None:
602
+ """Remove a field type you defined."""
603
+ if not yes:
604
+ interactive.confirm(f"Delete custom field type '{key}'?")
605
+ resp = ctx.obj.client().delete(f"/privacy/field-types/custom/{key}")
606
+ render.success(f"Deleted field type '{key}'.")
607
+ if render.is_json():
608
+ render.print_json(resp)
609
+
610
+
611
+ # ── Suggestions ──────────────────────────────────────────────────────────────
612
+
613
+
614
+ @suggestions_app.command(name="list")
615
+ def suggestions_list(
616
+ ctx: typer.Context,
617
+ days: int = typer.Option(30, "--days", min=7, max=365),
618
+ no_record: bool = typer.Option(
619
+ False, "--no-record",
620
+ help="Do not record that these were shown (looking creates a record otherwise).",
621
+ ),
622
+ ) -> None:
623
+ """Field types in your traffic that nobody has decided about yet."""
624
+ resp = ctx.obj.client().get(
625
+ "/privacy/suggestions", params={"days": days, "record": not no_record},
626
+ )
627
+ if render.is_json():
628
+ render.print_json(resp)
629
+ return
630
+ if isinstance(resp, dict):
631
+ # The server splits them: the ones worth acting on first, then the rest.
632
+ rows = list(resp.get("prominent") or []) + list(resp.get("rest") or [])
633
+ else:
634
+ rows = resp
635
+ render.print_table(
636
+ rows or [],
637
+ [
638
+ ("field_type", "FIELD TYPE"),
639
+ ("category", "CATEGORY"),
640
+ ("occurrences", "SEEN"),
641
+ ("distinct_users", "USERS"),
642
+ ("score", "SCORE"),
643
+ ],
644
+ empty="Nothing undecided.",
645
+ )
646
+
647
+
648
+ @suggestions_app.command(name="decide")
649
+ def suggestions_decide(
650
+ ctx: typer.Context,
651
+ field_type: str = typer.Argument(...),
652
+ outcome: str = typer.Option(..., "--outcome", help=f"One of: {' | '.join(_OUTCOMES)}."),
653
+ ) -> None:
654
+ """Protect it, ignore it permanently, or leave it for later."""
655
+ one_of(outcome, _OUTCOMES, flag="--outcome")
656
+ resp = ctx.obj.client().post(
657
+ "/privacy/suggestions/decide",
658
+ json={"field_type": field_type, "outcome": outcome},
659
+ )
660
+ render.success(f"Recorded '{outcome}' for {field_type}.")
661
+ if render.is_json():
662
+ render.print_json(resp)
663
+
664
+
665
+ @suggestions_app.command(name="example")
666
+ def suggestions_example(
667
+ ctx: typer.Context,
668
+ field_type: str = typer.Argument(...),
669
+ instance: Optional[str] = typer.Option(None, "--instance", "-i"),
670
+ ) -> None:
671
+ """Show one real occurrence of a suggested field type. Audited like a reveal."""
672
+ body = {"field_type": field_type}
673
+ if instance:
674
+ body["instance_id"] = instance
675
+ resp = ctx.obj.client().post("/privacy/suggestions/example", json=body)
676
+ render.print_detail(resp if isinstance(resp, dict) else {"example": resp},
677
+ title=field_type)