formist-cli 0.1.0__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.
formist_cli/resolve.py ADDED
@@ -0,0 +1,443 @@
1
+ """Name -> id resolution: the reason an operator never types a UUID.
2
+
3
+ The bulk endpoint's ``$ref`` only resolves a backward, within-batch
4
+ reference to a row the same request just created. Every ``update`` and
5
+ ``delete`` op still has to carry a literal ``$id`` UUID, so a wrong id
6
+ typed or copied by hand is exactly the failure this module exists to
7
+ prevent: every organisation's ids differ between environments, and a
8
+ wrong id written into a column with no foreign key raises nothing.
9
+
10
+ So resolution happens here, in the client, seconds before the write,
11
+ against the environment being written. The wire format the endpoint sees
12
+ is unchanged.
13
+
14
+ Three rules this module keeps:
15
+
16
+ 1. Exactly one row, or refuse. Not "the best match", not "the first".
17
+ Resolving by a shortened id prefix is exactly how a prefix collision
18
+ becomes a correctness bug.
19
+
20
+ 2. A page is not a table. The list endpoints cap a page, so a resolver
21
+ that counts matches in the page it was handed has measured the page.
22
+ When the server's reported total exceeds what came back, uniqueness is
23
+ unproven and this module refuses rather than reporting the count it
24
+ happens to be able to see.
25
+
26
+ 3. Match across shapes; carry the raw value. A name column can hold
27
+ either a plain string or an ``{en, ar}`` map depending on environment,
28
+ so matching looks inside both shapes, but :attr:`Match.value` is the
29
+ raw column value exactly as the server returned it, because it becomes
30
+ the ``$expect`` the server re-checks, an exact, un-coalesced
31
+ comparison. Flattening a map to the matched string here would send an
32
+ ``$expect`` that can never match.
33
+
34
+ Rule 3 is also what makes the resolution self-checking: the id this
35
+ module picks is handed back to the server together with the value it was
36
+ picked by, so a mis-resolution is refused by the row itself rather than
37
+ written to confidently.
38
+
39
+ Stdlib only: `fm` must add no runtime dependency.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ from collections.abc import Callable
45
+ from dataclasses import dataclass
46
+ from typing import Any
47
+
48
+ from formist_cli.cli_support import default_fetch as _default_fetch
49
+ from formist_cli.targets import Target, require_space_id
50
+
51
+ #: What the list endpoints cap a page at. Asking for more is silently
52
+ #: clamped, so this is the largest page uniqueness can be proved within;
53
+ #: beyond it, :func:`find` refuses instead of guessing.
54
+ MAX_PAGE = 200
55
+
56
+ #: How many pages a paginated walk will take before it gives up and
57
+ #: refuses. 50 x 200 = 10,000 rows, comfortably above any real space and
58
+ #: low enough that a server answering `items: []` beside a non-zero
59
+ #: `total` is reported rather than looped on forever.
60
+ MAX_PAGES = 50
61
+
62
+
63
+ class ResolutionError(Exception):
64
+ """A name that does not identify exactly one row. Written for an operator."""
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class KindSpec:
69
+ """How one writable kind is listed and identified.
70
+
71
+ ``name_fields`` empty means the kind has no name to resolve by, see
72
+ :attr:`no_name_reason`. The registry stays total over what the bulk
73
+ endpoint will write rather than omitting the awkward ones: a kind that
74
+ is silently absent reads as an oversight and gets "helpfully" added by
75
+ the next person, while a kind that refuses with a reason is a decision
76
+ someone can argue with.
77
+ """
78
+
79
+ path: str
80
+ name_fields: tuple[str, ...] = ()
81
+ #: For kinds whose identity lives inside a jsonb column (a custom entity
82
+ #: has no name column at all). The column is searched by its inner keys
83
+ #: but carried whole for ``$expect``.
84
+ data_field: str | None = None
85
+ data_keys: tuple[str, ...] = ("name", "title", "label", "subject")
86
+ no_name_reason: str | None = None
87
+
88
+
89
+ #: Every kind the bulk endpoint will write, and how to find one by name.
90
+ #: Two of them are join rows with no name of their own; they are present and
91
+ #: refusing rather than absent.
92
+ KINDS: dict[str, KindSpec] = {
93
+ # `org` is a legacy wire key kept for rows an old backfill has not yet
94
+ # reached; a stakeholder's organisation now lives at `parent_id`.
95
+ # `_candidates_for` filters on `if field in item`, so once a row no
96
+ # longer carries `org` this entry simply stops contributing to it
97
+ # rather than erroring. Remove it in the same change that drops the
98
+ # column, and resolve by `parent_id` instead if still needed.
99
+ "STAKEHOLDER": KindSpec("/projects/{space}/stakeholders", ("name", "email", "org")),
100
+ # Not "title": the DB column is `Session.title`, but the list endpoint's
101
+ # serialiser renames it on the wire to `name`, and the legacy-input
102
+ # mirror does the same rename in the other direction. `_candidates_for`
103
+ # below filters on `if field in item`, so a spec naming "title" here
104
+ # would match zero keys of every session dict the server ever sends.
105
+ # Resolve by the wire key, not the column.
106
+ "SESSION": KindSpec("/projects/{space}/sessions", ("name",)),
107
+ "TASK": KindSpec("/projects/{space}/tasks", ("subject",)),
108
+ "ENTITY_TYPE": KindSpec(
109
+ "/projects/{space}/entity-types", ("single_name", "plural_name")
110
+ ),
111
+ "SKILL": KindSpec("/projects/{space}/skills", ("name",)),
112
+ "SAVED_VIEW": KindSpec("/projects/{space}/views", ("name",)),
113
+ # A Section resolves by its own name, which is unique per space, so a
114
+ # name is an unambiguous handle here.
115
+ "SECTION": KindSpec("/projects/{space}/sections", ("name",)),
116
+ # SECTION_LINK is deliberately absent: this dict must equal the bulk
117
+ # endpoint's writable kinds, and SECTION_LINK is closed there on
118
+ # purpose. A kind `fm` can resolve is a kind the bulk endpoint can write.
119
+ "CUSTOM": KindSpec("/projects/{space}/custom-entities", data_field="data"),
120
+ "SESSION_PARTICIPANT": KindSpec(
121
+ "/projects/{space}/session-participants",
122
+ no_name_reason=(
123
+ "a SESSION_PARTICIPANT is the join row between a session and a "
124
+ "stakeholder and has no name of its own. Resolve the session and "
125
+ "the stakeholder by name separately, then address this row by "
126
+ "the pair."
127
+ ),
128
+ ),
129
+ "FILE_LINK": KindSpec(
130
+ "/projects/{space}/files",
131
+ no_name_reason=(
132
+ "a FILE_LINK is the join row attaching a file to an entity and has no "
133
+ "name of its own. Resolve the file and the entity separately."
134
+ ),
135
+ ),
136
+ }
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class Match:
141
+ """One resolved row.
142
+
143
+ :attr:`value` is the raw column value as the server returned it, never
144
+ a rendering of it. It travels into ``$expect`` unchanged.
145
+ """
146
+
147
+ id: str
148
+ #: The column that matched, the one whose value goes into ``$expect``.
149
+ field: str
150
+ value: Any
151
+ #: Display text for a human. NEVER used as data.
152
+ label: str
153
+
154
+
155
+ Fetcher = Callable[..., Any]
156
+
157
+
158
+ def _strings_in(value: Any) -> list[str]:
159
+ """Every string a column value could be identified by, across both shapes.
160
+
161
+ A plain string yields itself; an ``{en, ar}`` I18nString map yields its values.
162
+ This is for matching only; the raw value is what gets carried forward.
163
+ """
164
+ if isinstance(value, str):
165
+ return [value]
166
+ if isinstance(value, dict):
167
+ return [v for v in value.values() if isinstance(v, str)]
168
+ return []
169
+
170
+
171
+ def _candidates_for(item: dict, spec: KindSpec) -> list[tuple[str, Any, list[str]]]:
172
+ """``(field, raw_value, matchable_strings)`` for one row."""
173
+ if spec.data_field:
174
+ raw = item.get(spec.data_field) or {}
175
+ strings: list[str] = []
176
+ if isinstance(raw, dict):
177
+ for key in spec.data_keys:
178
+ strings.extend(_strings_in(raw.get(key)))
179
+ return [(spec.data_field, raw, strings)]
180
+ return [
181
+ (field, item.get(field), _strings_in(item.get(field)))
182
+ for field in spec.name_fields
183
+ if field in item
184
+ ]
185
+
186
+
187
+ def _label(item: dict, spec: KindSpec) -> str:
188
+ for _field, _raw, strings in _candidates_for(item, spec):
189
+ if strings:
190
+ return strings[0]
191
+ return str(item.get("id", "?"))
192
+
193
+
194
+ def kind_names() -> str:
195
+ """The valid kinds, lowercase, for a message an operator can retype."""
196
+ return ", ".join(sorted(k.lower() for k in KINDS))
197
+
198
+
199
+ def require_kind(raw: str | None) -> str:
200
+ """The one place a typed kind becomes a canonical one, or is refused.
201
+
202
+ Every command that takes a kind calls this, rather than each
203
+ normalising its own copy, so a rule like "kinds are typed in
204
+ lowercase" lives in one place instead of several that can disagree
205
+ about what `Stakeholder`, `saved-view` or a typo should do.
206
+
207
+ Deliberately not named `canonical_kind`: `chats.py` already has a
208
+ function by that name for an unrelated vocabulary (`background-agent` /
209
+ `user-chat`), and two same-named normalisers over different
210
+ vocabularies invite exactly the kind of collision this module's rules
211
+ exist to prevent.
212
+
213
+ Refuses rather than passes an unknown kind through, because a positional
214
+ argument accepts anything the shell hands it. The refusal lists the valid
215
+ kinds: an operator who typed `stakeholdr` needs the spelling, not the word
216
+ "invalid".
217
+ """
218
+ if raw is None or not raw.strip():
219
+ raise ResolutionError(
220
+ f"a kind is required. One of: {kind_names()}."
221
+ )
222
+ canonical = raw.strip().upper().replace("-", "_")
223
+ if canonical not in KINDS:
224
+ raise ResolutionError(
225
+ f"unknown kind {raw!r}. Valid kinds: {kind_names()}.\n"
226
+ "Kinds are case-insensitive and `-` and `_` are interchangeable, so "
227
+ "`saved-view`, `saved_view` and `SAVED_VIEW` are the same kind, "
228
+ f"but {raw!r} is not one of them under any spelling."
229
+ )
230
+ return canonical
231
+
232
+
233
+ def _spec(kind: str) -> KindSpec:
234
+ spec = KINDS.get(kind)
235
+ if spec is None:
236
+ raise ResolutionError(
237
+ f"unknown kind {kind!r}. Valid kinds: {kind_names()}."
238
+ )
239
+ return spec
240
+
241
+
242
+ def list_rows(
243
+ *,
244
+ kind: str,
245
+ target: Target,
246
+ space: str,
247
+ token: str | None = None,
248
+ fetch: Fetcher | None = None,
249
+ q: str | None = None,
250
+ subject: str | None = None,
251
+ remedy: str | None = None,
252
+ paginate: bool = False,
253
+ ) -> list[dict]:
254
+ """Every row of ``kind`` in ``space``, as the server sent them.
255
+
256
+ Extracted from :func:`find` rather than copied, because it carries rule 2
257
+ and a second copy of that rule is a second place for it to rot: a page
258
+ is not a table, so when the server says there are more rows than it
259
+ sent, no statement about the set is available, including a negative
260
+ one. ``fm diff`` needs whole rows (``find`` returns only the matched
261
+ column), and a diff that measured the page it was handed would report
262
+ every unseen row as a would-delete.
263
+
264
+ ``subject`` and ``remedy`` exist because the rule is shared and the
265
+ message cannot be: a resolver asked "is this name unique?" must not be
266
+ answered "the table could not be listed completely", which is true of
267
+ the table, not of the question, and drops the name the operator typed.
268
+ The remedies differ too: a resolver can narrow its search, and a diff
269
+ cannot, it needs every row or none.
270
+
271
+ ``paginate`` walks ``offset`` until the rows in hand equal the ``total``
272
+ the server reported, and is how a caller that needs the whole table
273
+ gets one. It does not weaken rule 2, it satisfies it: the refusal below
274
+ still fires whenever the walk ends holding fewer rows than the server
275
+ claims exist.
276
+ """
277
+ spec = _spec(kind)
278
+ space = require_space_id(space)
279
+ fetch = fetch or _default_fetch
280
+ path = spec.path.format(space=space)
281
+
282
+ items: list[dict] = []
283
+ total: Any = None
284
+ offset = 0
285
+ # A page that returns nothing, or a total that moves under the walk, ends
286
+ # it, and the reconciliation below turns that into a refusal. Without the
287
+ # cap a server that always answers `items: []` with a non-zero `total`
288
+ # would spin forever; with it, the same condition is reported as what it is.
289
+ for _ in range(MAX_PAGES):
290
+ params = {"limit": str(MAX_PAGE), "offset": str(offset)}
291
+ if q:
292
+ params["q"] = q
293
+ payload = fetch(target, path, token=token, params=params)
294
+ if not isinstance(payload, dict):
295
+ raise ResolutionError(
296
+ f"listing {kind} returned {type(payload).__name__}, not a list envelope."
297
+ )
298
+ page = [i for i in (payload.get("items") or []) if isinstance(i, dict)]
299
+ page_total = payload.get("total")
300
+ if total is None:
301
+ total = page_total
302
+ elif isinstance(total, int) and page_total != total:
303
+ # The table changed while it was being read. A plan built from an
304
+ # inconsistent scan is exactly the thing `$expect` exists to catch one
305
+ # step later, and catching it there means the operator has already read
306
+ # and approved a report describing a set that never existed.
307
+ raise ResolutionError(
308
+ f"{kind} changed while it was being listed: the server reported "
309
+ f"{total} rows and then {page_total} mid-scan.\n"
310
+ "The rows in hand are a mixture of two states of the table, and no "
311
+ "statement about the set is available.\n"
312
+ "-> Retry when the space is not being written to."
313
+ )
314
+ items.extend(page)
315
+ offset += MAX_PAGE
316
+ if not paginate or not page or not isinstance(total, int) or len(items) >= total:
317
+ break
318
+
319
+ if isinstance(total, int) and total > len(items):
320
+ capped = (
321
+ f"the walk stopped after {MAX_PAGES} pages"
322
+ if paginate
323
+ else f"the list endpoint caps a page at {MAX_PAGE}"
324
+ )
325
+ raise ResolutionError(
326
+ (subject or f"{kind} could not be listed completely")
327
+ + f": the server reports {total} matching rows but returned "
328
+ f"{len(items)} ({capped}).\n"
329
+ "Refusing rather than counting the page: a caller that measures the "
330
+ "page it was handed has not measured the table.\n"
331
+ "-> " + (remedy or "Narrow the search, or address these rows by id.")
332
+ )
333
+ return items
334
+
335
+
336
+ def find(
337
+ name: str | None,
338
+ *,
339
+ kind: str,
340
+ target: Target,
341
+ space: str,
342
+ token: str | None = None,
343
+ fetch: Fetcher | None = None,
344
+ ) -> list[Match]:
345
+ """Every row of ``kind`` whose name matches ``name`` exactly, as candidates.
346
+
347
+ ``name`` of None lists the kind (this is ``fm get``'s listing form).
348
+ Listing deliberately does not refuse on ambiguity: showing the operator
349
+ both rows is the entire point of the command.
350
+
351
+ ``?q=`` narrows server-side but only ilike-style, so it selects
352
+ candidates; identity is decided here, exactly. Accepting the server's
353
+ substring hit as an answer would resolve "Dr Haddad" onto "Dr Haddad Jr".
354
+ """
355
+ spec = _spec(kind)
356
+ # The two forms of this call are two different questions and must not share a
357
+ # refusal: `fm get STAKEHOLDER` with no --name printed "STAKEHOLDER None could
358
+ # not be proved unique", which names no row, asks about no name, and answers a
359
+ # question the operator did not put. Uniqueness is only at stake when a name is.
360
+ if name is None:
361
+ subject = f"{kind} could not be listed completely"
362
+ remedy = (
363
+ "Narrow with --name, or read the rows through the API directly: a "
364
+ "listing that shows some of the table looks exactly like one that shows "
365
+ "all of it."
366
+ )
367
+ else:
368
+ subject = f"{kind} {name!r} could not be proved unique"
369
+ remedy = "Narrow the search, or address this row by its id."
370
+ items = list_rows(
371
+ kind=kind, target=target, space=space, token=token, fetch=fetch, q=name,
372
+ subject=subject, remedy=remedy,
373
+ )
374
+
375
+ matches: list[Match] = []
376
+ for item in items:
377
+ for field, raw, strings in _candidates_for(item, spec):
378
+ if name is None or name in strings:
379
+ matches.append(
380
+ Match(
381
+ id=str(item.get("id")),
382
+ field=field,
383
+ value=raw,
384
+ label=_label(item, spec),
385
+ )
386
+ )
387
+ break
388
+ return matches
389
+
390
+
391
+ def resolve_one(
392
+ name: str,
393
+ *,
394
+ kind: str,
395
+ target: Target,
396
+ space: str,
397
+ token: str | None = None,
398
+ fetch: Fetcher | None = None,
399
+ ) -> Match:
400
+ """The single row named ``name``, or a refusal explaining what was found.
401
+
402
+ Rule 1. There is no "closest match" branch and there must never be one.
403
+ """
404
+ spec = _spec(kind)
405
+ if spec.no_name_reason:
406
+ raise ResolutionError(
407
+ f"{kind} cannot be resolved by name: {spec.no_name_reason}"
408
+ )
409
+
410
+ matches = find(
411
+ name, kind=kind, target=target, space=space, token=token, fetch=fetch
412
+ )
413
+
414
+ if len(matches) == 1:
415
+ return matches[0]
416
+
417
+ if not matches:
418
+ # Say what was NEARLY matched, or the operator cannot act on the refusal.
419
+ # Case is never folded silently: folding it is how the wrong row is picked.
420
+ near = find(
421
+ None, kind=kind, target=target, space=space, token=token, fetch=fetch
422
+ )
423
+ folded = [m for m in near if m.label.casefold() == name.casefold()]
424
+ hint = ""
425
+ if folded:
426
+ hint = (
427
+ "\nA row differs from it only by case: "
428
+ + ", ".join(f"{m.label!r} ({m.id})" for m in folded)
429
+ + "\n`fm` does not fold case when resolving: matching "
430
+ "case-insensitively is how a resolver picks the wrong row. Use the "
431
+ "name exactly as stored."
432
+ )
433
+ raise ResolutionError(
434
+ f"{name!r} matched no {kind} in this space ({target.name}).{hint}"
435
+ )
436
+
437
+ listed = "\n".join(f" {m.id} {m.label!r}" for m in matches)
438
+ raise ResolutionError(
439
+ f"{name!r} matched {len(matches)} {kind} rows in this space ({target.name}); "
440
+ "a name that identifies two rows identifies neither:\n"
441
+ f"{listed}\n"
442
+ "-> Address the one you mean by its id, or give a name that is unique."
443
+ )
@@ -0,0 +1,199 @@
1
+ """``fm settings``: read and flip the admin-editable runtime switches.
2
+
3
+ The CLI half of ``GET/PATCH /admin/settings``.
4
+
5
+ fm settings show --host evane
6
+ fm settings set --host evane scheduler.disabled=true
7
+ fm settings clear --host evane
8
+
9
+ The change is per region: the values live in a config document in that
10
+ region's blob storage (``file:`` in the output names it), so ``--env
11
+ ae`` and ``--host evane`` are two separate changes. Every replica of
12
+ the region reads it, and it survives restarts. Every response prints
13
+ the instance that answered.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+
21
+ from formist_cli import api, context
22
+ from formist_cli.cli_support import PLATFORM_ADMIN_GATE_NOTE, add_admin_flag
23
+ from formist_cli.cli_support import build_standalone_parser as _build_standalone_parser
24
+
25
+ SUBJECTS = ("show", "set", "clear")
26
+ DEFAULT_SUBJECT = "show"
27
+
28
+ ENDPOINT = "/admin/settings"
29
+
30
+ _TRUE = {"1", "true", "yes", "on"}
31
+ _FALSE = {"0", "false", "no", "off"}
32
+ #: The third state of the push-sync switches: neither on nor off, but "decide
33
+ #: from the notification URL". Spelled out rather than inferred from an empty
34
+ #: value, so `field=` is a typo rather than a silent reset.
35
+ _AUTO = {"auto", "null", "none", "unset"}
36
+
37
+
38
+ class SettingsError(Exception):
39
+ """A refusal about this surface, written for an operator."""
40
+
41
+
42
+ def canonical_subject(subject: str | None) -> str:
43
+ if subject is None:
44
+ return DEFAULT_SUBJECT
45
+ value = subject.strip().lower()
46
+ if value not in SUBJECTS:
47
+ raise SettingsError(f"unknown subcommand {subject!r}. Valid: {', '.join(SUBJECTS)}.")
48
+ return value
49
+
50
+
51
+ def parse_assignments(items: list[str]) -> dict[str, bool | None]:
52
+ """``["a.b=true", "c.d=0", "e.f=auto"]`` -> ``{"a.b": True, "c.d": False, "e.f": None}``.
53
+
54
+ Refuses anything outside the three vocabularies rather than guessing:
55
+ ``scheduler.disabled=maybe`` silently becoming ``False`` is how an operator
56
+ ends up believing a switch is off.
57
+ """
58
+ out: dict[str, bool | None] = {}
59
+ for item in items:
60
+ if "=" not in item:
61
+ raise SettingsError(f"expected field=value, got {item!r}")
62
+ field, _, raw = item.partition("=")
63
+ field = field.strip()
64
+ value = raw.strip().lower()
65
+ if value in _TRUE:
66
+ out[field] = True
67
+ elif value in _FALSE:
68
+ out[field] = False
69
+ elif value in _AUTO:
70
+ out[field] = None
71
+ else:
72
+ raise SettingsError(
73
+ f"{field}={raw!r} is not a boolean; use one of "
74
+ f"{', '.join(sorted(_TRUE))} / {', '.join(sorted(_FALSE))} "
75
+ f"/ {', '.join(sorted(_AUTO))}"
76
+ )
77
+ return out
78
+
79
+
80
+ def render_show(payload: dict) -> str:
81
+ lines = [f"instance: {payload.get('instance')}", f"file: {payload.get('file')}"]
82
+ if not payload.get("file_exists"):
83
+ lines.append(" (no overrides document yet: every value below is env/run-config)")
84
+ lines.append("")
85
+ width = max((len(f["field"]) for f in payload.get("fields", [])), default=0)
86
+ for entry in payload.get("fields", []):
87
+ mark = "*" if entry.get("overridden") else " "
88
+ value = "auto" if entry["value"] is None else str(entry["value"]).lower()
89
+ restart = " (restart)" if entry.get("restart_required") else ""
90
+ lines.append(f" {mark} {entry['field']:<{width}} {value}{restart}")
91
+ lines.append("")
92
+ lines.append("* = set by this region's overrides document")
93
+ lines.append("(restart) = read once at startup; the change lands on the next one")
94
+ lines.append(f"note: {payload.get('scope_note')}")
95
+ return "\n".join(lines)
96
+
97
+
98
+ def render_patch(payload: dict) -> str:
99
+ lines = [f"instance: {payload.get('instance')}", f"file: {payload.get('file')}"]
100
+ for change in payload.get("applied", []):
101
+ before = "auto" if change["before"] is None else str(change["before"]).lower()
102
+ after = "auto" if change["after"] is None else str(change["after"]).lower()
103
+ lines.append(f" {change['field']}: {before} -> {after}")
104
+ for field in payload.get("unchanged", []):
105
+ lines.append(f" {field}: unchanged")
106
+ for field in payload.get("cleared", []):
107
+ lines.append(f" {field}: override removed")
108
+ if not any(payload.get(k) for k in ("applied", "unchanged", "cleared")):
109
+ lines.append(" (nothing changed)")
110
+ restart = payload.get("restart_required") or []
111
+ if restart:
112
+ lines.append(
113
+ f"restart this instance for: {', '.join(restart)}"
114
+ )
115
+ return "\n".join(lines)
116
+
117
+
118
+ def _add_arguments(parser: argparse.ArgumentParser) -> None:
119
+ parser.add_argument(
120
+ "subject", nargs="?",
121
+ help=f"one of: {', '.join(SUBJECTS)} (default: {DEFAULT_SUBJECT})",
122
+ )
123
+ parser.add_argument(
124
+ "assignments", nargs="*", metavar="field=value",
125
+ help="for `set`: one or more dotted field names with a boolean value",
126
+ )
127
+ parser.add_argument(
128
+ "--host",
129
+ default=argparse.SUPPRESS,
130
+ metavar="HOST",
131
+ help="deployment name or API origin (default: formist, or `fm use` for reads); "
132
+ "a write never inherits it",
133
+ )
134
+ parser.add_argument("--json", action="store_true", help="raw JSON instead of a report")
135
+
136
+
137
+ _HELP = "read or flip the admin-editable runtime switches (admin)"
138
+
139
+ _DESCRIPTION = """Read and change the switches an admin may flip without a deploy.
140
+
141
+ fm settings show --host evane
142
+ fm settings set --host evane scheduler.disabled=true
143
+ fm settings set --env ae connectors.sync_enabled=false connectors.agentic_review=true
144
+ fm settings clear --host evane
145
+
146
+ The values live in a config-format document in each region's blob storage, so
147
+ `--env ae` and `--host evane` are two separate changes; every replica of a
148
+ region reads its document, and it survives restarts. `show` marks with a `*`
149
+ every field the document decides; the rest come from the environment or the
150
+ deployment's run-config.
151
+ """
152
+
153
+
154
+ def add_parser(subparsers) -> argparse.ArgumentParser:
155
+ parser = subparsers.add_parser(
156
+ "settings", help=_HELP, description=_DESCRIPTION,
157
+ epilog=PLATFORM_ADMIN_GATE_NOTE,
158
+ formatter_class=argparse.RawDescriptionHelpFormatter,
159
+ )
160
+ _add_arguments(parser)
161
+ add_admin_flag(parser)
162
+ return parser
163
+
164
+
165
+ def build_standalone_parser() -> argparse.ArgumentParser:
166
+ return _build_standalone_parser(add_parser)
167
+
168
+
169
+ def run(args) -> int:
170
+ subject = canonical_subject(getattr(args, "subject", None))
171
+ assignments = list(getattr(args, "assignments", []) or [])
172
+
173
+ if subject == "set" and not assignments:
174
+ raise SettingsError("`fm settings set` needs at least one field=value")
175
+ if subject != "set" and assignments:
176
+ raise SettingsError(f"`fm settings {subject}` takes no field=value arguments")
177
+
178
+ ctx = context.resolve(args, for_write=subject != "show", need_token=True)
179
+
180
+ if subject == "show":
181
+ payload = api.admin_get(ctx.target, ENDPOINT, token=ctx.token)
182
+ render = render_show
183
+ else:
184
+ body = (
185
+ {"clear": True}
186
+ if subject == "clear"
187
+ else {"values": parse_assignments(assignments)}
188
+ )
189
+ payload = api.admin_patch(ctx.target, ENDPOINT, body, token=ctx.token)
190
+ render = render_patch
191
+
192
+ if not isinstance(payload, dict):
193
+ raise SettingsError(f"{ENDPOINT} returned a non-object response: {payload!r}")
194
+
195
+ if args.json:
196
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
197
+ else:
198
+ print(render(payload))
199
+ return 0