polyctl 0.7.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.
Files changed (99) hide show
  1. polyctl/__init__.py +7 -0
  2. polyctl/__main__.py +5 -0
  3. polyctl/a2a.py +226 -0
  4. polyctl/a2a_mcp.py +546 -0
  5. polyctl/acp.py +417 -0
  6. polyctl/adapters/README.md +101 -0
  7. polyctl/adapters/aider.json +32 -0
  8. polyctl/adapters/amazon-q.json +15 -0
  9. polyctl/adapters/amp.json +16 -0
  10. polyctl/adapters/antigravity.json +120 -0
  11. polyctl/adapters/claude-code.json +229 -0
  12. polyctl/adapters/cloud-generic.json +57 -0
  13. polyctl/adapters/codex.json +47 -0
  14. polyctl/adapters/command-code.json +45 -0
  15. polyctl/adapters/copilot.json +17 -0
  16. polyctl/adapters/cursor-agent.json +29 -0
  17. polyctl/adapters/deepseek.json +13 -0
  18. polyctl/adapters/droid.json +34 -0
  19. polyctl/adapters/gemini.json +30 -0
  20. polyctl/adapters/grok.json +22 -0
  21. polyctl/adapters/hermes.json +34 -0
  22. polyctl/adapters/kilocode.json +30 -0
  23. polyctl/adapters/kimi.json +23 -0
  24. polyctl/adapters/kiro.json +332 -0
  25. polyctl/adapters/ollama.json +29 -0
  26. polyctl/adapters/omp.json +34 -0
  27. polyctl/adapters/openai-api.json +68 -0
  28. polyctl/adapters/opencode.json +162 -0
  29. polyctl/adapters/pi.json +24 -0
  30. polyctl/adapters/pr-agent.json +54 -0
  31. polyctl/adapters/profiles.json +9 -0
  32. polyctl/adapters/qoder.json +163 -0
  33. polyctl/adapters/qwen.json +27 -0
  34. polyctl/adapters/reasonix.json +25 -0
  35. polyctl/adapters/rewriters/rtk.json +24 -0
  36. polyctl/adapters/trae.json +31 -0
  37. polyctl/adapters/vendors.json +42 -0
  38. polyctl/adapters/warp.json +88 -0
  39. polyctl/allowlist.py +1756 -0
  40. polyctl/api_review.py +920 -0
  41. polyctl/cli.py +835 -0
  42. polyctl/conformance_harness.py +9 -0
  43. polyctl/demo.py +503 -0
  44. polyctl/drivers.py +146 -0
  45. polyctl/email.py +160 -0
  46. polyctl/features.py +98 -0
  47. polyctl/journal.py +144 -0
  48. polyctl/language.py +945 -0
  49. polyctl/lib.py +1296 -0
  50. polyctl/matrix.py +660 -0
  51. polyctl/mcp.py +1362 -0
  52. polyctl/ntfy.py +169 -0
  53. polyctl/outbound.py +39 -0
  54. polyctl/parts/__init__.py +5 -0
  55. polyctl/parts/cli_authority.py +2615 -0
  56. polyctl/parts/cli_channels.py +1325 -0
  57. polyctl/parts/cli_checks.py +2293 -0
  58. polyctl/parts/cli_completion.py +686 -0
  59. polyctl/parts/cli_evidence.py +141 -0
  60. polyctl/parts/cli_gain.py +375 -0
  61. polyctl/parts/cli_harness.py +392 -0
  62. polyctl/parts/cli_hooks.py +1816 -0
  63. polyctl/parts/cli_install.py +638 -0
  64. polyctl/parts/cli_lanes.py +106 -0
  65. polyctl/parts/cli_maintenance.py +2536 -0
  66. polyctl/parts/cli_next.py +248 -0
  67. polyctl/parts/cli_pr.py +53 -0
  68. polyctl/parts/cli_project.py +2857 -0
  69. polyctl/parts/cli_review.py +5158 -0
  70. polyctl/parts/cli_status.py +898 -0
  71. polyctl/parts/lib_adapters.py +2933 -0
  72. polyctl/parts/lib_alarms.py +2106 -0
  73. polyctl/parts/lib_events.py +224 -0
  74. polyctl/parts/lib_evidence.py +412 -0
  75. polyctl/parts/lib_gates.py +2099 -0
  76. polyctl/parts/lib_lanes.py +829 -0
  77. polyctl/parts/lib_mail.py +1541 -0
  78. polyctl/parts/lib_next.py +652 -0
  79. polyctl/parts/lib_pr.py +331 -0
  80. polyctl/parts/lib_slices.py +3337 -0
  81. polyctl/parts/lib_state.py +2415 -0
  82. polyctl/parts/lib_transcript.py +4118 -0
  83. polyctl/pressure.py +325 -0
  84. polyctl/prices.json +47 -0
  85. polyctl/procs.py +1194 -0
  86. polyctl/settings.py +505 -0
  87. polyctl/skill/SKILL.md +365 -0
  88. polyctl/skillkit.py +503 -0
  89. polyctl/storage.py +2055 -0
  90. polyctl/telegram.py +327 -0
  91. polyctl/tiers.py +123 -0
  92. polyctl/verdicts.py +41 -0
  93. polyctl/watchdog.py +3887 -0
  94. polyctl/web.py +337 -0
  95. polyctl-0.7.0.dist-info/METADATA +235 -0
  96. polyctl-0.7.0.dist-info/RECORD +99 -0
  97. polyctl-0.7.0.dist-info/WHEEL +4 -0
  98. polyctl-0.7.0.dist-info/entry_points.txt +5 -0
  99. polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
polyctl/settings.py ADDED
@@ -0,0 +1,505 @@
1
+ """What a person can set that the code used to decide for them (#74).
2
+
3
+ Every threshold here has been wrong for some project at least once, and each time
4
+ the fix was to edit polyctl's own source. They are settings now, each with a documented
5
+ default, resolved in this module and nowhere else: the project's `.polyctl/config.json`
6
+ first, then the machine's `~/.polyctl/settings.json`, then the default below. `polyctl config`
7
+ reads and writes them and docs/configuration.md lists them; a test keeps the
8
+ registry, the documentation and the code that reads them in agreement.
9
+
10
+ A value that is present but unusable - a string where a number belongs, a number
11
+ out of range - is not used, and `polyctl doctor` says what was set and what polyctl uses.
12
+ """
13
+ import json
14
+ import math
15
+ import os
16
+ from collections import namedtuple
17
+
18
+ UTF8 = "utf-8" # every text file polyctl writes or reads; Windows would otherwise use cp1252
19
+
20
+ Setting = namedtuple("Setting", "default kind minimum maximum scope text")
21
+ # The longest a gate may run, in seconds: a longer wait overflowed once the machine lock was held (LEADS-GATE).
22
+ GATE_TIMEOUT_MAX = 7 * 24 * 3600
23
+
24
+
25
+ class Location(str):
26
+ """The kind of a setting that names a repository by URL or path, so separators are allowed."""
27
+
28
+
29
+ # scope: "project" settings are read from the project first; "machine" settings
30
+ # govern state shared by every project on the machine and are read from there only.
31
+ SETTINGS = {
32
+ "round_budget": Setting(
33
+ 5, int, 1, None, "project",
34
+ "review rounds a slice may spend before the watchdog stops nudging and tells a person"),
35
+ "review.max_inflight": Setting(
36
+ 2, int, 1, None, "project",
37
+ "submitted reviews that may run at once; a submit beyond it names what to collect"),
38
+ "review.unhandled_minutes": Setting(
39
+ 30, int, 1, None, "project",
40
+ "minutes a returned review may wait uncollected before the watchdog raises it"),
41
+ "review.prune_after_days": Setting(
42
+ 30, int, 1, None, "project",
43
+ "days after which polyctl prune moves a review artefact nothing rests on out of the repository"),
44
+ "review_timeout": Setting(
45
+ 900, int, 1, None, "project",
46
+ "seconds one reviewer may take; never taken from the command line"),
47
+ "stall_minutes": Setting(
48
+ 60, int, 1, None, "project",
49
+ "minutes a staged candidate may wait to land before throughput calls the slice stalled"),
50
+ "slice_budget_minutes": Setting(
51
+ 0, int, 0, None, "project",
52
+ "minutes one run of a slice may spend before the watchdog parks it; 0 leaves it unbounded"),
53
+ "slice_budget_spend": Setting(
54
+ 0.0, float, 0, None, "project",
55
+ "implementer spend, in the unit its adapter records, one run of a slice may reach before the "
56
+ "watchdog parks it; 0 leaves it unbounded"),
57
+ "size.guideline_paths": Setting(
58
+ 5, int, 1, None, "project",
59
+ "paths a candidate may change before its boundary must say why it is one slice"),
60
+ "size.guideline_product_lines": Setting(
61
+ 400, int, 1, None, "project",
62
+ "product lines a candidate may change before its boundary must say why it is one slice"),
63
+ "size.refuse_product_lines": Setting(
64
+ 4000, int, 1, None, "project",
65
+ "product lines above which no review is credible and polyctl review refuses before spawning"),
66
+ "size.small_overshoot_pct": Setting(
67
+ 25, int, 0, None, "project",
68
+ "percent over the guideline small enough that verified code is never reshaped to meet it"),
69
+ "boundary.inline_max_chars": Setting(
70
+ 400, int, 1, None, "project",
71
+ "characters of acceptance a board row may carry before its boundary belongs in a file"),
72
+ "merge.link_paths": Setting(
73
+ [".venv", "node_modules"], list, None, None, "project",
74
+ "untracked dependency directories a merge result borrows from the project to run its gates"),
75
+ "merge.check_days": Setting(
76
+ 7, int, 1, None, "project",
77
+ "days back polyctl doctor looks for merges no passing run of their result vouches for"),
78
+ "evidence.max_commits_behind": Setting(
79
+ 100, int, 0, None, "project",
80
+ "commits HEAD may move past a platform run's commit before polyctl doctor calls that platform's newest "
81
+ "evidence stale; 0 treats any commit behind as stale"),
82
+ "mail.unseen_yellow_minutes": Setting(
83
+ 15, int, 1, None, "project",
84
+ "minutes a needs-decision message may wait unseen before the architect is told"),
85
+ "mail.unseen_orange_minutes": Setting(
86
+ 60, int, 1, None, "project",
87
+ "minutes unseen before a person's desktop and phone are told"),
88
+ "mail.unseen_red_minutes": Setting(
89
+ 240, int, 1, None, "project",
90
+ "minutes unseen before it rings red and goes to e-mail"),
91
+ "retention.observation_kb": Setting(
92
+ 2048, int, 64, None, "project",
93
+ "kilobytes an observation store (notices, progress, cycles, logs) keeps before its oldest records go"),
94
+ "retention.evidence_keep": Setting(
95
+ 500, int, 1, None, "project",
96
+ "newest rows a chained evidence ledger keeps live when polyctl prune --evidence seals the rest"),
97
+ "repository.kind": Setting(
98
+ "product", str, None, None, "project",
99
+ "product: the architect does not implement beyond a named hotfix; tool: roles may rotate per slice"),
100
+ "review.lenses": Setting(
101
+ "declared", str, None, None, "project",
102
+ "declared: lenses only where a slice names them; auto: defaults from what the candidate touches; off: none"),
103
+ "review.stall_minutes": Setting(
104
+ 10, int, 1, None, "project",
105
+ "minutes a reviewer may spend no CPU before it is killed as stalled, its partial answer kept"),
106
+ "review.context_bytes": Setting(
107
+ 100_000, int, 0, None, "project",
108
+ "bytes of commit-message claims and read-only context a review prompt may carry beside its diff, "
109
+ "where no reviewer route holds it to one argument"),
110
+ "review.same_family": Setting(
111
+ "refused", str, None, None, "project",
112
+ "refused: a reviewer of the implementer's model family is refused; labeled: another model of that "
113
+ "family may review, labeled weaker independence, once a person opts in with --by, on the record"),
114
+ "mode": Setting(
115
+ "full", str, None, None, "project",
116
+ "full: independent reviewer and commit hooks enforced; lite: basic setup without enforcement "
117
+ "(no reviewer probe, no commit hooks; polyctl commit refuses), switched to with polyctl mode lite --by <name>, "
118
+ "on the record"),
119
+ "review.transport": Setting(
120
+ "spawn", str, None, None, "project",
121
+ "spawn: each reviewer route runs as its command; acp: a route whose adapter's ACP command was measured to "
122
+ "hold a reviewer to reads answers through ACP, and any other is spawned with a line saying why; a change "
123
+ "is the reviewer's, held until a person accepts it with polyctl harness seen"),
124
+ "hunter.every_hours": Setting(
125
+ 24, int, 1, None, "project",
126
+ "hours between bug hunts the watchdog starts, when the hunter feature is on"),
127
+ "hunter.files_per_run": Setting(
128
+ 8, int, 1, None, "project",
129
+ "tracked files one hunt reads, going round the tree run by run"),
130
+ "hunter.bytes_per_run": Setting(
131
+ 60_000, int, 1000, None, "project",
132
+ "bytes of source one hunt reads"),
133
+ "hunter.max_file_kb": Setting(
134
+ 512, int, 1, None, "project",
135
+ "kilobytes of a tracked file past which no hunt reads it: a lock file, a bundle, a data set"),
136
+ "hunter.max_leads": Setting(
137
+ 5, int, 1, None, "project",
138
+ "new leads one hunt may send"),
139
+ "hunter.argv": Setting(
140
+ [], list, None, None, "project",
141
+ "the hunter's command with {prompt}, unable to write; none: no hunt runs"),
142
+ "hunter.id": Setting(
143
+ "hunter", str, None, None, "project",
144
+ "the name a hunt's runs and leads are recorded under"),
145
+ "pr.watch": Setting(
146
+ "off", str, None, None, "project",
147
+ "on: polyctl pr watch --once reads this checkout's pull requests through gh and mails the implementer what "
148
+ "needs it; off: it reads nothing"),
149
+ "mail.store": Setting(
150
+ "deletion", str, None, None, "project",
151
+ "deletion: handled mail is deleted; append-only: messages are kept and handling is a record"),
152
+ "mail.sync_repo": Setting(
153
+ None, Location, None, None, "project",
154
+ "the one private repository the message store is pushed to as refs/mail/<project>; none: not synced"),
155
+ "gates.default_timeout": Setting(
156
+ 600, int, 1, GATE_TIMEOUT_MAX, "project",
157
+ "seconds a gate may run when its own definition names no timeout, at most a week"),
158
+ "gates.coverage_min_files": Setting(
159
+ 5, int, 1, None, "project",
160
+ "source files of one toolchain a top-level tree must hold before a gate must exercise it"),
161
+ "watchdog.idle_minutes": Setting(
162
+ 6.0, float, 1, None, "project",
163
+ "minutes of implementer silence before the watchdog acts"),
164
+ "watchdog.max_attempts": Setting(
165
+ 3, int, 1, None, "project",
166
+ "nudges without progress before a person is told the implementer is stuck"),
167
+ "watchdog.resume_gap_hours": Setting(
168
+ 2, int, 1, None, "project",
169
+ "hours without a watchdog cycle after which the next one is a resume: one notice names what stands "
170
+ "and its clocks restart"),
171
+ "watchdog.quota_retry_hours": Setting(
172
+ 5, int, 1, None, "project",
173
+ "hours a slice parked on a usage limit that named no reset waits before one nudge tries again"),
174
+ "decisions.human_after_minutes": Setting(
175
+ 15, int, 1, None, "project",
176
+ "minutes an open decision waits before it rings a person"),
177
+ "waivers.default_hours": Setting(
178
+ 24, int, 1, None, "project",
179
+ "hours a review waiver stays open when --hours is not given"),
180
+ "waivers.max_hours": Setting(
181
+ 168, int, 1, None, "project",
182
+ "the longest a review waiver may be granted for"),
183
+ "alarms.red_after_minutes": Setting(
184
+ 60, int, 1, None, "project",
185
+ "minutes an orange alarm stands before it turns red and sends one e-mail"),
186
+ "fanout.max_agents": Setting(
187
+ 12, int, 1, None, "project",
188
+ "the most agents one fan-out may start"),
189
+ "fanout.per_agent_tokens": Setting(
190
+ 50_000, int, 1, None, "project",
191
+ "the token budget each fanned-out agent is given"),
192
+ "fanout.window_reserve_pct": Setting(
193
+ 30, int, 0, 100, "project",
194
+ "percent of the provider window a fan-out must leave unused"),
195
+ "implementer.name": Setting(
196
+ None, str, None, None, "project",
197
+ "the implementer's name in mail file names; none: its adapter's actor name"),
198
+ "architect.name": Setting(
199
+ "architect", str, None, None, "project",
200
+ "the architect's name in mail file names: its role's, never a model's (#72)"),
201
+ "language": Setting(
202
+ "en", str, None, None, "project",
203
+ "en: the files polyctl init writes and the markers polyctl writes into mail are English; tr: Turkish. "
204
+ "The markers of both are read in every project"),
205
+ "lane.link_paths": Setting(
206
+ [], list, None, None, "project",
207
+ "paths polyctl lane start links into a new lane from the main checkout, such as untracked dependency "
208
+ "directories; none: nothing is linked"),
209
+ "lane.env": Setting(
210
+ [], list, None, None, "project",
211
+ "NAME=value lines polyctl lane start writes into a new lane's lane.env_file and gives its post-create command; "
212
+ "{item}, {lane} and {path} stand for the lane's own"),
213
+ "lane.env_file": Setting(
214
+ ".env", str, None, None, "project",
215
+ "the file at the top of a new lane that lane.env is written to; never one the lane already has"),
216
+ "lane.post_create": Setting(
217
+ [], list, None, None, "project",
218
+ "the command a new lane runs before it is reported ready, as an argument list and never shell text; "
219
+ "{item}, {lane} and {path} stand for the lane's own; none: nothing runs"),
220
+ "lane.post_create_timeout": Setting(
221
+ 600, int, 1, None, "project",
222
+ "seconds a new lane's post-create command may run before the lane is reported not ready"),
223
+ "limits.max_write_lanes": Setting(
224
+ 2, int, 1, None, "project",
225
+ "lanes polyctl lane start makes in this checkout, in any state, before it refuses another until one is removed"),
226
+ "keyflip.rotation": Setting(
227
+ "off", str, None, None, "machine",
228
+ "on: before an actor starts on a spent window, keyflip rotates the machine's account; off: never"),
229
+ "alarms.red_repeat_hours": Setting(
230
+ 6, int, 1, None, "machine",
231
+ "hours before a red alarm that still stands e-mails again"),
232
+ "alarms.reset_after_hours": Setting(
233
+ 2, int, 1, None, "machine",
234
+ "hours of quiet after which an alarm episode is over"),
235
+ "quota.block_percent": Setting(
236
+ 97, int, 1, 100, "machine",
237
+ "a provider window used at or above this percent stops a wake or a nudge"),
238
+ "architect.quota_window_hours": Setting(
239
+ 5, int, 1, None, "machine",
240
+ "the architect's usage window, unless its limit names a week or a month; a reset named further away "
241
+ "is not the one meant"),
242
+ "heartbeat.retired_days": Setting(
243
+ 7, int, 1, None, "machine",
244
+ "days of watchdog silence after which a project counts as retired, not dead"),
245
+ "fleet.window_reserve_pct": Setting(
246
+ 20, int, 0, 100, "machine",
247
+ "percent of the machine's provider window kept free before a report wake"),
248
+ # Read before a gate run, `polyctl lock` and a lane start (MACHINE-PRESSURE). Machine settings on purpose: no flag skips
249
+ # the reading, and a person who wants it off changes these, outside every repository an agent writes. The numbers
250
+ # are those a working machine was gated with: idle to busy paged under 200 swap-ins a second and thrash in the
251
+ # thousands; healthy work ran at 40 to 49% of memory free and at 10 GiB of disk, and none ran at a third of a GiB.
252
+ "limits.refuse_above_swapins_per_sec": Setting(
253
+ 1500, int, 1, None, "machine",
254
+ "swap-ins a second - the lower median of four one-second samples - above which a gate run and polyctl lock wait "
255
+ "for the machine, then refuse, and a lane start refuses; swap used is never read"),
256
+ "limits.refuse_below_free_memory_pct": Setting(
257
+ 15, int, 0, 100, "machine",
258
+ "percent of memory free - memory_pressure's figure on macOS, MemAvailable on Linux - below which a gate run "
259
+ "and polyctl lock wait for the machine, then refuse, and a lane start refuses; 0: never"),
260
+ "limits.refuse_below_free_disk_gib": Setting(
261
+ 8, int, 0, None, "machine",
262
+ "GiB free on the volume that holds the home, never /, below which a gate run and polyctl lock wait for the "
263
+ "machine, then refuse, and a lane start refuses; 0: never"),
264
+ "binaries.extra_dirs": Setting(
265
+ [], list, None, None, "machine",
266
+ "directories searched for agent binaries after PATH, before the usual install locations; "
267
+ "a relative one is not searched"),
268
+ "watchdog.bypass_adapters": Setting(
269
+ [], list, None, None, "machine",
270
+ "adapters whose implementer the watchdog may nudge with the flag that turns off their own sandbox; "
271
+ "none: such a nudge is refused"),
272
+ "review.api_providers": Setting(
273
+ [], list, None, None, "machine",
274
+ "OpenAI-compatible providers the API reviewer may ask, each `<word> <base URL> <variable holding its key>`; "
275
+ "a reviewer names one as `<word>/<model>`; none: no provider"),
276
+ "filters.probe_programs": Setting(
277
+ ["rtk"], list, None, None, "machine",
278
+ "programs polyctl doctor may run as a user-level shell-command filter hook, to prove it leaves measurements alone"),
279
+ "hooks.probe_timeout_seconds": Setting(
280
+ 60, int, 5, 900, "machine",
281
+ "seconds Git may take to run polyctl's pre-commit hook on the synthetic candidate that proves it is installed"),
282
+ "filters.probe_timeout_seconds": Setting(
283
+ 5, int, 1, 60, "machine",
284
+ "seconds a probed filter hook may take to answer for one measurement command before polyctl stops asking it"),
285
+ "retention.events_kb": Setting(
286
+ 2048, int, 64, None, "machine",
287
+ "kilobytes the machine's event log, ~/.polyctl/events.jsonl, keeps before its oldest lines go"),
288
+ }
289
+
290
+ # A setting whose values are words, and the words it takes. Any other value is unusable: set by
291
+ # hand, it is passed over for the default, and `polyctl doctor` names it.
292
+ CHOICES = {
293
+ "mode": ("full", "lite"),
294
+ "review.same_family": ("refused", "labeled"),
295
+ "review.transport": ("spawn", "acp"),
296
+ "language": ("en", "tr"),
297
+ "pr.watch": ("off", "on"),
298
+ }
299
+
300
+ # A setting that weakens a guarantee is a person's act, on the record, as a waiver is (REVIEW-TIERS).
301
+ # `polyctl config set` and `unset` change it only with --by naming a person, never --machine, and append
302
+ # who did it - the name, the login, whether a terminal was attached - to .polyctl/ledger/opt-ins.jsonl.
303
+ # A value written into .polyctl/config.json by hand, which an agent that edits files can do, is not in
304
+ # force until a person's record says the same.
305
+ RECORDED = ("review.same_family", "mode")
306
+
307
+ _MISSING = object()
308
+
309
+
310
+ def default(key):
311
+ value = SETTINGS[key].default
312
+ return list(value) if isinstance(value, list) else value
313
+
314
+
315
+ def machine_path():
316
+ from . import lib as A
317
+ return os.environ.get("POLYCTL_SETTINGS") or os.path.join(A.HOME, ".polyctl", "settings.json")
318
+
319
+
320
+ _MACHINE_TEXT = {}
321
+
322
+
323
+ def machine_settings():
324
+ """The machine's settings, as a document the caller owns.
325
+
326
+ Every setting lookup read the file, 56 times in one `polyctl doctor --check`. Its text is
327
+ kept against the path, size, mtime and inode it was read at, so another POLYCTL_SETTINGS
328
+ or a changed file is read again, and it is parsed on every call: a caller that edits
329
+ what it is given - `polyctl config set --machine` does - edits its own copy.
330
+ """
331
+ path = machine_path()
332
+ try:
333
+ state = os.stat(path)
334
+ text = _MACHINE_TEXT.get((path, state.st_size, state.st_mtime_ns, state.st_ino))
335
+ if text is None:
336
+ with open(path, encoding=UTF8) as fh:
337
+ opened = os.fstat(fh.fileno())
338
+ text = fh.read()
339
+ _MACHINE_TEXT.clear()
340
+ _MACHINE_TEXT[(path, opened.st_size, opened.st_mtime_ns, opened.st_ino)] = text
341
+ data = json.loads(text)
342
+ except (OSError, ValueError):
343
+ return {}
344
+ return data if isinstance(data, dict) else {}
345
+
346
+
347
+ def lookup(document, key):
348
+ node = document
349
+ for part in key.split("."):
350
+ if not isinstance(node, dict) or part not in node:
351
+ return _MISSING
352
+ node = node[part]
353
+ return node
354
+
355
+
356
+ def usable(key, value):
357
+ """Whether a value can be used for this setting."""
358
+ spec = SETTINGS[key]
359
+ if key in CHOICES:
360
+ return isinstance(value, str) and value in CHOICES[key]
361
+ if spec.kind is int:
362
+ if isinstance(value, bool) or not isinstance(value, int):
363
+ return False
364
+ elif spec.kind is float:
365
+ try:
366
+ finite = not isinstance(value, bool) and isinstance(value, (int, float)) and math.isfinite(value)
367
+ except OverflowError:
368
+ return False
369
+ if not finite:
370
+ return False
371
+ elif spec.kind is str:
372
+ return isinstance(value, str) and bool(value.strip()) and "/" not in value and "\\" not in value
373
+ elif spec.kind is Location:
374
+ return isinstance(value, str) and bool(value.strip())
375
+ elif spec.kind is list:
376
+ return isinstance(value, list) and all(isinstance(item, str) and item.strip() for item in value)
377
+ if spec.minimum is not None and value < spec.minimum:
378
+ return False
379
+ if spec.maximum is not None and value > spec.maximum:
380
+ return False
381
+ return True
382
+
383
+
384
+ def expected(key):
385
+ spec = SETTINGS[key]
386
+ if key in CHOICES:
387
+ return "one of " + ", ".join(CHOICES[key])
388
+ if spec.kind is list:
389
+ return "a list of non-empty strings"
390
+ if spec.kind is Location:
391
+ return "a repository URL or path"
392
+ if spec.kind is str:
393
+ return "a name with no path separator"
394
+ words = {int: "a whole number", float: "a finite number"}[spec.kind]
395
+ if spec.minimum is not None and spec.maximum is not None:
396
+ return f"{words} from {spec.minimum} to {spec.maximum}"
397
+ if spec.minimum is not None:
398
+ return f"{words} of at least {spec.minimum}"
399
+ return words
400
+
401
+
402
+ def resolve(cfg, key):
403
+ """(value, source, problem) for one setting.
404
+
405
+ A project setting is read from the project, then the machine; a machine
406
+ setting from the machine only. The first usable value wins; one that is set
407
+ but unusable is passed over and named in `problem`.
408
+ """
409
+ spec = SETTINGS[key]
410
+ layers = [("machine", machine_settings())]
411
+ if spec.scope == "project":
412
+ layers.insert(0, ("project", cfg or {}))
413
+ problem = None
414
+ for source, document in layers:
415
+ value = lookup(document, key)
416
+ if value is _MISSING:
417
+ continue
418
+ if usable(key, value):
419
+ return (list(value) if isinstance(value, list) else value), source, problem
420
+ problem = problem or (f"{key} is set to {value!r} in the {source} settings, which is not "
421
+ f"{expected(key)}")
422
+ return default(key), "default", problem
423
+
424
+
425
+ def get(cfg, key):
426
+ return resolve(cfg, key)[0]
427
+
428
+
429
+ def parse(key, text):
430
+ """A value from the command line, as the setting's kind, or ValueError."""
431
+ spec = SETTINGS[key]
432
+ if spec.kind is int:
433
+ value = int(text)
434
+ elif spec.kind is float:
435
+ try:
436
+ value = float(text)
437
+ except OverflowError as exc:
438
+ raise ValueError(f"{key} must be {expected(key)}") from exc
439
+ elif spec.kind is list:
440
+ value = [part.strip() for part in str(text).split(",") if part.strip()]
441
+ else:
442
+ value = str(text).strip()
443
+ if not usable(key, value):
444
+ raise ValueError(f"{key} must be {expected(key)}")
445
+ return value
446
+
447
+
448
+ def assign(document, key, value):
449
+ """Set or, with value _MISSING, remove one dotted key in a config document."""
450
+ parts = key.split(".")
451
+ node = document
452
+ for part in parts[:-1]:
453
+ child = node.get(part)
454
+ if not isinstance(child, dict):
455
+ if value is _MISSING:
456
+ return document
457
+ child = node[part] = {}
458
+ node = child
459
+ if value is _MISSING:
460
+ node.pop(parts[-1], None)
461
+ else:
462
+ node[parts[-1]] = value
463
+ return document
464
+
465
+
466
+ def write_machine(document):
467
+ from .storage import replace_file_durably
468
+ try:
469
+ replace_file_durably(machine_path(), (json.dumps(document, indent=2, sort_keys=True) + "\n").encode(UTF8))
470
+ finally:
471
+ _MACHINE_TEXT.clear() # the next read takes the file as it now is, whatever its timestamps say
472
+
473
+
474
+ def problems(cfg):
475
+ """(key, text) for every setting whose effective value is not what was written.
476
+
477
+ Covers values that are set but unusable, project settings placed where only
478
+ the machine is read, and names under a settings group that polyctl does not read.
479
+ """
480
+ out = []
481
+ machine = machine_settings()
482
+ for key, spec in SETTINGS.items():
483
+ _, _, problem = resolve(cfg, key)
484
+ if problem:
485
+ out.append((key, f"{problem}; polyctl uses {resolve(cfg, key)[0]!r}"))
486
+ if spec.scope == "machine" and lookup(cfg or {}, key) is not _MISSING:
487
+ out.append((key, f"{key} is set in the project, but it governs the whole machine and is read "
488
+ f"only from {machine_path()}: `polyctl config set {key} … --machine`"))
489
+ groups = {key.split(".")[0] for key in SETTINGS if "." in key}
490
+ for source, document in (("project", cfg or {}), ("machine", machine)):
491
+ for group in sorted(groups):
492
+ # Project roles also hold argv and adapter fields; machine roles are settings (TRIAGE-1-LOW).
493
+ if source == "project" and group in ("implementer", "architect"):
494
+ continue
495
+ section = document.get(group)
496
+ if not isinstance(section, dict):
497
+ continue
498
+ for name in sorted(section):
499
+ if f"{group}.{name}" not in SETTINGS:
500
+ out.append((f"{group}.{name}", f"{group}.{name} in the {source} settings is not a setting "
501
+ "polyctl reads; `polyctl config list` shows the names"))
502
+ for name in sorted(machine):
503
+ if name not in SETTINGS and name not in groups:
504
+ out.append((name, f"{name} in the machine settings is not a setting polyctl reads"))
505
+ return out