@yahyahammad/venastine 0.3.8 → 0.3.9

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 (128) hide show
  1. package/.env.example +19 -19
  2. package/CONFIG_ARCHITECTURE.md +2030 -2002
  3. package/LICENSE +201 -201
  4. package/README.md +1034 -1034
  5. package/agents/builtin/compactor.md +75 -75
  6. package/agents/builtin/explore.md +77 -77
  7. package/agents/builtin/pipeline-reviewer.md +100 -100
  8. package/agents/builtin/plan.md +106 -106
  9. package/agents/builtin/review.md +74 -74
  10. package/agents/manager.py +261 -261
  11. package/agents/subagent_tool.py +472 -472
  12. package/agents/tui_commands.py +238 -146
  13. package/bin/venastine.mjs +528 -528
  14. package/bin/venastine.py +71 -71
  15. package/cli_commands.py +838 -835
  16. package/config.yaml +13 -0
  17. package/config_edit.py +1301 -1301
  18. package/config_schema.py +971 -966
  19. package/config_update.py +749 -749
  20. package/core/agent_activity.py +256 -256
  21. package/core/ansi.py +452 -452
  22. package/core/approval.py +137 -137
  23. package/core/call_view.py +364 -364
  24. package/core/cancel.py +121 -121
  25. package/core/chatgpt_auth.py +747 -747
  26. package/core/claims_view.py +107 -107
  27. package/core/client.py +2715 -2715
  28. package/core/commands.py +460 -454
  29. package/core/compaction.py +1735 -1735
  30. package/core/config_loader.py +1982 -1982
  31. package/core/connect.py +686 -686
  32. package/core/events.py +123 -123
  33. package/core/file_mentions.py +280 -280
  34. package/core/interaction.py +411 -411
  35. package/core/loop.py +2566 -2566
  36. package/core/memory.py +482 -482
  37. package/core/pipeline_models.py +190 -190
  38. package/core/provider_errors.py +234 -234
  39. package/core/reasoning/authorization.py +130 -130
  40. package/core/reasoning/base.py +219 -219
  41. package/core/reasoning/confidence_scoring.py +484 -484
  42. package/core/reasoning/events.py +149 -149
  43. package/core/reasoning/orchestrator.py +1561 -1561
  44. package/core/reasoning/output_writer.py +345 -345
  45. package/core/reasoning/payload_validation.py +524 -524
  46. package/core/reasoning/pipeline_storage.py +427 -427
  47. package/core/reasoning/scholar.py +458 -458
  48. package/core/reasoning/source_corpus.py +433 -433
  49. package/core/reasoning/source_scoring.py +855 -855
  50. package/core/replay.py +315 -315
  51. package/core/shell_sessions.py +1553 -1553
  52. package/credentials.py +307 -307
  53. package/database.py +333 -333
  54. package/docs/PRIVACY.md +78 -78
  55. package/docs/SECURITY.md +108 -108
  56. package/docs/THIRD_PARTY_NOTICES.md +148 -148
  57. package/env_secrets.py +118 -118
  58. package/json_store.py +343 -343
  59. package/logging_setup.py +295 -295
  60. package/main.py +3433 -3433
  61. package/mcp_client/client.py +733 -733
  62. package/mcp_client/config.py +484 -484
  63. package/mcp_client/registration.py +343 -343
  64. package/memories/manager.py +147 -147
  65. package/memories/tui_commands.py +319 -239
  66. package/package.json +303 -303
  67. package/project_init/config_files.py +282 -282
  68. package/project_init/generator.py +728 -728
  69. package/project_init/manifest.py +418 -418
  70. package/project_init/tui_commands.py +147 -147
  71. package/prompts/critic_pass.md +24 -24
  72. package/prompts/revalidate.md +25 -25
  73. package/prompts/revise.md +17 -17
  74. package/prompts/source_grounding.md +66 -66
  75. package/prompts/system_prompts.py +316 -316
  76. package/providers.json.example +94 -94
  77. package/pyproject.toml +149 -149
  78. package/requirements.txt +295 -295
  79. package/safety/policy_enforcement.py +1082 -1082
  80. package/security/askpass.py +419 -419
  81. package/security/capability.py +207 -207
  82. package/security/confine.py +484 -484
  83. package/security/hosted.py +182 -182
  84. package/security/permissions.py +237 -237
  85. package/security/protected_paths.py +501 -501
  86. package/security/sandbox.py +4108 -4108
  87. package/skills/builtin/math/formal-specification.md +67 -67
  88. package/skills/builtin/math/numerical-methods.md +66 -66
  89. package/skills/builtin/research/experiment-design.md +62 -62
  90. package/skills/builtin/research/reproducibility.md +55 -55
  91. package/skills/builtin/research/source-evaluation.md +70 -70
  92. package/skills/builtin/research/statistical-inference.md +63 -63
  93. package/skills/builtin/research/technical-writing.md +59 -59
  94. package/skills/builtin/software/code-review.md +61 -61
  95. package/skills/builtin/software/debugging.md +61 -61
  96. package/skills/builtin/software/test-design.md +67 -67
  97. package/skills/tui_commands.py +110 -110
  98. package/storage.py +1338 -1338
  99. package/tools/base.py +465 -465
  100. package/tools/builtin/_math_common.py +667 -667
  101. package/tools/builtin/_net_common.py +267 -267
  102. package/tools/builtin/arxiv.py +681 -681
  103. package/tools/builtin/fetch_url.py +371 -371
  104. package/tools/builtin/file_ops.py +720 -720
  105. package/tools/builtin/geometry.py +184 -184
  106. package/tools/builtin/load_skill.py +76 -76
  107. package/tools/builtin/pin.py +227 -227
  108. package/tools/builtin/probability_stats.py +224 -224
  109. package/tools/builtin/project_docs.py +464 -464
  110. package/tools/builtin/remember.py +175 -175
  111. package/tools/builtin/shell.py +980 -980
  112. package/tools/builtin/todo.py +149 -149
  113. package/tools/builtin/web_search.py +328 -328
  114. package/tools/context.py +159 -159
  115. package/tools/isolation.py +387 -387
  116. package/tools/registry.py +1242 -1242
  117. package/tui/app.py +8318 -8307
  118. package/tui/app.tcss +747 -739
  119. package/tui/commands.py +26 -26
  120. package/tui/diffs.py +286 -286
  121. package/tui/history.py +128 -128
  122. package/tui/hosted_driver.py +102 -102
  123. package/tui/markdown.py +1329 -1329
  124. package/tui/meters.py +364 -364
  125. package/tui/ravens.py +146 -146
  126. package/tui/screens.py +1255 -1197
  127. package/tui/themes.py +599 -599
  128. package/tui/widgets.py +3813 -3796
package/tui/screens.py CHANGED
@@ -1,1197 +1,1255 @@
1
- """
2
- tui/screens.py
3
-
4
- ROADMAP_v2 §16 modal screens: the permission prompt (AC2) and the thread
5
- picker (§16 AC1), plus §25's research grant picker.
6
-
7
- The permission modal is the load-bearing one. §13 built `permission_channel`
8
- as a plain stdlib queue.Queue precisely so this hand-off works: the worker
9
- thread running _run() blocks on channel.get() while the UI thread shows the
10
- modal, and the user's answer unblocks it. Nothing here is async-aware --
11
- the blocking side is a thread, not a coroutine.
12
-
13
- EVERY RENDERABLE BUILT FROM A NON-LITERAL IS WRAPPED IN `Text(...)`
14
- (batch 42, RA1). Textual parses a `str` as MARKUP, so a square bracket
15
- in a tool argument, a claim, a thread preview or an `ask_user` option
16
- is a tag here -- and these screens exist to show a person exactly what
17
- a model asked for. It was Rich's console markup until the textual pin
18
- moved and is Textual's own grammar now; nothing below changed with it,
19
- which is the point of re-measuring rather than assuming. Two live
20
- failures:
21
-
22
- * `sed -i "s/[/]//" f.txt` in a permission payload
23
- raised MarkupError inside compose(). The screen was pushed and
24
- never rendered, so its dismissal callback never fired and the
25
- worker parked on Queue.get() for ATTENDED_APPROVAL_TIMEOUT_S --
26
- 600s, presenting as a hang. ARCHITECTURE.md records that every
27
- DISMISSAL path must produce a boolean; this is the case that rule
28
- misses, because a screen that cannot render never reaches one.
29
-
30
- * `ReviewScreen`'s title read `[{severity}]`, and `[high]` is a tag.
31
- The severity was silently absent from every review modal since
32
- §20 -- an unconditional defect, needing no adversary at all.
33
-
34
- `markup=False` WORKS NOW AND IS STILL NOT THE FIX, which is a
35
- different sentence from the one that stood here. On textual 1.0.0 the
36
- flag was stored by `__init__` and never read by the `visual`
37
- property, so `Static(x, markup=False)` raised anyway -- measured then.
38
- Since the pin moved it is honoured: `visualize(self, content,
39
- markup=self._render_markup)`, and all four payloads below render
40
- literally -- measured again.
41
-
42
- The wrap stays, for two reasons that outlived the version fact. It
43
- covers `Selection` and `Button`, which take no such flag and both
44
- parse what they are given. And it is one rule for one file, where the
45
- flag would be a per-constructor argument somebody adding the next
46
- screen has to remember -- which is exactly the failure RA1 is.
47
-
48
- What a bare `str` still does on 8.2.8, measured:
49
- `sed -i "s/[/]//" f.txt` raises, `[bold]x` renders as `x`,
50
- `[HIGH] rated` renders as ` rated`, and `[1, 2]` survives intact.
51
- That last one is why the rule cannot be a scan for brackets: the
52
- shapes that fail are not the ones a reader expects to be dangerous.
53
-
54
- A literal written in THIS file is left alone: it is ours and it is
55
- reviewed. The rule is mechanical, so it holds for the next screen
56
- somebody adds -- test_tui.py walks this file's AST and asserts it.
57
- """
58
-
59
- import json
60
-
61
- from rich.text import Text
62
- from textual.app import ComposeResult
63
- from textual.containers import Horizontal, Vertical, VerticalScroll
64
- from textual.screen import ModalScreen
65
- from textual.widgets import (
66
- Button,
67
- Input,
68
- Label,
69
- ListItem,
70
- ListView,
71
- SelectionList,
72
- Static,
73
- )
74
- from textual.widgets.selection_list import Selection
75
-
76
- from core.claims_view import claims_header, render_claims
77
- from core.replay import thread_row
78
-
79
-
80
- class ScrollBox(VerticalScroll):
81
- """A bounded block of text whose overflow can actually be reached
82
- (§46, EP3).
83
-
84
- Two things were wrong with `Static` + `max-height` + `overflow-y`,
85
- and only the first is the one that looks wrong:
86
-
87
- * `Static.can_focus` is False on the pinned textual 1.0.0, so the
88
- scrollbar such a rule produces can only be moved by a mouse.
89
- * A `Static` NEVER reports content taller than its own box --
90
- `virtual_size` follows the clamped box, not the text -- so
91
- `max_scroll_y` was 0 and the hidden rows were not scrolled past,
92
- they were GONE. Measured: nine lines of payload in a seven-row
93
- block, `max_scroll_y == 0`, End does nothing. Making the Static
94
- focusable would have fixed the visible half of that and left the
95
- truncation exactly where it was.
96
-
97
- So the bound belongs on a real scroll container and the text on an
98
- auto-height child inside it.
99
-
100
- THE BOUND IS `height: auto` WITH A `max-height`, NOT A DEFINITE
101
- `height` (batch 49, amending EP3). §46 read the zero it measured as
102
- "a scrollable container asked for `height: auto` resolves to ZERO"
103
- and prescribed a definite height. The zero was EP1's `1fr` ROW.
104
- Measured again with the row `auto`, all three spellings differ and
105
- only one is right:
106
-
107
- 25 lines of payload, grid row `auto`
108
- height: auto box=25, no scroll, BUTTONS OUTSIDE
109
- height: 9 box=9, 16 scrollable, BUTTONS OUT
110
- height: auto; max-height: 9 box=9, 16 scrollable, buttons in
111
- the same three inside a `1fr` row box=0, all three
112
-
113
- A definite height bounds what this box DRAWS and not what its parent
114
- RESERVES, so the row kept growing with the payload and pushed the
115
- Allow/Deny row past the dialog's own `max-height`, where it was
116
- clipped away entirely. `auto` with a `max-height` reports the bound
117
- upward, so the dialog stays inside itself -- and it still shrinks for
118
- a short payload, which a definite height never did.
119
-
120
- Bindings are `ScrollableContainer`'s minus the horizontal ones:
121
- there is nothing to scroll sideways, because the text wraps.
122
- """
123
-
124
-
125
- def asker_label(asked_by, depth) -> list:
126
- """`[Label]` naming the run that raised a question, or `[]` (§47).
127
-
128
- ONE SENTENCE FOR THE THREE MODALS THAT CAN BE ASKED FROM INSIDE A RUN.
129
- §47 gave it to the permission modal alone; batch 75's review found the
130
- sign-off and the model's own question without it, which is where it
131
- matters most now that three children of one turn can each be asking:
132
- three sign-off screens naming the grandchild and nothing about who
133
- asked are three identical screens.
134
-
135
- Empty at depth 0, and that is the right SCOPE rather than a gap: the
136
- asking run is then the conversation you are looking at, which needs no
137
- label.
138
-
139
- Returned as a LIST so a caller splices it into its widget list without
140
- a branch, which is what keeps the placement rule (directly under the
141
- title, above anything the agent wrote) in one shape across the three.
142
-
143
- `Text(...)` for RA1's reason -- an agent name comes from a file whose
144
- author is not necessarily this project.
145
- """
146
- if not asked_by:
147
- return []
148
- return [Label(Text(f"asked by {asked_by} (depth {depth})"),
149
- id="permission-asker")]
150
-
151
-
152
- class PermissionScreen(ModalScreen[bool]):
153
- """Approve or deny one tool call. Dismisses with the decision.
154
-
155
- The payload is shown FULL and UNREDACTED: the user must see the exact
156
- path/command/URL they are being asked to authorise, and truncation or
157
- redaction here would make the consent uninformed (the param_digest
158
- truncation is for the transcript only). Logs redact via
159
- logging_setup._RedactingFormatter and safety/policy_enforcement's
160
- check_output_policy, so the full value never reaches disk unguarded —
161
- do not add redaction here to "match" the transcript.
162
-
163
- Full and unredacted, and NOT INTERPRETED: the payload goes
164
- through `Text(...)` so a bracket in a command stays a bracket.
165
- Showing the exact value is this screen's whole purpose, and
166
- markup parsing is a way of showing something else -- see the
167
- module docstring.
168
-
169
- THE RATIONALE IS NOT EVIDENCE (§42, RA6). It is the agent's own
170
- sentence about its own call, so it is unverifiable by
171
- construction: an agent that has been steered writes a reassuring
172
- one, and that is the case this screen exists for. It is labelled
173
- as a claim and placed BELOW the notice, which the harness
174
- computed, so nobody reads the harness as vouching for it. What it
175
- is actually for is longitudinal -- a thread's worth of stated
176
- reasons, archived beside the calls, is a drift signal no single
177
- prompt can be.
178
-
179
- THE SUBJECT OF THE QUESTION IS PINNED, OUTSIDE THE SCROLL (§46,
180
- EP1). RA6 ordered three things -- the harness's notice, the agent's
181
- claim, the payload -- and the command is none of them: it is what
182
- all three are ABOUT. Ranked among them it came last, inside the
183
- payload, which is how a user came to report that the command was
184
- visible in the transcript and nowhere on the modal asking about it.
185
- The payload keeps RA6's order intact below; the headline is lifted
186
- out of the ranking, not moved up it.
187
-
188
- What the investigation actually found is worse than the ordering,
189
- and it is recorded here because the obvious reading of the report
190
- was wrong. `#permission-params` sat in a `1fr` grid row inside a
191
- `height: auto` dialog, and a fractional row in an auto-height
192
- container resolves to ZERO. Measured against HEAD in a worktree:
193
- `region.height == 0`, `virtual_size.height == 0`, nine lines of
194
- content. The notice, the agent's stated reason and the payload were
195
- not clipped and scrollable -- they were absent, from every
196
- permission modal this app has ever shown, for every tool. The
197
- command was merely the part somebody noticed was missing.
198
-
199
- Nothing caught it because every assertion about this screen reads
200
- the widget's own VISUAL -- the string it was built from, which a
201
- widget of zero height still reports in full. §46's tests assert on
202
- the rendered REGION for that reason.
203
-
204
- The headline is DISPLAY ONLY and is also inside `params`, which is
205
- still rendered whole below it. That duplication is deliberate for
206
- the reason the rationale's is: this screen shows the payload
207
- entire, and the pinned copy is a placement, not a substitution. A
208
- reader comparing the two is doing something useful.
209
- """
210
-
211
- BINDINGS = [("escape", "deny", "Deny")]
212
-
213
- def __init__(self, tool_name: str, params: dict, notice: str = None,
214
- rationale: str = None, headline: str = None,
215
- asked_by: str = None, depth: int = 0):
216
- super().__init__()
217
- self._tool_name = tool_name
218
- self._params = params
219
- # ROADMAP_v2 §47. WHICH run raised this question, when it was
220
- # not the conversation itself. A subagent's approvals have
221
- # always surfaced here -- the channel is inherited -- and the
222
- # modal said only which TOOL was asked for, so "Allow shell?"
223
- # over a chat turn and over a nested agent two levels down
224
- # were the same screen.
225
- #
226
- # None for a top-level turn, and that is the right scope
227
- # rather than a gap: the asking run is then the conversation
228
- # you are looking at, which needs no label. It becomes
229
- # load-bearing when two questions can be pending at once,
230
- # which is why it is a prerequisite for §47's last slice
231
- # rather than a nicety.
232
- self._asked_by = asked_by
233
- self._depth = depth
234
- # §46 (EP2). What this call is asking to DO -- for `shell`, the
235
- # command. Resolved by the registry from whichever param the
236
- # tool declared and passed in already a string, for the reason
237
- # the rationale is: this module imports nothing from the rest
238
- # of the project. None for every tool that declares no
239
- # headline, and the pinned block simply does not render.
240
- self._headline = headline
241
- # §42 (RA6). The agent's OWN account of why it wants this call,
242
- # resolved by the registry from whichever param the tool
243
- # declared. Passed in rather than looked up: this module
244
- # imports nothing from the rest of the project and that is
245
- # worth more than saving a parameter.
246
- self._rationale = rationale
247
- # Supplied by the tool via ToolSpec.approval_notice, not composed
248
- # here: what approving authorises is the TOOL's knowledge.
249
- # spawn_subagent uses it to list the tools the subagent could then
250
- # run unprompted, which the params alone never say.
251
- # DISPLAYED FULL above — see class docstring for why this stays
252
- # unredacted while the transcript's `▸` digest and the log do not.
253
- self._notice = notice
254
-
255
- def compose(self) -> ComposeResult:
256
- try:
257
- rendered = json.dumps(self._params, indent=2, default=str)
258
- except (TypeError, ValueError):
259
- rendered = repr(self._params)
260
- # HARNESS FACT, THEN AGENT CLAIM, THEN EVIDENCE (§42, RA6).
261
- # The notice is computed -- `classify_command` decided it --
262
- # so it is read before any reassurance the model wrote. The
263
- # payload stays last and stays whole; the rationale appears in
264
- # it as well, and that duplication is the honest cost of
265
- # surfacing the field without breaking the rule above that
266
- # this screen shows the payload entire.
267
- reason = self._rationale or "(none given)"
268
- rendered = (f"Agent's stated reason (its own words, unverified):\n"
269
- f" {reason}\n\n{rendered}")
270
- if self._notice:
271
- rendered = f"{self._notice}\n\n{rendered}"
272
- widgets = [Label(Text(f"Allow {self._tool_name}?"),
273
- id="permission-title")]
274
- # DIRECTLY under the title, above the headline and everything the
275
- # agent wrote: RA6's ordering says a harness fact is read before an
276
- # agent's claim, and which run is asking is the most harness-y fact
277
- # on the screen. See `asker_label` for the rest.
278
- widgets.extend(asker_label(self._asked_by, self._depth))
279
- if self._headline:
280
- # `Text(...)` is not optional here (batch 42, RA1). This is
281
- # the most attacker-influenced string on the screen -- a
282
- # model-authored command shown so a person can vet it --
283
- # and `Static` renders a `str` through `Text.from_markup`,
284
- # so `sed -i "s/[/]//" f.txt` would raise MarkupError
285
- # inside compose(), leaving the screen pushed, unrendered
286
- # and its dismissal callback never fired. test_tui.py walks
287
- # this file's AST and asserts the wrapping.
288
- widgets.append(ScrollBox(
289
- Static(Text(self._headline), id="permission-command"),
290
- id="permission-command-box"))
291
- # The id stays on the STATIC and the scroll container is a
292
- # `-box` sibling, rather than the other way round: a stylesheet
293
- # wants the bound and the overflow, which belong to the
294
- # container, while every assertion in test_rationale.py and
295
- # test_tui.py asks what text was DRAWN, which only the Static
296
- # can answer. Moving the id outward would make
297
- # `query_one("#permission-params")` return a container with no
298
- # `visual` -- and reading that attribute is how batch 42's
299
- # markup bug was caught.
300
- widgets.append(ScrollBox(
301
- Static(Text(rendered), id="permission-params"),
302
- id="permission-params-box"))
303
- # ONE bar, centred, holding both answers (batch 49). Two
304
- # Buttons in a two-column Grid sat at the LEFT of their columns,
305
- # so a 16-wide Deny left ~22 dead columns beside it while Allow
306
- # was flush against the padding -- the dialog was centred and its
307
- # contents were not. A Horizontal with `align: center middle`
308
- # centres the pair as a unit and keeps both answers the same
309
- # size, which the alternative (each button filling its half) does
310
- # not: it would make the permissive answer a target half the
311
- # width of the modal.
312
- widgets.append(Horizontal(
313
- Button("Allow", variant="success", id="allow"),
314
- Button("Deny", variant="error", id="deny"),
315
- id="permission-buttons"))
316
- # A Vertical, not a Grid (batch 49). Every child spanned both
317
- # columns, so the second column only ever held the Deny button --
318
- # and the `with-headline` class existed solely to carry a ROW
319
- # COUNT to the stylesheet, because a Grid's `grid-size` is static
320
- # and this screen composes three children or four. A Vertical
321
- # does not care how many there are, so the template it guarded
322
- # against getting wrong is gone rather than documented.
323
- yield Vertical(*widgets, id="permission-dialog")
324
-
325
- def on_mount(self) -> None:
326
- # ENTER DECLINES (batch 49). Focus lands on the first focusable
327
- # widget otherwise, which is whichever ScrollBox composed first --
328
- # so Enter did nothing here, and on ConfirmScreen, whose body is a
329
- # plain Static, it said YES. The convenient action must not be the
330
- # permissive one; that is already the recorded reason
331
- # GrantPickerScreen ships every option unticked, and it applies
332
- # with more force to a key a person presses without looking.
333
- self.query_one("#deny", Button).focus()
334
-
335
- def on_button_pressed(self, event: Button.Pressed) -> None:
336
- self.dismiss(event.button.id == "allow")
337
-
338
- def action_deny(self) -> None:
339
- # Escape answers with the SAME value the No button produces.
340
- # Since §23 a dismissal carrying None would be safe anyway --
341
- # interaction.decode supplies APPROVAL's declining default -- so
342
- # this is explicitness rather than hang-prevention: one screen
343
- # should not have two ways to say no.
344
- self.dismiss(False)
345
-
346
-
347
- class GrantPickerScreen(ModalScreen[object]):
348
- """Pick which approval-gated tools a research run may use (§25 R1).
349
-
350
- Dismisses with a set of names, or None to cancel the run entirely --
351
- the two are different answers. An empty SET means "run with no grants"
352
- (a legitimate choice: the pipeline just keeps hiding gated tools),
353
- while None means "I did not mean to start this at all".
354
-
355
- Per-tool rather than one prompt for the whole set, and each row shows
356
- what the tool says it does, because the harness cannot tell a
357
- read-only tool from one that writes or sends -- MCP exposes no such
358
- metadata. The description and the individual choice are the entire
359
- substance of informed consent here.
360
- """
361
-
362
- BINDINGS = [("escape", "cancel", "Cancel")]
363
-
364
- def __init__(self, offered: list):
365
- super().__init__()
366
- self._offered = list(offered)
367
-
368
- def compose(self) -> ComposeResult:
369
- # Every option starts UNSELECTED. A pre-ticked list would make the
370
- # convenient action the permissive one, and this prompt exists
371
- # precisely because nobody will be watching afterwards.
372
- options = [
373
- Selection(Text(f"{name} — {description}" if description
374
- else name),
375
- name, False)
376
- for name, description in self._offered
377
- ]
378
- yield Vertical(
379
- Label("Authorise for this run only", id="grant-title"),
380
- Static(
381
- "These tools need approval, and nothing can give it during "
382
- "an unattended run.\nSpace toggles, Enter confirms, Escape "
383
- "cancels the run. Nothing is saved.",
384
- id="grant-help"),
385
- SelectionList(*options, id="grant-list"),
386
- # A bar with one button in it. NO focus call here and none on
387
- # ProjectKindScreen: neither screen HAS a declining button --
388
- # escape is the decline on both -- so there is nothing to
389
- # focus that would make Enter safe, and focusing the
390
- # affirmative one for consistency would be the exact
391
- # inversion PermissionScreen.on_mount exists to prevent.
392
- Horizontal(
393
- Button("Run with selected", variant="success",
394
- id="grant-ok"),
395
- id="grant-buttons"),
396
- id="grant-dialog",
397
- )
398
-
399
- def on_button_pressed(self, event: Button.Pressed) -> None:
400
- self.dismiss(set(self.query_one("#grant-list", SelectionList).selected))
401
-
402
- def action_cancel(self) -> None:
403
- self.dismiss(None)
404
-
405
-
406
- class SubagentSignoffScreen(ModalScreen[object]):
407
- """Pick which of a subagent's gated tools it may use unprompted
408
- (ROADMAP_v2 §23 AC1b).
409
-
410
- Modelled on GrantPickerScreen, and dismissing with the same THREE
411
- answers for the same reason: a set of names grants those, an EMPTY set
412
- spawns the agent with nothing granted, and None refuses the spawn
413
- outright. Those are three different intentions and a bool cannot hold
414
- them -- which is precisely why §18 shipped this all-or-nothing (S1)
415
- on a boolean channel, and why it could only be built once §23 gave the
416
- channel a typed answer.
417
-
418
- Every option starts UNSELECTED. A pre-ticked list makes the convenient
419
- action the permissive one, and the point of this prompt is that
420
- approving a spawn used to authorise the child's ENTIRE gated set.
421
- """
422
-
423
- BINDINGS = [("escape", "refuse", "Refuse")]
424
-
425
- def __init__(self, agent: str, candidates: list, asked_by: str = None,
426
- depth: int = 0):
427
- super().__init__()
428
- self._agent = agent
429
- self._candidates = list(candidates)
430
- # §47, extended by batch 75's review. WHICH run wants to spawn
431
- # this one -- a different agent from `self._agent`, which is the
432
- # one about to be spawned. It matters more here than on the
433
- # permission modal: three children of one turn each spawning a
434
- # grandchild produce three of these screens, and without this they
435
- # name the grandchild and nothing else, so they are identical.
436
- self._asked_by = asked_by
437
- self._depth = depth
438
-
439
- def compose(self) -> ComposeResult:
440
- if not self._candidates:
441
- yield Vertical(
442
- Label(Text(f"Run {self._agent}?"),
443
- id="permission-title"),
444
- *asker_label(self._asked_by, self._depth),
445
- Static(Text(f"{self._agent} needs no approval-gated "
446
- f"tools."),
447
- id="permission-params"),
448
- Horizontal(
449
- Button("Run", variant="success", id="signoff-none"),
450
- Button("Refuse", variant="error", id="signoff-refuse"),
451
- id="permission-buttons"),
452
- id="permission-dialog",
453
- )
454
- return
455
- options = [Selection(Text(name), name, False)
456
- for name in self._candidates]
457
- yield Vertical(
458
- Label(Text(f"What may {self._agent} use without asking again?"),
459
- id="grant-title"),
460
- # BOTH branches, because either can be reached from inside a
461
- # run -- the no-candidates one is what a nested spawn of an
462
- # agent with no gated tools shows.
463
- *asker_label(self._asked_by, self._depth),
464
- Static(
465
- "Space toggles, then choose. Anything left unticked still "
466
- "prompts you if the subagent tries it.\nRunning with none "
467
- "selected is fine. Escape refuses the spawn entirely.",
468
- id="grant-help"),
469
- SelectionList(*options, id="signoff-list"),
470
- Horizontal(
471
- Button("Run with selected", variant="success",
472
- id="signoff-ok"),
473
- Button("Refuse the spawn", variant="error",
474
- id="signoff-refuse"),
475
- id="grant-buttons"),
476
- id="grant-dialog",
477
- )
478
-
479
- def on_mount(self) -> None:
480
- # The refusal, on both branches -- see PermissionScreen.on_mount.
481
- self.query_one("#signoff-refuse", Button).focus()
482
-
483
- def on_button_pressed(self, event: Button.Pressed) -> None:
484
- if event.button.id == "signoff-refuse":
485
- self.dismiss(None)
486
- elif event.button.id == "signoff-none":
487
- self.dismiss(set())
488
- else:
489
- self.dismiss(
490
- set(self.query_one("#signoff-list", SelectionList).selected))
491
-
492
- def action_refuse(self) -> None:
493
- # Escape REFUSES rather than running with nothing granted. The two
494
- # are different answers, and the one a user reaches for when they
495
- # did not mean to start this is the refusal.
496
- self.dismiss(None)
497
-
498
-
499
- class QuestionScreen(ModalScreen[object]):
500
- """Ask the user the model's question (§23 slice 2, AC2).
501
-
502
- Dismisses with a dict, or None. THREE answers, and the middle one is
503
- the one to lose -- the same distinction SubagentSignoffScreen draws:
504
-
505
- None nobody answered. Escape, and the app's
506
- shutdown release.
507
- {"defer": True} "let's talk about it instead". A REAL
508
- answer: the user engaged and declined to
509
- pick, which tells the model something that
510
- closing the modal does not.
511
- {"options": [...], what they chose, what they typed, or both.
512
- "text": "..."}
513
-
514
- Four affordances, all four from the spec. Options are a SelectionList
515
- when several may be chosen and Buttons when only one may -- a
516
- single-select SelectionList would let a user tick three and then be
517
- told only one counted, which is a worse lie than not offering it.
518
-
519
- UNSELECTED and EMPTY to start, like every other picker here. The
520
- convenient action must not be the one that answers on the user's
521
- behalf, and this modal exists precisely because the model does not
522
- know the answer.
523
-
524
- The screen does NOT validate. Whether a returned option was actually
525
- offered is core.interaction.decode's job, which is why it takes the
526
- request -- ProjectKindScreen made the same move for the same reason.
527
- """
528
-
529
- BINDINGS = [("escape", "dismiss_unanswered", "No answer")]
530
-
531
- def __init__(self, question: str, options=(), multi_select: bool = False,
532
- allow_text: bool = True, asked_by: str = None,
533
- depth: int = 0):
534
- super().__init__()
535
- self._question = question
536
- self._options = list(options)
537
- self._multi = bool(multi_select)
538
- self._allow_text = bool(allow_text)
539
- # §47, added by batch 75's review. "The assistant has a question"
540
- # is the right title for a chat turn and an understatement for a
541
- # subagent two levels down, whose question surfaces on the parent's
542
- # screen exactly as its approvals do.
543
- self._asked_by = asked_by
544
- self._depth = depth
545
-
546
- def compose(self) -> ComposeResult:
547
- # The question is the MODEL's, so its length is the one thing
548
- # this screen does not choose -- bounded and scrollable for the
549
- # same reason the payload block is.
550
- widgets = [Label("The assistant has a question", id="question-title"),
551
- *asker_label(self._asked_by, self._depth),
552
- ScrollBox(Static(Text(self._question), id="question-body"),
553
- id="question-body-box")]
554
-
555
- if self._options and self._multi:
556
- widgets.append(Static(
557
- "Space toggles; several may be chosen.", id="question-help"))
558
- widgets.append(SelectionList(
559
- *[Selection(Text(o), o, False) for o in self._options],
560
- id="question-list"))
561
- widgets.append(
562
- Button("Answer", variant="success", id="question-ok"))
563
- elif self._options:
564
- # Bounded and scrollable, like the multi-select branch's
565
- # SelectionList beside it (batch 49). Unbounded, four options
566
- # of two lines each cost 16 of the dialog's 18 rows and took
567
- # the Answer button and Discuss instead off the bottom with
568
- # them. The Buttons are also FIXED WIDTH in the stylesheet:
569
- # at `width: auto` an option wider than the dialog was
570
- # CLIPPED, and the same label at `width: 100%` wraps to two
571
- # centred lines instead.
572
- #
573
- # `Text(option)` for batch 42's reason (RA1), which had
574
- # not reached a Button: these are the MODEL's words, and
575
- # measured on both the old pin and the new one, a
576
- # `Button` given a `str` sends it through markup parsing
577
- # and raises on an unbalanced tag -- inside compose(), so
578
- # the screen is pushed and never drawn. The multi-select
579
- # branch above already wraps its `Selection`; this branch
580
- # simply had not.
581
- widgets.append(ScrollBox(
582
- *[Button(Text(option), variant="primary",
583
- id=f"question-opt-{index}")
584
- for index, option in enumerate(self._options)],
585
- id="question-options"))
586
-
587
- if self._allow_text:
588
- widgets.append(Input(
589
- placeholder="…or write your own answer",
590
- id="question-text"))
591
- if not (self._options and self._multi):
592
- # A submit button for the typed answer. The multi-select
593
- # branch already has one, and the single-select branch's
594
- # option Buttons read the Input too -- but an open question
595
- # with no options at all would otherwise have no way to
596
- # submit anything.
597
- widgets.append(
598
- Button("Answer", variant="success", id="question-ok"))
599
-
600
- # Always last, always available: the spec's escape is an answer the
601
- # user can give on purpose, not only a thing that happens when they
602
- # close the window. In the bar rather than beside it, so it cannot
603
- # be the child that falls off the bottom -- which is exactly what
604
- # it was.
605
- trailing = [w for w in widgets if getattr(w, "id", "") == "question-ok"]
606
- for widget in trailing:
607
- widgets.remove(widget)
608
- widgets.append(Horizontal(
609
- *trailing,
610
- Button("Discuss instead", variant="default", id="question-defer"),
611
- id="question-buttons"))
612
- yield Vertical(*widgets, id="question-dialog")
613
-
614
- def on_mount(self) -> None:
615
- # The first OPTION, which is where focus landed before the options
616
- # gained a ScrollBox around them -- a scroll container is focusable
617
- # and would otherwise take it. NOT the declining button: this
618
- # screen authorises nothing, so there is no permissive answer for
619
- # Enter to give, and the whole point of it is that the model does
620
- # not know which option is right.
621
- for candidate in ("#question-opt-0", "#question-list",
622
- "#question-text", "#question-defer"):
623
- found = self.query(candidate)
624
- if found:
625
- found.first().focus()
626
- return
627
-
628
- def _typed(self) -> str:
629
- if not self._allow_text:
630
- return ""
631
- # Read on EVERY path, like ReviewScreen's note: a user who ticks an
632
- # option and qualifies it in the box has given one answer, and
633
- # dropping half of it because they pressed the wrong button first
634
- # would be silent.
635
- try:
636
- return self.query_one("#question-text", Input).value.strip()
637
- except Exception: # noqa: BLE001 -- absent when allow_text is False
638
- return ""
639
-
640
- def on_button_pressed(self, event: Button.Pressed) -> None:
641
- button_id = event.button.id or ""
642
- if button_id == "question-defer":
643
- self.dismiss({"defer": True})
644
- return
645
-
646
- chosen = []
647
- if button_id.startswith("question-opt-"):
648
- index = int(button_id.rsplit("-", 1)[1])
649
- chosen = [self._options[index]]
650
- self._answer(chosen)
651
-
652
- def on_input_submitted(self, event: Input.Submitted) -> None:
653
- # Enter in the text box answers (batch 49). Textual posts this and
654
- # nothing handled it, so the one affordance whose entire purpose
655
- # is being typed into had no way to send what was typed -- and the
656
- # Answer button it needed instead was the child clipped off the
657
- # bottom. Through `_answer`, not a second dismissal: one shape of
658
- # answer, one place that builds it.
659
- self._answer([])
660
-
661
- def _answer(self, chosen: list) -> None:
662
- if self._options and self._multi:
663
- chosen = list(
664
- self.query_one("#question-list", SelectionList).selected)
665
- self.dismiss({"options": chosen, "text": self._typed()})
666
-
667
- def action_dismiss_unanswered(self) -> None:
668
- # None, NOT a deferral. Escape means "I am not dealing with this";
669
- # "Discuss instead" means "I want to talk about it". The tool says
670
- # different things to the model about each, so collapsing them here
671
- # would make the button pointless.
672
- self.dismiss(None)
673
-
674
-
675
- class ReviewScreen(ModalScreen[object]):
676
- """Decide one proposed correction to a finished research run (§20 V4).
677
-
678
- Dismisses with a (decision, notes) tuple. Every dismissal path carries
679
- one -- escape, the buttons, and the app's shutdown release -- because
680
- the /research worker is blocked on a queue that must receive AN
681
- answer. What the answer is matters less than that it arrives:
682
- interaction.decode turns anything unusable (None, a bare False from
683
- shutdown, malformed junk) into REVIEW's declining default, so a new
684
- path added later fails safe -- an edit is never applied because
685
- nobody answered.
686
-
687
- Four outcomes, not two. Reject and refine are different answers: "this
688
- is wrong" ends the finding, while "you missed something" sends it back
689
- with a note. And "reject the rest" is the escape a long review needs,
690
- safe by construction because it only ever declines -- the affordance
691
- that must NOT exist is the one that accepts in bulk.
692
- """
693
-
694
- BINDINGS = [("escape", "reject", "Reject")]
695
-
696
- def __init__(self, finding: dict, round_index: int = 0,
697
- max_rounds: int = 0):
698
- super().__init__()
699
- self._finding = finding
700
- self._round = round_index
701
- self._max_rounds = max_rounds
702
-
703
- def compose(self) -> ComposeResult:
704
- kind = self._finding.get("kind", "?")
705
- target = self._finding.get("claim_id") or "the report"
706
- severity = self._finding.get("severity", "unknown")
707
- body = (
708
- f"Why: {self._finding.get('reason', '(no reason given)')}\n\n"
709
- f"Proposed: {self._finding.get('proposed')}"
710
- )
711
- if self._round:
712
- body = (f"(refinement {self._round} of {self._max_rounds})\n\n"
713
- f"{body}")
714
- yield Vertical(
715
- # `[{severity}]` is a MARKUP TAG to Rich, so this title
716
- # rendered WITHOUT its severity on every review modal from
717
- # §20 until batch 42 -- `[high]` parsed as an unknown
718
- # style over a zero-width span. The brackets are wanted
719
- # here; the parsing never was.
720
- Label(Text(f"{kind} correction to {target} [{severity}]"),
721
- id="review-title"),
722
- ScrollBox(Static(Text(body), id="review-body"),
723
- id="review-body-box"),
724
- Input(placeholder="Note for the reviewer (used by Refine)",
725
- id="review-note"),
726
- # FOUR buttons in ONE row (batch 49). Stacked they cost 12 of
727
- # the 18 rows a dialog has on an 80x24 terminal, so the body
728
- # and the note pushed three of the four decisions off the
729
- # bottom -- Refine, Reject and Reject the rest, which is to
730
- # say every answer except Accept. Measured at 65 columns of
731
- # buttons in 70, so they fit the floor as a row.
732
- Horizontal(
733
- Button("Accept", variant="success", id="review-accept"),
734
- Button("Refine", variant="primary", id="review-refine"),
735
- Button("Reject", variant="error", id="review-reject"),
736
- Button("Reject the rest", variant="error",
737
- id="review-reject-all"),
738
- id="review-buttons"),
739
- id="review-dialog",
740
- )
741
-
742
- def on_mount(self) -> None:
743
- # The declining answer, like every other consent surface here --
744
- # see PermissionScreen.on_mount. `reject` and not `reject_all`:
745
- # both decline, and only one of them declines everything else too.
746
- self.query_one("#review-reject", Button).focus()
747
-
748
- def on_button_pressed(self, event: Button.Pressed) -> None:
749
- decisions = {
750
- "review-accept": "accept",
751
- "review-refine": "refine",
752
- "review-reject": "reject",
753
- "review-reject-all": "reject_all",
754
- }
755
- note = self.query_one("#review-note", Input).value.strip()
756
- self.dismiss((decisions[event.button.id], note))
757
-
758
- def action_reject(self) -> None:
759
- # Escape declines rather than dismissing with no value, for the
760
- # same reason PermissionScreen's escape denies.
761
- self.dismiss(("reject", ""))
762
-
763
-
764
- class ClaimsScreen(ModalScreen[None]):
765
- """Every claim a research run produced, with the metadata that decided
766
- its tier (ROADMAP_v2 §26).
767
-
768
- The report a run ends with is a synthesis. What it was synthesised
769
- FROM -- which assertions were extracted, which were grounded and by
770
- how many sources, which carried unexamined assumptions, which were
771
- revised and how often, and what arithmetic produced each tier -- all
772
- exists on every Claim and reaches /output/<run_id>/, and none of it was
773
- reachable from either shell. So a run could be read only as prose,
774
- with the confidence machinery that is the point of the pipeline
775
- visible nowhere.
776
-
777
- A MODAL rather than transcript rows: a dozen claims at this detail is
778
- longer than the report, and dumping it inline would push the answer
779
- off screen at the moment it arrives. Scrollable, escape closes.
780
-
781
- Takes plain DICTS, not Claim objects, and that is deliberate -- the
782
- three sources are `vars(c)` for a finished in-session run,
783
- pipeline_storage.load_pipeline_run() for an earlier one (which already
784
- returns the dicts vars(c) wrote), and the partial picture assembled
785
- from PipelineEvents while a run is still going. One shape here means
786
- no branch inside the renderer, and it is the shape §5 already
787
- persists.
788
- """
789
-
790
- BINDINGS = [("escape", "close", "Close")]
791
-
792
- def __init__(self, claims: list, title: str = "Claims",
793
- partial: bool = False):
794
- super().__init__()
795
- self._claims = list(claims or [])
796
- self._title = title
797
- self._partial = partial
798
-
799
- def compose(self) -> ComposeResult:
800
- # core/claims_view.py says what the view shows (§89), so the
801
- # CLI's /claims and this screen cannot disagree about a run.
802
- header = claims_header(self._title, len(self._claims),
803
- self._partial)
804
- yield Vertical(
805
- Label(Text(header), id="claims-title"),
806
- # A ScrollBox, not a `max-height` Static (batch 49). EP3's
807
- # second rule was right about this one: a Static's
808
- # virtual_size follows its clamped box, so a run with more
809
- # claims than fit had the remainder GONE rather than below
810
- # the fold, on the one screen whose entire purpose is showing
811
- # all of them.
812
- ScrollBox(Static(Text(render_claims(self._claims)),
813
- id="claims-body"),
814
- id="claims-body-box"),
815
- id="claims-dialog",
816
- )
817
-
818
- def action_close(self) -> None:
819
- self.dismiss(None)
820
-
821
-
822
- class ConfirmScreen(ModalScreen[bool]):
823
- """A titled yes/no over a block of text (ROADMAP_v2 §24).
824
-
825
- PermissionScreen is the wrong shape here even though it also returns a
826
- bool: it titles itself "Allow <tool>?" and renders params as JSON,
827
- because it exists to gate ONE tool call. /init's question is about a
828
- set of files, and the substance is the diff -- so the body is text the
829
- caller composed and the title says what is being decided.
830
-
831
- Escape declines rather than dismissing with no value. Fifth place that
832
- invariant applies, and here the unsafe failure is a worker parked on a
833
- queue nobody will answer.
834
- """
835
-
836
- BINDINGS = [("escape", "decline", "No")]
837
-
838
- def __init__(self, title: str, body: str, confirm_label: str = "Yes"):
839
- super().__init__()
840
- self._title = title
841
- self._body = body
842
- self._confirm_label = confirm_label
843
-
844
- def compose(self) -> ComposeResult:
845
- yield Vertical(
846
- Label(Text(self._title), id="permission-title"),
847
- # The body is a DIFF (/init's file list), so it is the one
848
- # here most able to outgrow the dialog -- 30 files measured at
849
- # 36 rows of content in a 16-row box, which took both buttons
850
- # off the bottom with it. Bounded and scrollable like the
851
- # payload block, for the same reason.
852
- ScrollBox(Static(Text(self._body), id="permission-params"),
853
- id="permission-params-box"),
854
- Horizontal(
855
- Button(Text(self._confirm_label), variant="success",
856
- id="allow"),
857
- Button("No", variant="error", id="deny"),
858
- id="permission-buttons"),
859
- id="permission-dialog",
860
- )
861
-
862
- def on_mount(self) -> None:
863
- # See PermissionScreen.on_mount. This screen is where Enter
864
- # actually said yes: its body was a plain Static, so the
865
- # affirmative button was the first focusable widget on it.
866
- self.query_one("#deny", Button).focus()
867
-
868
- def on_button_pressed(self, event: Button.Pressed) -> None:
869
- self.dismiss(event.button.id == "allow")
870
-
871
- def action_decline(self) -> None:
872
- self.dismiss(False)
873
-
874
-
875
- class NoticeScreen(ModalScreen[None]):
876
- """Something to read and acknowledge, with one button (ROADMAP_v3 §83,
877
- CG8).
878
-
879
- OpenAI's guidelines for Sign in with ChatGPT ask for a notice the first
880
- time someone signs in with plan usage on: that eligible requests use
881
- their ChatGPT plan and that usage is managed in ChatGPT's settings,
882
- titled "You're using your ChatGPT plan", with "Got it". There is no
883
- decision in it, so it is not a ConfirmScreen with the No hidden: Enter,
884
- Escape and the button all mean the one thing it can mean.
885
- """
886
-
887
- BINDINGS = [("escape", "acknowledge", "Got it")]
888
-
889
- def __init__(self, title: str, body: str, button_label: str = "Got it"):
890
- super().__init__()
891
- self._title = title
892
- self._body = body
893
- self._button_label = button_label
894
-
895
- def compose(self) -> ComposeResult:
896
- yield Vertical(
897
- Label(Text(self._title), id="permission-title"),
898
- ScrollBox(Static(Text(self._body), id="permission-params"),
899
- id="permission-params-box"),
900
- Horizontal(
901
- Button(Text(self._button_label), variant="primary",
902
- id="notice-ok"),
903
- id="permission-buttons"),
904
- id="permission-dialog",
905
- )
906
-
907
- def on_mount(self) -> None:
908
- self.query_one("#notice-ok", Button).focus()
909
-
910
- def on_button_pressed(self, event: Button.Pressed) -> None:
911
- self.dismiss(None)
912
-
913
- def action_acknowledge(self) -> None:
914
- self.dismiss(None)
915
-
916
-
917
- class ProjectKindScreen(ModalScreen[object]):
918
- """Which document set /init scaffolds (§24, I13).
919
-
920
- Dismisses with "software", "research", or None to cancel -- three
921
- answers, not a bool, because cancelling is not the same as picking the
922
- other one.
923
-
924
- An established project arrives here with a PROPOSAL and the reason for
925
- it, so the user is confirming a finding. A blank folder arrives with
926
- neither: there is nothing to infer from, and a proposal would be a
927
- guess wearing a finding's clothes.
928
- """
929
-
930
- BINDINGS = [("escape", "cancel", "Cancel")]
931
-
932
- def __init__(self, proposal=None, reason: str = "", blank: bool = False):
933
- super().__init__()
934
- self._proposal = proposal
935
- self._reason = reason
936
- self._blank = blank
937
-
938
- def compose(self) -> ComposeResult:
939
- if self._blank:
940
- explanation = ("This folder is empty, so there is nothing to go "
941
- "on. Which kind of project is this?")
942
- elif self._proposal:
943
- explanation = (f"This looks like a {self._proposal} project — "
944
- f"{self._reason}. Change it if that is wrong.")
945
- else:
946
- explanation = "Which kind of project is this?"
947
- yield Vertical(
948
- Label("Set up documentation for which kind of project?",
949
- id="permission-title"),
950
- ScrollBox(Static(
951
- Text(
952
- f"{explanation}\n\n"
953
- "software — ARCHITECTURE, ROADMAP, DEVLOG, "
954
- "TECHNICAL_DEBT, DOCUMENTATION_STANDARDS, "
955
- "TEST_WRITING, BREAKING_CHANGES\n"
956
- "research — RESEARCH_QUESTIONS, METHODOLOGY, "
957
- "SOURCES, FINDINGS, LIMITATIONS, EXPERIMENT_LOG, "
958
- "OPEN_QUESTIONS, DOCUMENTATION_STANDARDS"),
959
- id="permission-params"),
960
- id="permission-params-box"),
961
- Horizontal(
962
- Button("Software", variant="success", id="kind-software"),
963
- Button("Research", variant="primary", id="kind-research"),
964
- id="permission-buttons"),
965
- id="permission-dialog",
966
- )
967
-
968
- def on_button_pressed(self, event: Button.Pressed) -> None:
969
- self.dismiss("research" if event.button.id == "kind-research"
970
- else "software")
971
-
972
- def action_cancel(self) -> None:
973
- self.dismiss(None)
974
-
975
-
976
- class AgentPickerScreen(ModalScreen[object]):
977
- """Pick a run to read. Dismisses with a thread id, or None (§47).
978
-
979
- THE KEYBOARD ROUTE to what the sidebar offers on a click. The
980
- sidebar is deliberately not focusable -- batch 59 refused a tab
981
- stop and refused to take the arrow keys the suggestion panel
982
- uses -- so making its rows clickable made navigation reachable by
983
- mouse only. A key-bound picker keeps the panel as it is and
984
- mirrors ctrl+t, which is already this project's answer to
985
- "choose a thread".
986
-
987
- Only runs that HAVE a thread are listed. A row for one that
988
- cannot be opened would be a control that does nothing, which is
989
- the rule the sidebar's unbound rows already follow.
990
- """
991
-
992
- BINDINGS = [("escape", "cancel", "Cancel")]
993
-
994
- def __init__(self, runs: list[dict]):
995
- super().__init__()
996
- self._runs = runs
997
-
998
- def compose(self) -> ComposeResult:
999
- items = [
1000
- # Indented by the LINEAGE LEVEL the app read off
1001
- # `widgets.lineage_rows`, which is the walk the sidebar
1002
- # indents by -- not `AgentRow.depth`, which is the spawn
1003
- # bound and parts company with the column wherever a span
1004
- # adds a display level without adding a spawn level.
1005
- # `Text(...)` for RA1's reason: an agent name comes from a
1006
- # file this project did not necessarily write. Finished
1007
- # runs read muted: they open like any other row, so the
1008
- # mark is de-emphasis rather than a warning, and `live`
1009
- # defaults True so a hand-built row renders as running.
1010
- ListItem(
1011
- Label(Text(
1012
- f"{' ' * run.get('level', 0)}{run['label']}")),
1013
- classes="" if run.get("live", True) else "finished")
1014
- for run in self._runs
1015
- ]
1016
- children = [Label("Read which run?", id="agent-picker-title")]
1017
- if items:
1018
- children.append(ListView(*items, id="agent-picker-list"))
1019
- else:
1020
- children.append(Static(
1021
- "Nothing is running, and this conversation has not "
1022
- "started yet.", id="agent-picker-empty"))
1023
- yield Vertical(*children, id="agent-picker-dialog")
1024
-
1025
- def on_list_view_selected(self, event: ListView.Selected) -> None:
1026
- index = event.list_view.index
1027
- if index is not None and 0 <= index < len(self._runs):
1028
- self.dismiss(self._runs[index]["thread_id"])
1029
- else:
1030
- self.dismiss(None)
1031
-
1032
- def action_cancel(self) -> None:
1033
- self.dismiss(None)
1034
-
1035
-
1036
- class SessionKillScreen(ModalScreen[object]):
1037
- """Pick a background session to stop. Dismisses with a session id, or
1038
- None to cancel (ROADMAP_v3 §49, SS2).
1039
-
1040
- ALWAYS A PICKER, including for a single session, and that is a
1041
- decision rather than a simplification. §49's adopted default killed
1042
- outright when exactly one was live and showed this list only for
1043
- several, which made one key mean two things -- and the destructive
1044
- one was the case that needed no confirmation. A one-row list costs a
1045
- keypress and removes the mistyped-ctrl+b case entirely.
1046
-
1047
- It is also the only thing on screen that says what is running until
1048
- the sidebar panel lands, which is why the rows carry the command and
1049
- not just an id.
1050
-
1051
- The rows arrive already rendered and already REDACTED: the command
1052
- goes through the same output policy the model's own view of it does,
1053
- because a modal is a display surface like any other and a secret does
1054
- not become safe by being shown to the person who typed it.
1055
- """
1056
-
1057
- BINDINGS = [("escape", "cancel", "Cancel")]
1058
-
1059
- def __init__(self, rows: list[dict]):
1060
- super().__init__()
1061
- self._rows = rows
1062
-
1063
- def compose(self) -> ComposeResult:
1064
- items = [ListItem(Label(Text(row["label"]))) for row in self._rows]
1065
- children = [Label("Stop which session?", id="session-kill-title")]
1066
- if items:
1067
- children.append(ListView(*items, id="session-kill-list"))
1068
- else:
1069
- children.append(Static("Nothing is running.",
1070
- id="session-kill-empty"))
1071
- yield Vertical(*children, id="session-kill-dialog")
1072
-
1073
- def on_list_view_selected(self, event: ListView.Selected) -> None:
1074
- index = event.list_view.index
1075
- if index is not None and 0 <= index < len(self._rows):
1076
- self.dismiss(self._rows[index]["id"])
1077
- else:
1078
- self.dismiss(None)
1079
-
1080
- def action_cancel(self) -> None:
1081
- self.dismiss(None)
1082
-
1083
-
1084
- class ThreadPickerScreen(ModalScreen[object]):
1085
- """Pick a thread to resume. Dismisses with a UUID, or None to cancel.
1086
-
1087
- Reads storage.list_threads(), which since §27 returns CONVERSATIONS only
1088
- -- a research run creates ~15 threads of machinery and every automatic
1089
- compaction one more, and all of them used to be offered here as things
1090
- to resume.
1091
-
1092
- A row leads with the thread's first user message (§27), because a list
1093
- of uuids and timestamps was still unusable once it was short: filtering
1094
- made the picker correct, and the preview is what makes it answerable.
1095
- The id stays, since it is what --thread and /resume take.
1096
-
1097
- `note` carries one line shown under the title when the list is not the
1098
- whole story (#30/#32): the picker caps at PICKER_LIMIT rows, and a cap
1099
- that does not say so reads as "this is everything" (M14's rule). Older
1100
- conversations remain reachable by id via /resume.
1101
- """
1102
-
1103
- BINDINGS = [("escape", "cancel", "Cancel")]
1104
-
1105
- def __init__(self, threads: list[dict], note: str = ""):
1106
- super().__init__()
1107
- self._threads = threads
1108
- self._note = note
1109
-
1110
- def compose(self) -> ComposeResult:
1111
- items = [ListItem(Label(Text(thread_row(t))))
1112
- for t in self._threads]
1113
- children = [Label("Resume which thread?", id="thread-title")]
1114
- if self._note:
1115
- children.append(Static(Text(self._note),
1116
- id="thread-note"))
1117
- if items:
1118
- children.append(ListView(*items, id="thread-list"))
1119
- else:
1120
- children.append(Static("No saved threads yet.", id="thread-empty"))
1121
- yield Vertical(*children, id="thread-dialog")
1122
-
1123
- def on_list_view_selected(self, event: ListView.Selected) -> None:
1124
- index = event.list_view.index
1125
- if index is not None and 0 <= index < len(self._threads):
1126
- self.dismiss(self._threads[index]["id"])
1127
- else:
1128
- self.dismiss(None)
1129
-
1130
- def action_cancel(self) -> None:
1131
- self.dismiss(None)
1132
-
1133
-
1134
- class SecretScreen(ModalScreen[object]):
1135
- """Ask for one secret, masked (ROADMAP_v3 §49 slice 5a, SS59).
1136
-
1137
- THE FIRST MASKED INPUT IN THIS PROJECT, which is why it is its own
1138
- screen rather than a flag on QuestionScreen. The KIND is what tells a
1139
- shell how to render (§23 AC1), and here the rendering IS the substance: a
1140
- flag that a screen forgot to read would show the passphrase in clear
1141
- while every test about the plumbing still passed.
1142
-
1143
- Four properties this screen owes, none of which QuestionScreen has:
1144
-
1145
- * `password=True`, so the characters are never drawn;
1146
- * the value is dismissed and NOTHING ELSE. It is not put in a
1147
- reactive, not logged, not echoed into the transcript, and not kept
1148
- on the screen object past `dismiss` -- `on_button_pressed` reads
1149
- the widget and hands the string straight out;
1150
- * Escape and the Cancel button dismiss with None, which
1151
- `interaction.decode` turns into the declining default. A dismissed
1152
- passphrase prompt must not become an empty passphrase, because an
1153
- empty passphrase is an authentication ATTEMPT (SS59);
1154
- * Enter submits, because a password field that needs a mouse is a
1155
- password field people paste into something else first.
1156
- """
1157
-
1158
- BINDINGS = [("escape", "cancel", "Cancel")]
1159
-
1160
- def __init__(self, title: str, body: str = "",
1161
- confirm_label: str = "Unlock"):
1162
- super().__init__()
1163
- self._title = title
1164
- self._body = body
1165
- self._confirm_label = confirm_label
1166
-
1167
- def compose(self) -> ComposeResult:
1168
- widgets = [Label(Text(self._title), id="permission-title")]
1169
- if self._body:
1170
- widgets.append(
1171
- ScrollBox(Static(Text(self._body), id="permission-params"),
1172
- id="permission-params-box"))
1173
- widgets.append(Input(password=True, id="secret-value"))
1174
- widgets.append(Horizontal(
1175
- Button(Text(self._confirm_label), variant="success",
1176
- id="secret-ok"),
1177
- Button("Cancel", variant="error", id="secret-cancel"),
1178
- id="permission-buttons"))
1179
- yield Vertical(*widgets, id="permission-dialog")
1180
-
1181
- def on_mount(self) -> None:
1182
- self.query_one("#secret-value", Input).focus()
1183
-
1184
- def _submit(self) -> None:
1185
- self.dismiss(self.query_one("#secret-value", Input).value)
1186
-
1187
- def on_input_submitted(self, event: Input.Submitted) -> None:
1188
- self._submit()
1189
-
1190
- def on_button_pressed(self, event: Button.Pressed) -> None:
1191
- if event.button.id == "secret-ok":
1192
- self._submit()
1193
- else:
1194
- self.dismiss(None)
1195
-
1196
- def action_cancel(self) -> None:
1197
- self.dismiss(None)
1
+ """
2
+ tui/screens.py
3
+
4
+ ROADMAP_v2 §16 modal screens: the permission prompt (AC2) and the thread
5
+ picker (§16 AC1), plus §25's research grant picker.
6
+
7
+ The permission modal is the load-bearing one. §13 built `permission_channel`
8
+ as a plain stdlib queue.Queue precisely so this hand-off works: the worker
9
+ thread running _run() blocks on channel.get() while the UI thread shows the
10
+ modal, and the user's answer unblocks it. Nothing here is async-aware --
11
+ the blocking side is a thread, not a coroutine.
12
+
13
+ EVERY RENDERABLE BUILT FROM A NON-LITERAL IS WRAPPED IN `Text(...)`
14
+ (batch 42, RA1). Textual parses a `str` as MARKUP, so a square bracket
15
+ in a tool argument, a claim, a thread preview or an `ask_user` option
16
+ is a tag here -- and these screens exist to show a person exactly what
17
+ a model asked for. It was Rich's console markup until the textual pin
18
+ moved and is Textual's own grammar now; nothing below changed with it,
19
+ which is the point of re-measuring rather than assuming. Two live
20
+ failures:
21
+
22
+ * `sed -i "s/[/]//" f.txt` in a permission payload
23
+ raised MarkupError inside compose(). The screen was pushed and
24
+ never rendered, so its dismissal callback never fired and the
25
+ worker parked on Queue.get() for ATTENDED_APPROVAL_TIMEOUT_S --
26
+ 600s, presenting as a hang. ARCHITECTURE.md records that every
27
+ DISMISSAL path must produce a boolean; this is the case that rule
28
+ misses, because a screen that cannot render never reaches one.
29
+
30
+ * `ReviewScreen`'s title read `[{severity}]`, and `[high]` is a tag.
31
+ The severity was silently absent from every review modal since
32
+ §20 -- an unconditional defect, needing no adversary at all.
33
+
34
+ `markup=False` WORKS NOW AND IS STILL NOT THE FIX, which is a
35
+ different sentence from the one that stood here. On textual 1.0.0 the
36
+ flag was stored by `__init__` and never read by the `visual`
37
+ property, so `Static(x, markup=False)` raised anyway -- measured then.
38
+ Since the pin moved it is honoured: `visualize(self, content,
39
+ markup=self._render_markup)`, and all four payloads below render
40
+ literally -- measured again.
41
+
42
+ The wrap stays, for two reasons that outlived the version fact. It
43
+ covers `Selection` and `Button`, which take no such flag and both
44
+ parse what they are given. And it is one rule for one file, where the
45
+ flag would be a per-constructor argument somebody adding the next
46
+ screen has to remember -- which is exactly the failure RA1 is.
47
+
48
+ What a bare `str` still does on 8.2.8, measured:
49
+ `sed -i "s/[/]//" f.txt` raises, `[bold]x` renders as `x`,
50
+ `[HIGH] rated` renders as ` rated`, and `[1, 2]` survives intact.
51
+ That last one is why the rule cannot be a scan for brackets: the
52
+ shapes that fail are not the ones a reader expects to be dangerous.
53
+
54
+ A literal written in THIS file is left alone: it is ours and it is
55
+ reviewed. The rule is mechanical, so it holds for the next screen
56
+ somebody adds -- test_tui.py walks this file's AST and asserts it.
57
+ """
58
+
59
+ import json
60
+
61
+ from rich.text import Text
62
+ from textual.app import ComposeResult
63
+ from textual.containers import Horizontal, Vertical, VerticalScroll
64
+ from textual.screen import ModalScreen
65
+ from textual.widgets import (
66
+ Button,
67
+ Input,
68
+ Label,
69
+ ListItem,
70
+ ListView,
71
+ SelectionList,
72
+ Static,
73
+ )
74
+ from textual.widgets.selection_list import Selection
75
+
76
+ from core.claims_view import claims_header, render_claims
77
+ from core.replay import thread_row
78
+
79
+
80
+ class ScrollBox(VerticalScroll):
81
+ """A bounded block of text whose overflow can actually be reached
82
+ (§46, EP3).
83
+
84
+ Two things were wrong with `Static` + `max-height` + `overflow-y`,
85
+ and only the first is the one that looks wrong:
86
+
87
+ * `Static.can_focus` is False on the pinned textual 1.0.0, so the
88
+ scrollbar such a rule produces can only be moved by a mouse.
89
+ * A `Static` NEVER reports content taller than its own box --
90
+ `virtual_size` follows the clamped box, not the text -- so
91
+ `max_scroll_y` was 0 and the hidden rows were not scrolled past,
92
+ they were GONE. Measured: nine lines of payload in a seven-row
93
+ block, `max_scroll_y == 0`, End does nothing. Making the Static
94
+ focusable would have fixed the visible half of that and left the
95
+ truncation exactly where it was.
96
+
97
+ So the bound belongs on a real scroll container and the text on an
98
+ auto-height child inside it.
99
+
100
+ THE BOUND IS `height: auto` WITH A `max-height`, NOT A DEFINITE
101
+ `height` (batch 49, amending EP3). §46 read the zero it measured as
102
+ "a scrollable container asked for `height: auto` resolves to ZERO"
103
+ and prescribed a definite height. The zero was EP1's `1fr` ROW.
104
+ Measured again with the row `auto`, all three spellings differ and
105
+ only one is right:
106
+
107
+ 25 lines of payload, grid row `auto`
108
+ height: auto box=25, no scroll, BUTTONS OUTSIDE
109
+ height: 9 box=9, 16 scrollable, BUTTONS OUT
110
+ height: auto; max-height: 9 box=9, 16 scrollable, buttons in
111
+ the same three inside a `1fr` row box=0, all three
112
+
113
+ A definite height bounds what this box DRAWS and not what its parent
114
+ RESERVES, so the row kept growing with the payload and pushed the
115
+ Allow/Deny row past the dialog's own `max-height`, where it was
116
+ clipped away entirely. `auto` with a `max-height` reports the bound
117
+ upward, so the dialog stays inside itself -- and it still shrinks for
118
+ a short payload, which a definite height never did.
119
+
120
+ Bindings are `ScrollableContainer`'s minus the horizontal ones:
121
+ there is nothing to scroll sideways, because the text wraps.
122
+ """
123
+
124
+
125
+ def asker_label(asked_by, depth) -> list:
126
+ """`[Label]` naming the run that raised a question, or `[]` (§47).
127
+
128
+ ONE SENTENCE FOR THE THREE MODALS THAT CAN BE ASKED FROM INSIDE A RUN.
129
+ §47 gave it to the permission modal alone; batch 75's review found the
130
+ sign-off and the model's own question without it, which is where it
131
+ matters most now that three children of one turn can each be asking:
132
+ three sign-off screens naming the grandchild and nothing about who
133
+ asked are three identical screens.
134
+
135
+ Empty at depth 0, and that is the right SCOPE rather than a gap: the
136
+ asking run is then the conversation you are looking at, which needs no
137
+ label.
138
+
139
+ Returned as a LIST so a caller splices it into its widget list without
140
+ a branch, which is what keeps the placement rule (directly under the
141
+ title, above anything the agent wrote) in one shape across the three.
142
+
143
+ `Text(...)` for RA1's reason -- an agent name comes from a file whose
144
+ author is not necessarily this project.
145
+ """
146
+ if not asked_by:
147
+ return []
148
+ return [Label(Text(f"asked by {asked_by} (depth {depth})"),
149
+ id="permission-asker")]
150
+
151
+
152
+ class PermissionScreen(ModalScreen[bool]):
153
+ """Approve or deny one tool call. Dismisses with the decision.
154
+
155
+ The payload is shown FULL and UNREDACTED: the user must see the exact
156
+ path/command/URL they are being asked to authorise, and truncation or
157
+ redaction here would make the consent uninformed (the param_digest
158
+ truncation is for the transcript only). Logs redact via
159
+ logging_setup._RedactingFormatter and safety/policy_enforcement's
160
+ check_output_policy, so the full value never reaches disk unguarded —
161
+ do not add redaction here to "match" the transcript.
162
+
163
+ Full and unredacted, and NOT INTERPRETED: the payload goes
164
+ through `Text(...)` so a bracket in a command stays a bracket.
165
+ Showing the exact value is this screen's whole purpose, and
166
+ markup parsing is a way of showing something else -- see the
167
+ module docstring.
168
+
169
+ THE RATIONALE IS NOT EVIDENCE (§42, RA6). It is the agent's own
170
+ sentence about its own call, so it is unverifiable by
171
+ construction: an agent that has been steered writes a reassuring
172
+ one, and that is the case this screen exists for. It is labelled
173
+ as a claim and placed BELOW the notice, which the harness
174
+ computed, so nobody reads the harness as vouching for it. What it
175
+ is actually for is longitudinal -- a thread's worth of stated
176
+ reasons, archived beside the calls, is a drift signal no single
177
+ prompt can be.
178
+
179
+ THE SUBJECT OF THE QUESTION IS PINNED, OUTSIDE THE SCROLL (§46,
180
+ EP1). RA6 ordered three things -- the harness's notice, the agent's
181
+ claim, the payload -- and the command is none of them: it is what
182
+ all three are ABOUT. Ranked among them it came last, inside the
183
+ payload, which is how a user came to report that the command was
184
+ visible in the transcript and nowhere on the modal asking about it.
185
+ The payload keeps RA6's order intact below; the headline is lifted
186
+ out of the ranking, not moved up it.
187
+
188
+ What the investigation actually found is worse than the ordering,
189
+ and it is recorded here because the obvious reading of the report
190
+ was wrong. `#permission-params` sat in a `1fr` grid row inside a
191
+ `height: auto` dialog, and a fractional row in an auto-height
192
+ container resolves to ZERO. Measured against HEAD in a worktree:
193
+ `region.height == 0`, `virtual_size.height == 0`, nine lines of
194
+ content. The notice, the agent's stated reason and the payload were
195
+ not clipped and scrollable -- they were absent, from every
196
+ permission modal this app has ever shown, for every tool. The
197
+ command was merely the part somebody noticed was missing.
198
+
199
+ Nothing caught it because every assertion about this screen reads
200
+ the widget's own VISUAL -- the string it was built from, which a
201
+ widget of zero height still reports in full. §46's tests assert on
202
+ the rendered REGION for that reason.
203
+
204
+ The headline is DISPLAY ONLY and is also inside `params`, which is
205
+ still rendered whole below it. That duplication is deliberate for
206
+ the reason the rationale's is: this screen shows the payload
207
+ entire, and the pinned copy is a placement, not a substitution. A
208
+ reader comparing the two is doing something useful.
209
+ """
210
+
211
+ BINDINGS = [("escape", "deny", "Deny")]
212
+
213
+ def __init__(self, tool_name: str, params: dict, notice: str = None,
214
+ rationale: str = None, headline: str = None,
215
+ asked_by: str = None, depth: int = 0):
216
+ super().__init__()
217
+ self._tool_name = tool_name
218
+ self._params = params
219
+ # ROADMAP_v2 §47. WHICH run raised this question, when it was
220
+ # not the conversation itself. A subagent's approvals have
221
+ # always surfaced here -- the channel is inherited -- and the
222
+ # modal said only which TOOL was asked for, so "Allow shell?"
223
+ # over a chat turn and over a nested agent two levels down
224
+ # were the same screen.
225
+ #
226
+ # None for a top-level turn, and that is the right scope
227
+ # rather than a gap: the asking run is then the conversation
228
+ # you are looking at, which needs no label. It becomes
229
+ # load-bearing when two questions can be pending at once,
230
+ # which is why it is a prerequisite for §47's last slice
231
+ # rather than a nicety.
232
+ self._asked_by = asked_by
233
+ self._depth = depth
234
+ # §46 (EP2). What this call is asking to DO -- for `shell`, the
235
+ # command. Resolved by the registry from whichever param the
236
+ # tool declared and passed in already a string, for the reason
237
+ # the rationale is: this module imports nothing from the rest
238
+ # of the project. None for every tool that declares no
239
+ # headline, and the pinned block simply does not render.
240
+ self._headline = headline
241
+ # §42 (RA6). The agent's OWN account of why it wants this call,
242
+ # resolved by the registry from whichever param the tool
243
+ # declared. Passed in rather than looked up: this module
244
+ # imports nothing from the rest of the project and that is
245
+ # worth more than saving a parameter.
246
+ self._rationale = rationale
247
+ # Supplied by the tool via ToolSpec.approval_notice, not composed
248
+ # here: what approving authorises is the TOOL's knowledge.
249
+ # spawn_subagent uses it to list the tools the subagent could then
250
+ # run unprompted, which the params alone never say.
251
+ # DISPLAYED FULL above — see class docstring for why this stays
252
+ # unredacted while the transcript's `▸` digest and the log do not.
253
+ self._notice = notice
254
+
255
+ def compose(self) -> ComposeResult:
256
+ try:
257
+ rendered = json.dumps(self._params, indent=2, default=str)
258
+ except (TypeError, ValueError):
259
+ rendered = repr(self._params)
260
+ # HARNESS FACT, THEN AGENT CLAIM, THEN EVIDENCE (§42, RA6).
261
+ # The notice is computed -- `classify_command` decided it --
262
+ # so it is read before any reassurance the model wrote. The
263
+ # payload stays last and stays whole; the rationale appears in
264
+ # it as well, and that duplication is the honest cost of
265
+ # surfacing the field without breaking the rule above that
266
+ # this screen shows the payload entire.
267
+ reason = self._rationale or "(none given)"
268
+ rendered = (f"Agent's stated reason (its own words, unverified):\n"
269
+ f" {reason}\n\n{rendered}")
270
+ if self._notice:
271
+ rendered = f"{self._notice}\n\n{rendered}"
272
+ widgets = [Label(Text(f"Allow {self._tool_name}?"),
273
+ id="permission-title")]
274
+ # DIRECTLY under the title, above the headline and everything the
275
+ # agent wrote: RA6's ordering says a harness fact is read before an
276
+ # agent's claim, and which run is asking is the most harness-y fact
277
+ # on the screen. See `asker_label` for the rest.
278
+ widgets.extend(asker_label(self._asked_by, self._depth))
279
+ if self._headline:
280
+ # `Text(...)` is not optional here (batch 42, RA1). This is
281
+ # the most attacker-influenced string on the screen -- a
282
+ # model-authored command shown so a person can vet it --
283
+ # and `Static` renders a `str` through `Text.from_markup`,
284
+ # so `sed -i "s/[/]//" f.txt` would raise MarkupError
285
+ # inside compose(), leaving the screen pushed, unrendered
286
+ # and its dismissal callback never fired. test_tui.py walks
287
+ # this file's AST and asserts the wrapping.
288
+ widgets.append(ScrollBox(
289
+ Static(Text(self._headline), id="permission-command"),
290
+ id="permission-command-box"))
291
+ # The id stays on the STATIC and the scroll container is a
292
+ # `-box` sibling, rather than the other way round: a stylesheet
293
+ # wants the bound and the overflow, which belong to the
294
+ # container, while every assertion in test_rationale.py and
295
+ # test_tui.py asks what text was DRAWN, which only the Static
296
+ # can answer. Moving the id outward would make
297
+ # `query_one("#permission-params")` return a container with no
298
+ # `visual` -- and reading that attribute is how batch 42's
299
+ # markup bug was caught.
300
+ widgets.append(ScrollBox(
301
+ Static(Text(rendered), id="permission-params"),
302
+ id="permission-params-box"))
303
+ # ONE bar, centred, holding both answers (batch 49). Two
304
+ # Buttons in a two-column Grid sat at the LEFT of their columns,
305
+ # so a 16-wide Deny left ~22 dead columns beside it while Allow
306
+ # was flush against the padding -- the dialog was centred and its
307
+ # contents were not. A Horizontal with `align: center middle`
308
+ # centres the pair as a unit and keeps both answers the same
309
+ # size, which the alternative (each button filling its half) does
310
+ # not: it would make the permissive answer a target half the
311
+ # width of the modal.
312
+ widgets.append(Horizontal(
313
+ Button("Allow", variant="success", id="allow"),
314
+ Button("Deny", variant="error", id="deny"),
315
+ id="permission-buttons"))
316
+ # A Vertical, not a Grid (batch 49). Every child spanned both
317
+ # columns, so the second column only ever held the Deny button --
318
+ # and the `with-headline` class existed solely to carry a ROW
319
+ # COUNT to the stylesheet, because a Grid's `grid-size` is static
320
+ # and this screen composes three children or four. A Vertical
321
+ # does not care how many there are, so the template it guarded
322
+ # against getting wrong is gone rather than documented.
323
+ yield Vertical(*widgets, id="permission-dialog")
324
+
325
+ def on_mount(self) -> None:
326
+ # ENTER DECLINES (batch 49). Focus lands on the first focusable
327
+ # widget otherwise, which is whichever ScrollBox composed first --
328
+ # so Enter did nothing here, and on ConfirmScreen, whose body is a
329
+ # plain Static, it said YES. The convenient action must not be the
330
+ # permissive one; that is already the recorded reason
331
+ # GrantPickerScreen ships every option unticked, and it applies
332
+ # with more force to a key a person presses without looking.
333
+ self.query_one("#deny", Button).focus()
334
+
335
+ def on_button_pressed(self, event: Button.Pressed) -> None:
336
+ self.dismiss(event.button.id == "allow")
337
+
338
+ def action_deny(self) -> None:
339
+ # Escape answers with the SAME value the No button produces.
340
+ # Since §23 a dismissal carrying None would be safe anyway --
341
+ # interaction.decode supplies APPROVAL's declining default -- so
342
+ # this is explicitness rather than hang-prevention: one screen
343
+ # should not have two ways to say no.
344
+ self.dismiss(False)
345
+
346
+
347
+ class GrantPickerScreen(ModalScreen[object]):
348
+ """Pick which approval-gated tools a research run may use (§25 R1).
349
+
350
+ Dismisses with a set of names, or None to cancel the run entirely --
351
+ the two are different answers. An empty SET means "run with no grants"
352
+ (a legitimate choice: the pipeline just keeps hiding gated tools),
353
+ while None means "I did not mean to start this at all".
354
+
355
+ Per-tool rather than one prompt for the whole set, and each row shows
356
+ what the tool says it does, because the harness cannot tell a
357
+ read-only tool from one that writes or sends -- MCP exposes no such
358
+ metadata. The description and the individual choice are the entire
359
+ substance of informed consent here.
360
+ """
361
+
362
+ BINDINGS = [("escape", "cancel", "Cancel")]
363
+
364
+ def __init__(self, offered: list):
365
+ super().__init__()
366
+ self._offered = list(offered)
367
+
368
+ def compose(self) -> ComposeResult:
369
+ # Every option starts UNSELECTED. A pre-ticked list would make the
370
+ # convenient action the permissive one, and this prompt exists
371
+ # precisely because nobody will be watching afterwards.
372
+ options = [
373
+ Selection(Text(f"{name} — {description}" if description
374
+ else name),
375
+ name, False)
376
+ for name, description in self._offered
377
+ ]
378
+ yield Vertical(
379
+ Label("Authorise for this run only", id="grant-title"),
380
+ Static(
381
+ "These tools need approval, and nothing can give it during "
382
+ "an unattended run.\nSpace toggles, Enter confirms, Escape "
383
+ "cancels the run. Nothing is saved.",
384
+ id="grant-help"),
385
+ SelectionList(*options, id="grant-list"),
386
+ # A bar with one button in it. NO focus call here and none on
387
+ # ProjectKindScreen: neither screen HAS a declining button --
388
+ # escape is the decline on both -- so there is nothing to
389
+ # focus that would make Enter safe, and focusing the
390
+ # affirmative one for consistency would be the exact
391
+ # inversion PermissionScreen.on_mount exists to prevent.
392
+ Horizontal(
393
+ Button("Run with selected", variant="success",
394
+ id="grant-ok"),
395
+ id="grant-buttons"),
396
+ id="grant-dialog",
397
+ )
398
+
399
+ def on_button_pressed(self, event: Button.Pressed) -> None:
400
+ self.dismiss(set(self.query_one("#grant-list", SelectionList).selected))
401
+
402
+ def action_cancel(self) -> None:
403
+ self.dismiss(None)
404
+
405
+
406
+ class SubagentSignoffScreen(ModalScreen[object]):
407
+ """Pick which of a subagent's gated tools it may use unprompted
408
+ (ROADMAP_v2 §23 AC1b).
409
+
410
+ Modelled on GrantPickerScreen, and dismissing with the same THREE
411
+ answers for the same reason: a set of names grants those, an EMPTY set
412
+ spawns the agent with nothing granted, and None refuses the spawn
413
+ outright. Those are three different intentions and a bool cannot hold
414
+ them -- which is precisely why §18 shipped this all-or-nothing (S1)
415
+ on a boolean channel, and why it could only be built once §23 gave the
416
+ channel a typed answer.
417
+
418
+ Every option starts UNSELECTED. A pre-ticked list makes the convenient
419
+ action the permissive one, and the point of this prompt is that
420
+ approving a spawn used to authorise the child's ENTIRE gated set.
421
+ """
422
+
423
+ BINDINGS = [("escape", "refuse", "Refuse")]
424
+
425
+ def __init__(self, agent: str, candidates: list, asked_by: str = None,
426
+ depth: int = 0):
427
+ super().__init__()
428
+ self._agent = agent
429
+ self._candidates = list(candidates)
430
+ # §47, extended by batch 75's review. WHICH run wants to spawn
431
+ # this one -- a different agent from `self._agent`, which is the
432
+ # one about to be spawned. It matters more here than on the
433
+ # permission modal: three children of one turn each spawning a
434
+ # grandchild produce three of these screens, and without this they
435
+ # name the grandchild and nothing else, so they are identical.
436
+ self._asked_by = asked_by
437
+ self._depth = depth
438
+
439
+ def compose(self) -> ComposeResult:
440
+ if not self._candidates:
441
+ yield Vertical(
442
+ Label(Text(f"Run {self._agent}?"),
443
+ id="permission-title"),
444
+ *asker_label(self._asked_by, self._depth),
445
+ Static(Text(f"{self._agent} needs no approval-gated "
446
+ f"tools."),
447
+ id="permission-params"),
448
+ Horizontal(
449
+ Button("Run", variant="success", id="signoff-none"),
450
+ Button("Refuse", variant="error", id="signoff-refuse"),
451
+ id="permission-buttons"),
452
+ id="permission-dialog",
453
+ )
454
+ return
455
+ options = [Selection(Text(name), name, False)
456
+ for name in self._candidates]
457
+ yield Vertical(
458
+ Label(Text(f"What may {self._agent} use without asking again?"),
459
+ id="grant-title"),
460
+ # BOTH branches, because either can be reached from inside a
461
+ # run -- the no-candidates one is what a nested spawn of an
462
+ # agent with no gated tools shows.
463
+ *asker_label(self._asked_by, self._depth),
464
+ Static(
465
+ "Space toggles, then choose. Anything left unticked still "
466
+ "prompts you if the subagent tries it.\nRunning with none "
467
+ "selected is fine. Escape refuses the spawn entirely.",
468
+ id="grant-help"),
469
+ SelectionList(*options, id="signoff-list"),
470
+ Horizontal(
471
+ Button("Run with selected", variant="success",
472
+ id="signoff-ok"),
473
+ Button("Refuse the spawn", variant="error",
474
+ id="signoff-refuse"),
475
+ id="grant-buttons"),
476
+ id="grant-dialog",
477
+ )
478
+
479
+ def on_mount(self) -> None:
480
+ # The refusal, on both branches -- see PermissionScreen.on_mount.
481
+ self.query_one("#signoff-refuse", Button).focus()
482
+
483
+ def on_button_pressed(self, event: Button.Pressed) -> None:
484
+ if event.button.id == "signoff-refuse":
485
+ self.dismiss(None)
486
+ elif event.button.id == "signoff-none":
487
+ self.dismiss(set())
488
+ else:
489
+ self.dismiss(
490
+ set(self.query_one("#signoff-list", SelectionList).selected))
491
+
492
+ def action_refuse(self) -> None:
493
+ # Escape REFUSES rather than running with nothing granted. The two
494
+ # are different answers, and the one a user reaches for when they
495
+ # did not mean to start this is the refusal.
496
+ self.dismiss(None)
497
+
498
+
499
+ class MemoryPickerScreen(ModalScreen[object]):
500
+ """Tick the durable memories to forget (ROADMAP_v3 §59, UI1).
501
+
502
+ `/forget` with no id opens this, so removing a memory no longer means
503
+ reading a uuid out of the transcript and typing it back. Dismisses with
504
+ the set of ticked ids, or None for Escape and Cancel. The caller asks
505
+ for confirmation before anything is deleted (UI4); this screen only
506
+ picks.
507
+
508
+ `options` is `(label, id)` pairs, labelled by `memories/tui_commands.py`
509
+ so this screen does not need to know a memory row's shape. Every row
510
+ starts UNTICKED, GrantPickerScreen's rule: the convenient action must
511
+ not be the destructive one.
512
+ """
513
+
514
+ BINDINGS = [("escape", "cancel", "Cancel")]
515
+
516
+ def __init__(self, options: list):
517
+ super().__init__()
518
+ self._options = list(options)
519
+
520
+ def compose(self) -> ComposeResult:
521
+ # Text(...): a memory is text a model proposed, so it must not be
522
+ # read as Rich markup (RA1's rule for anything this project did
523
+ # not write itself).
524
+ rows = [Selection(Text(label), memory_id, False)
525
+ for label, memory_id in self._options]
526
+ yield Vertical(
527
+ Label("Forget which memories?", id="grant-title"),
528
+ Static(
529
+ "Space ticks a memory. Tab to Forget selected and press "
530
+ "Enter; you confirm before anything is deleted.\nEscape "
531
+ "cancels. /forget <id> still removes one by id.",
532
+ id="grant-help"),
533
+ SelectionList(*rows, id="forget-list"),
534
+ Horizontal(
535
+ Button("Forget selected", variant="error", id="forget-ok"),
536
+ Button("Cancel", variant="primary", id="forget-cancel"),
537
+ id="grant-buttons"),
538
+ id="grant-dialog",
539
+ )
540
+
541
+ def on_mount(self) -> None:
542
+ # The list, so Space works at once. Not a button: Enter on the
543
+ # affirmative one is what PermissionScreen.on_mount guards against,
544
+ # and on the list Enter only ticks.
545
+ self.query_one("#forget-list", SelectionList).focus()
546
+
547
+ def on_button_pressed(self, event: Button.Pressed) -> None:
548
+ if event.button.id == "forget-cancel":
549
+ self.dismiss(None)
550
+ return
551
+ self.dismiss(set(self.query_one("#forget-list", SelectionList).selected))
552
+
553
+ def action_cancel(self) -> None:
554
+ self.dismiss(None)
555
+
556
+
557
+ class QuestionScreen(ModalScreen[object]):
558
+ """Ask the user the model's question (§23 slice 2, AC2).
559
+
560
+ Dismisses with a dict, or None. THREE answers, and the middle one is
561
+ the one to lose -- the same distinction SubagentSignoffScreen draws:
562
+
563
+ None nobody answered. Escape, and the app's
564
+ shutdown release.
565
+ {"defer": True} "let's talk about it instead". A REAL
566
+ answer: the user engaged and declined to
567
+ pick, which tells the model something that
568
+ closing the modal does not.
569
+ {"options": [...], what they chose, what they typed, or both.
570
+ "text": "..."}
571
+
572
+ Four affordances, all four from the spec. Options are a SelectionList
573
+ when several may be chosen and Buttons when only one may -- a
574
+ single-select SelectionList would let a user tick three and then be
575
+ told only one counted, which is a worse lie than not offering it.
576
+
577
+ UNSELECTED and EMPTY to start, like every other picker here. The
578
+ convenient action must not be the one that answers on the user's
579
+ behalf, and this modal exists precisely because the model does not
580
+ know the answer.
581
+
582
+ The screen does NOT validate. Whether a returned option was actually
583
+ offered is core.interaction.decode's job, which is why it takes the
584
+ request -- ProjectKindScreen made the same move for the same reason.
585
+ """
586
+
587
+ BINDINGS = [("escape", "dismiss_unanswered", "No answer")]
588
+
589
+ def __init__(self, question: str, options=(), multi_select: bool = False,
590
+ allow_text: bool = True, asked_by: str = None,
591
+ depth: int = 0):
592
+ super().__init__()
593
+ self._question = question
594
+ self._options = list(options)
595
+ self._multi = bool(multi_select)
596
+ self._allow_text = bool(allow_text)
597
+ # §47, added by batch 75's review. "The assistant has a question"
598
+ # is the right title for a chat turn and an understatement for a
599
+ # subagent two levels down, whose question surfaces on the parent's
600
+ # screen exactly as its approvals do.
601
+ self._asked_by = asked_by
602
+ self._depth = depth
603
+
604
+ def compose(self) -> ComposeResult:
605
+ # The question is the MODEL's, so its length is the one thing
606
+ # this screen does not choose -- bounded and scrollable for the
607
+ # same reason the payload block is.
608
+ widgets = [Label("The assistant has a question", id="question-title"),
609
+ *asker_label(self._asked_by, self._depth),
610
+ ScrollBox(Static(Text(self._question), id="question-body"),
611
+ id="question-body-box")]
612
+
613
+ if self._options and self._multi:
614
+ widgets.append(Static(
615
+ "Space toggles; several may be chosen.", id="question-help"))
616
+ widgets.append(SelectionList(
617
+ *[Selection(Text(o), o, False) for o in self._options],
618
+ id="question-list"))
619
+ widgets.append(
620
+ Button("Answer", variant="success", id="question-ok"))
621
+ elif self._options:
622
+ # Bounded and scrollable, like the multi-select branch's
623
+ # SelectionList beside it (batch 49). Unbounded, four options
624
+ # of two lines each cost 16 of the dialog's 18 rows and took
625
+ # the Answer button and Discuss instead off the bottom with
626
+ # them. The Buttons are also FIXED WIDTH in the stylesheet:
627
+ # at `width: auto` an option wider than the dialog was
628
+ # CLIPPED, and the same label at `width: 100%` wraps to two
629
+ # centred lines instead.
630
+ #
631
+ # `Text(option)` for batch 42's reason (RA1), which had
632
+ # not reached a Button: these are the MODEL's words, and
633
+ # measured on both the old pin and the new one, a
634
+ # `Button` given a `str` sends it through markup parsing
635
+ # and raises on an unbalanced tag -- inside compose(), so
636
+ # the screen is pushed and never drawn. The multi-select
637
+ # branch above already wraps its `Selection`; this branch
638
+ # simply had not.
639
+ widgets.append(ScrollBox(
640
+ *[Button(Text(option), variant="primary",
641
+ id=f"question-opt-{index}")
642
+ for index, option in enumerate(self._options)],
643
+ id="question-options"))
644
+
645
+ if self._allow_text:
646
+ widgets.append(Input(
647
+ placeholder="…or write your own answer",
648
+ id="question-text"))
649
+ if not (self._options and self._multi):
650
+ # A submit button for the typed answer. The multi-select
651
+ # branch already has one, and the single-select branch's
652
+ # option Buttons read the Input too -- but an open question
653
+ # with no options at all would otherwise have no way to
654
+ # submit anything.
655
+ widgets.append(
656
+ Button("Answer", variant="success", id="question-ok"))
657
+
658
+ # Always last, always available: the spec's escape is an answer the
659
+ # user can give on purpose, not only a thing that happens when they
660
+ # close the window. In the bar rather than beside it, so it cannot
661
+ # be the child that falls off the bottom -- which is exactly what
662
+ # it was.
663
+ trailing = [w for w in widgets if getattr(w, "id", "") == "question-ok"]
664
+ for widget in trailing:
665
+ widgets.remove(widget)
666
+ widgets.append(Horizontal(
667
+ *trailing,
668
+ Button("Discuss instead", variant="default", id="question-defer"),
669
+ id="question-buttons"))
670
+ yield Vertical(*widgets, id="question-dialog")
671
+
672
+ def on_mount(self) -> None:
673
+ # The first OPTION, which is where focus landed before the options
674
+ # gained a ScrollBox around them -- a scroll container is focusable
675
+ # and would otherwise take it. NOT the declining button: this
676
+ # screen authorises nothing, so there is no permissive answer for
677
+ # Enter to give, and the whole point of it is that the model does
678
+ # not know which option is right.
679
+ for candidate in ("#question-opt-0", "#question-list",
680
+ "#question-text", "#question-defer"):
681
+ found = self.query(candidate)
682
+ if found:
683
+ found.first().focus()
684
+ return
685
+
686
+ def _typed(self) -> str:
687
+ if not self._allow_text:
688
+ return ""
689
+ # Read on EVERY path, like ReviewScreen's note: a user who ticks an
690
+ # option and qualifies it in the box has given one answer, and
691
+ # dropping half of it because they pressed the wrong button first
692
+ # would be silent.
693
+ try:
694
+ return self.query_one("#question-text", Input).value.strip()
695
+ except Exception: # noqa: BLE001 -- absent when allow_text is False
696
+ return ""
697
+
698
+ def on_button_pressed(self, event: Button.Pressed) -> None:
699
+ button_id = event.button.id or ""
700
+ if button_id == "question-defer":
701
+ self.dismiss({"defer": True})
702
+ return
703
+
704
+ chosen = []
705
+ if button_id.startswith("question-opt-"):
706
+ index = int(button_id.rsplit("-", 1)[1])
707
+ chosen = [self._options[index]]
708
+ self._answer(chosen)
709
+
710
+ def on_input_submitted(self, event: Input.Submitted) -> None:
711
+ # Enter in the text box answers (batch 49). Textual posts this and
712
+ # nothing handled it, so the one affordance whose entire purpose
713
+ # is being typed into had no way to send what was typed -- and the
714
+ # Answer button it needed instead was the child clipped off the
715
+ # bottom. Through `_answer`, not a second dismissal: one shape of
716
+ # answer, one place that builds it.
717
+ self._answer([])
718
+
719
+ def _answer(self, chosen: list) -> None:
720
+ if self._options and self._multi:
721
+ chosen = list(
722
+ self.query_one("#question-list", SelectionList).selected)
723
+ self.dismiss({"options": chosen, "text": self._typed()})
724
+
725
+ def action_dismiss_unanswered(self) -> None:
726
+ # None, NOT a deferral. Escape means "I am not dealing with this";
727
+ # "Discuss instead" means "I want to talk about it". The tool says
728
+ # different things to the model about each, so collapsing them here
729
+ # would make the button pointless.
730
+ self.dismiss(None)
731
+
732
+
733
+ class ReviewScreen(ModalScreen[object]):
734
+ """Decide one proposed correction to a finished research run (§20 V4).
735
+
736
+ Dismisses with a (decision, notes) tuple. Every dismissal path carries
737
+ one -- escape, the buttons, and the app's shutdown release -- because
738
+ the /research worker is blocked on a queue that must receive AN
739
+ answer. What the answer is matters less than that it arrives:
740
+ interaction.decode turns anything unusable (None, a bare False from
741
+ shutdown, malformed junk) into REVIEW's declining default, so a new
742
+ path added later fails safe -- an edit is never applied because
743
+ nobody answered.
744
+
745
+ Four outcomes, not two. Reject and refine are different answers: "this
746
+ is wrong" ends the finding, while "you missed something" sends it back
747
+ with a note. And "reject the rest" is the escape a long review needs,
748
+ safe by construction because it only ever declines -- the affordance
749
+ that must NOT exist is the one that accepts in bulk.
750
+ """
751
+
752
+ BINDINGS = [("escape", "reject", "Reject")]
753
+
754
+ def __init__(self, finding: dict, round_index: int = 0,
755
+ max_rounds: int = 0):
756
+ super().__init__()
757
+ self._finding = finding
758
+ self._round = round_index
759
+ self._max_rounds = max_rounds
760
+
761
+ def compose(self) -> ComposeResult:
762
+ kind = self._finding.get("kind", "?")
763
+ target = self._finding.get("claim_id") or "the report"
764
+ severity = self._finding.get("severity", "unknown")
765
+ body = (
766
+ f"Why: {self._finding.get('reason', '(no reason given)')}\n\n"
767
+ f"Proposed: {self._finding.get('proposed')}"
768
+ )
769
+ if self._round:
770
+ body = (f"(refinement {self._round} of {self._max_rounds})\n\n"
771
+ f"{body}")
772
+ yield Vertical(
773
+ # `[{severity}]` is a MARKUP TAG to Rich, so this title
774
+ # rendered WITHOUT its severity on every review modal from
775
+ # §20 until batch 42 -- `[high]` parsed as an unknown
776
+ # style over a zero-width span. The brackets are wanted
777
+ # here; the parsing never was.
778
+ Label(Text(f"{kind} correction to {target} [{severity}]"),
779
+ id="review-title"),
780
+ ScrollBox(Static(Text(body), id="review-body"),
781
+ id="review-body-box"),
782
+ Input(placeholder="Note for the reviewer (used by Refine)",
783
+ id="review-note"),
784
+ # FOUR buttons in ONE row (batch 49). Stacked they cost 12 of
785
+ # the 18 rows a dialog has on an 80x24 terminal, so the body
786
+ # and the note pushed three of the four decisions off the
787
+ # bottom -- Refine, Reject and Reject the rest, which is to
788
+ # say every answer except Accept. Measured at 65 columns of
789
+ # buttons in 70, so they fit the floor as a row.
790
+ Horizontal(
791
+ Button("Accept", variant="success", id="review-accept"),
792
+ Button("Refine", variant="primary", id="review-refine"),
793
+ Button("Reject", variant="error", id="review-reject"),
794
+ Button("Reject the rest", variant="error",
795
+ id="review-reject-all"),
796
+ id="review-buttons"),
797
+ id="review-dialog",
798
+ )
799
+
800
+ def on_mount(self) -> None:
801
+ # The declining answer, like every other consent surface here --
802
+ # see PermissionScreen.on_mount. `reject` and not `reject_all`:
803
+ # both decline, and only one of them declines everything else too.
804
+ self.query_one("#review-reject", Button).focus()
805
+
806
+ def on_button_pressed(self, event: Button.Pressed) -> None:
807
+ decisions = {
808
+ "review-accept": "accept",
809
+ "review-refine": "refine",
810
+ "review-reject": "reject",
811
+ "review-reject-all": "reject_all",
812
+ }
813
+ note = self.query_one("#review-note", Input).value.strip()
814
+ self.dismiss((decisions[event.button.id], note))
815
+
816
+ def action_reject(self) -> None:
817
+ # Escape declines rather than dismissing with no value, for the
818
+ # same reason PermissionScreen's escape denies.
819
+ self.dismiss(("reject", ""))
820
+
821
+
822
+ class ClaimsScreen(ModalScreen[None]):
823
+ """Every claim a research run produced, with the metadata that decided
824
+ its tier (ROADMAP_v2 §26).
825
+
826
+ The report a run ends with is a synthesis. What it was synthesised
827
+ FROM -- which assertions were extracted, which were grounded and by
828
+ how many sources, which carried unexamined assumptions, which were
829
+ revised and how often, and what arithmetic produced each tier -- all
830
+ exists on every Claim and reaches /output/<run_id>/, and none of it was
831
+ reachable from either shell. So a run could be read only as prose,
832
+ with the confidence machinery that is the point of the pipeline
833
+ visible nowhere.
834
+
835
+ A MODAL rather than transcript rows: a dozen claims at this detail is
836
+ longer than the report, and dumping it inline would push the answer
837
+ off screen at the moment it arrives. Scrollable, escape closes.
838
+
839
+ Takes plain DICTS, not Claim objects, and that is deliberate -- the
840
+ three sources are `vars(c)` for a finished in-session run,
841
+ pipeline_storage.load_pipeline_run() for an earlier one (which already
842
+ returns the dicts vars(c) wrote), and the partial picture assembled
843
+ from PipelineEvents while a run is still going. One shape here means
844
+ no branch inside the renderer, and it is the shape §5 already
845
+ persists.
846
+ """
847
+
848
+ BINDINGS = [("escape", "close", "Close")]
849
+
850
+ def __init__(self, claims: list, title: str = "Claims",
851
+ partial: bool = False):
852
+ super().__init__()
853
+ self._claims = list(claims or [])
854
+ self._title = title
855
+ self._partial = partial
856
+
857
+ def compose(self) -> ComposeResult:
858
+ # core/claims_view.py says what the view shows (§89), so the
859
+ # CLI's /claims and this screen cannot disagree about a run.
860
+ header = claims_header(self._title, len(self._claims),
861
+ self._partial)
862
+ yield Vertical(
863
+ Label(Text(header), id="claims-title"),
864
+ # A ScrollBox, not a `max-height` Static (batch 49). EP3's
865
+ # second rule was right about this one: a Static's
866
+ # virtual_size follows its clamped box, so a run with more
867
+ # claims than fit had the remainder GONE rather than below
868
+ # the fold, on the one screen whose entire purpose is showing
869
+ # all of them.
870
+ ScrollBox(Static(Text(render_claims(self._claims)),
871
+ id="claims-body"),
872
+ id="claims-body-box"),
873
+ id="claims-dialog",
874
+ )
875
+
876
+ def action_close(self) -> None:
877
+ self.dismiss(None)
878
+
879
+
880
+ class ConfirmScreen(ModalScreen[bool]):
881
+ """A titled yes/no over a block of text (ROADMAP_v2 §24).
882
+
883
+ PermissionScreen is the wrong shape here even though it also returns a
884
+ bool: it titles itself "Allow <tool>?" and renders params as JSON,
885
+ because it exists to gate ONE tool call. /init's question is about a
886
+ set of files, and the substance is the diff -- so the body is text the
887
+ caller composed and the title says what is being decided.
888
+
889
+ Escape declines rather than dismissing with no value. Fifth place that
890
+ invariant applies, and here the unsafe failure is a worker parked on a
891
+ queue nobody will answer.
892
+ """
893
+
894
+ BINDINGS = [("escape", "decline", "No")]
895
+
896
+ def __init__(self, title: str, body: str, confirm_label: str = "Yes"):
897
+ super().__init__()
898
+ self._title = title
899
+ self._body = body
900
+ self._confirm_label = confirm_label
901
+
902
+ def compose(self) -> ComposeResult:
903
+ yield Vertical(
904
+ Label(Text(self._title), id="permission-title"),
905
+ # The body is a DIFF (/init's file list), so it is the one
906
+ # here most able to outgrow the dialog -- 30 files measured at
907
+ # 36 rows of content in a 16-row box, which took both buttons
908
+ # off the bottom with it. Bounded and scrollable like the
909
+ # payload block, for the same reason.
910
+ ScrollBox(Static(Text(self._body), id="permission-params"),
911
+ id="permission-params-box"),
912
+ Horizontal(
913
+ Button(Text(self._confirm_label), variant="success",
914
+ id="allow"),
915
+ Button("No", variant="error", id="deny"),
916
+ id="permission-buttons"),
917
+ id="permission-dialog",
918
+ )
919
+
920
+ def on_mount(self) -> None:
921
+ # See PermissionScreen.on_mount. This screen is where Enter
922
+ # actually said yes: its body was a plain Static, so the
923
+ # affirmative button was the first focusable widget on it.
924
+ self.query_one("#deny", Button).focus()
925
+
926
+ def on_button_pressed(self, event: Button.Pressed) -> None:
927
+ self.dismiss(event.button.id == "allow")
928
+
929
+ def action_decline(self) -> None:
930
+ self.dismiss(False)
931
+
932
+
933
+ class NoticeScreen(ModalScreen[None]):
934
+ """Something to read and acknowledge, with one button (ROADMAP_v3 §83,
935
+ CG8).
936
+
937
+ OpenAI's guidelines for Sign in with ChatGPT ask for a notice the first
938
+ time someone signs in with plan usage on: that eligible requests use
939
+ their ChatGPT plan and that usage is managed in ChatGPT's settings,
940
+ titled "You're using your ChatGPT plan", with "Got it". There is no
941
+ decision in it, so it is not a ConfirmScreen with the No hidden: Enter,
942
+ Escape and the button all mean the one thing it can mean.
943
+ """
944
+
945
+ BINDINGS = [("escape", "acknowledge", "Got it")]
946
+
947
+ def __init__(self, title: str, body: str, button_label: str = "Got it"):
948
+ super().__init__()
949
+ self._title = title
950
+ self._body = body
951
+ self._button_label = button_label
952
+
953
+ def compose(self) -> ComposeResult:
954
+ yield Vertical(
955
+ Label(Text(self._title), id="permission-title"),
956
+ ScrollBox(Static(Text(self._body), id="permission-params"),
957
+ id="permission-params-box"),
958
+ Horizontal(
959
+ Button(Text(self._button_label), variant="primary",
960
+ id="notice-ok"),
961
+ id="permission-buttons"),
962
+ id="permission-dialog",
963
+ )
964
+
965
+ def on_mount(self) -> None:
966
+ self.query_one("#notice-ok", Button).focus()
967
+
968
+ def on_button_pressed(self, event: Button.Pressed) -> None:
969
+ self.dismiss(None)
970
+
971
+ def action_acknowledge(self) -> None:
972
+ self.dismiss(None)
973
+
974
+
975
+ class ProjectKindScreen(ModalScreen[object]):
976
+ """Which document set /init scaffolds (§24, I13).
977
+
978
+ Dismisses with "software", "research", or None to cancel -- three
979
+ answers, not a bool, because cancelling is not the same as picking the
980
+ other one.
981
+
982
+ An established project arrives here with a PROPOSAL and the reason for
983
+ it, so the user is confirming a finding. A blank folder arrives with
984
+ neither: there is nothing to infer from, and a proposal would be a
985
+ guess wearing a finding's clothes.
986
+ """
987
+
988
+ BINDINGS = [("escape", "cancel", "Cancel")]
989
+
990
+ def __init__(self, proposal=None, reason: str = "", blank: bool = False):
991
+ super().__init__()
992
+ self._proposal = proposal
993
+ self._reason = reason
994
+ self._blank = blank
995
+
996
+ def compose(self) -> ComposeResult:
997
+ if self._blank:
998
+ explanation = ("This folder is empty, so there is nothing to go "
999
+ "on. Which kind of project is this?")
1000
+ elif self._proposal:
1001
+ explanation = (f"This looks like a {self._proposal} project — "
1002
+ f"{self._reason}. Change it if that is wrong.")
1003
+ else:
1004
+ explanation = "Which kind of project is this?"
1005
+ yield Vertical(
1006
+ Label("Set up documentation for which kind of project?",
1007
+ id="permission-title"),
1008
+ ScrollBox(Static(
1009
+ Text(
1010
+ f"{explanation}\n\n"
1011
+ "software — ARCHITECTURE, ROADMAP, DEVLOG, "
1012
+ "TECHNICAL_DEBT, DOCUMENTATION_STANDARDS, "
1013
+ "TEST_WRITING, BREAKING_CHANGES\n"
1014
+ "research — RESEARCH_QUESTIONS, METHODOLOGY, "
1015
+ "SOURCES, FINDINGS, LIMITATIONS, EXPERIMENT_LOG, "
1016
+ "OPEN_QUESTIONS, DOCUMENTATION_STANDARDS"),
1017
+ id="permission-params"),
1018
+ id="permission-params-box"),
1019
+ Horizontal(
1020
+ Button("Software", variant="success", id="kind-software"),
1021
+ Button("Research", variant="primary", id="kind-research"),
1022
+ id="permission-buttons"),
1023
+ id="permission-dialog",
1024
+ )
1025
+
1026
+ def on_button_pressed(self, event: Button.Pressed) -> None:
1027
+ self.dismiss("research" if event.button.id == "kind-research"
1028
+ else "software")
1029
+
1030
+ def action_cancel(self) -> None:
1031
+ self.dismiss(None)
1032
+
1033
+
1034
+ class AgentPickerScreen(ModalScreen[object]):
1035
+ """Pick a run to read. Dismisses with a thread id, or None (§47).
1036
+
1037
+ THE KEYBOARD ROUTE to what the sidebar offers on a click. The
1038
+ sidebar is deliberately not focusable -- batch 59 refused a tab
1039
+ stop and refused to take the arrow keys the suggestion panel
1040
+ uses -- so making its rows clickable made navigation reachable by
1041
+ mouse only. A key-bound picker keeps the panel as it is and
1042
+ mirrors ctrl+t, which is already this project's answer to
1043
+ "choose a thread".
1044
+
1045
+ Only runs that HAVE a thread are listed. A row for one that
1046
+ cannot be opened would be a control that does nothing, which is
1047
+ the rule the sidebar's unbound rows already follow.
1048
+ """
1049
+
1050
+ BINDINGS = [("escape", "cancel", "Cancel")]
1051
+
1052
+ def __init__(self, runs: list[dict]):
1053
+ super().__init__()
1054
+ self._runs = runs
1055
+
1056
+ def compose(self) -> ComposeResult:
1057
+ items = [
1058
+ # Indented by the LINEAGE LEVEL the app read off
1059
+ # `widgets.lineage_rows`, which is the walk the sidebar
1060
+ # indents by -- not `AgentRow.depth`, which is the spawn
1061
+ # bound and parts company with the column wherever a span
1062
+ # adds a display level without adding a spawn level.
1063
+ # `Text(...)` for RA1's reason: an agent name comes from a
1064
+ # file this project did not necessarily write. Finished
1065
+ # runs read muted: they open like any other row, so the
1066
+ # mark is de-emphasis rather than a warning, and `live`
1067
+ # defaults True so a hand-built row renders as running.
1068
+ ListItem(
1069
+ Label(Text(
1070
+ f"{' ' * run.get('level', 0)}{run['label']}")),
1071
+ classes="" if run.get("live", True) else "finished")
1072
+ for run in self._runs
1073
+ ]
1074
+ children = [Label("Read which run?", id="agent-picker-title")]
1075
+ if items:
1076
+ children.append(ListView(*items, id="agent-picker-list"))
1077
+ else:
1078
+ children.append(Static(
1079
+ "Nothing is running, and this conversation has not "
1080
+ "started yet.", id="agent-picker-empty"))
1081
+ yield Vertical(*children, id="agent-picker-dialog")
1082
+
1083
+ def on_list_view_selected(self, event: ListView.Selected) -> None:
1084
+ index = event.list_view.index
1085
+ if index is not None and 0 <= index < len(self._runs):
1086
+ self.dismiss(self._runs[index]["thread_id"])
1087
+ else:
1088
+ self.dismiss(None)
1089
+
1090
+ def action_cancel(self) -> None:
1091
+ self.dismiss(None)
1092
+
1093
+
1094
+ class SessionKillScreen(ModalScreen[object]):
1095
+ """Pick a background session to stop. Dismisses with a session id, or
1096
+ None to cancel (ROADMAP_v3 §49, SS2).
1097
+
1098
+ ALWAYS A PICKER, including for a single session, and that is a
1099
+ decision rather than a simplification. §49's adopted default killed
1100
+ outright when exactly one was live and showed this list only for
1101
+ several, which made one key mean two things -- and the destructive
1102
+ one was the case that needed no confirmation. A one-row list costs a
1103
+ keypress and removes the mistyped-ctrl+b case entirely.
1104
+
1105
+ It is also the only thing on screen that says what is running until
1106
+ the sidebar panel lands, which is why the rows carry the command and
1107
+ not just an id.
1108
+
1109
+ The rows arrive already rendered and already REDACTED: the command
1110
+ goes through the same output policy the model's own view of it does,
1111
+ because a modal is a display surface like any other and a secret does
1112
+ not become safe by being shown to the person who typed it.
1113
+ """
1114
+
1115
+ BINDINGS = [("escape", "cancel", "Cancel")]
1116
+
1117
+ def __init__(self, rows: list[dict]):
1118
+ super().__init__()
1119
+ self._rows = rows
1120
+
1121
+ def compose(self) -> ComposeResult:
1122
+ items = [ListItem(Label(Text(row["label"]))) for row in self._rows]
1123
+ children = [Label("Stop which session?", id="session-kill-title")]
1124
+ if items:
1125
+ children.append(ListView(*items, id="session-kill-list"))
1126
+ else:
1127
+ children.append(Static("Nothing is running.",
1128
+ id="session-kill-empty"))
1129
+ yield Vertical(*children, id="session-kill-dialog")
1130
+
1131
+ def on_list_view_selected(self, event: ListView.Selected) -> None:
1132
+ index = event.list_view.index
1133
+ if index is not None and 0 <= index < len(self._rows):
1134
+ self.dismiss(self._rows[index]["id"])
1135
+ else:
1136
+ self.dismiss(None)
1137
+
1138
+ def action_cancel(self) -> None:
1139
+ self.dismiss(None)
1140
+
1141
+
1142
+ class ThreadPickerScreen(ModalScreen[object]):
1143
+ """Pick a thread to resume. Dismisses with a UUID, or None to cancel.
1144
+
1145
+ Reads storage.list_threads(), which since §27 returns CONVERSATIONS only
1146
+ -- a research run creates ~15 threads of machinery and every automatic
1147
+ compaction one more, and all of them used to be offered here as things
1148
+ to resume.
1149
+
1150
+ A row leads with the thread's first user message (§27), because a list
1151
+ of uuids and timestamps was still unusable once it was short: filtering
1152
+ made the picker correct, and the preview is what makes it answerable.
1153
+ The id stays, since it is what --thread and /resume take.
1154
+
1155
+ `note` carries one line shown under the title when the list is not the
1156
+ whole story (#30/#32): the picker caps at PICKER_LIMIT rows, and a cap
1157
+ that does not say so reads as "this is everything" (M14's rule). Older
1158
+ conversations remain reachable by id via /resume.
1159
+ """
1160
+
1161
+ BINDINGS = [("escape", "cancel", "Cancel")]
1162
+
1163
+ def __init__(self, threads: list[dict], note: str = ""):
1164
+ super().__init__()
1165
+ self._threads = threads
1166
+ self._note = note
1167
+
1168
+ def compose(self) -> ComposeResult:
1169
+ items = [ListItem(Label(Text(thread_row(t))))
1170
+ for t in self._threads]
1171
+ children = [Label("Resume which thread?", id="thread-title")]
1172
+ if self._note:
1173
+ children.append(Static(Text(self._note),
1174
+ id="thread-note"))
1175
+ if items:
1176
+ children.append(ListView(*items, id="thread-list"))
1177
+ else:
1178
+ children.append(Static("No saved threads yet.", id="thread-empty"))
1179
+ yield Vertical(*children, id="thread-dialog")
1180
+
1181
+ def on_list_view_selected(self, event: ListView.Selected) -> None:
1182
+ index = event.list_view.index
1183
+ if index is not None and 0 <= index < len(self._threads):
1184
+ self.dismiss(self._threads[index]["id"])
1185
+ else:
1186
+ self.dismiss(None)
1187
+
1188
+ def action_cancel(self) -> None:
1189
+ self.dismiss(None)
1190
+
1191
+
1192
+ class SecretScreen(ModalScreen[object]):
1193
+ """Ask for one secret, masked (ROADMAP_v3 §49 slice 5a, SS59).
1194
+
1195
+ THE FIRST MASKED INPUT IN THIS PROJECT, which is why it is its own
1196
+ screen rather than a flag on QuestionScreen. The KIND is what tells a
1197
+ shell how to render (§23 AC1), and here the rendering IS the substance: a
1198
+ flag that a screen forgot to read would show the passphrase in clear
1199
+ while every test about the plumbing still passed.
1200
+
1201
+ Four properties this screen owes, none of which QuestionScreen has:
1202
+
1203
+ * `password=True`, so the characters are never drawn;
1204
+ * the value is dismissed and NOTHING ELSE. It is not put in a
1205
+ reactive, not logged, not echoed into the transcript, and not kept
1206
+ on the screen object past `dismiss` -- `on_button_pressed` reads
1207
+ the widget and hands the string straight out;
1208
+ * Escape and the Cancel button dismiss with None, which
1209
+ `interaction.decode` turns into the declining default. A dismissed
1210
+ passphrase prompt must not become an empty passphrase, because an
1211
+ empty passphrase is an authentication ATTEMPT (SS59);
1212
+ * Enter submits, because a password field that needs a mouse is a
1213
+ password field people paste into something else first.
1214
+ """
1215
+
1216
+ BINDINGS = [("escape", "cancel", "Cancel")]
1217
+
1218
+ def __init__(self, title: str, body: str = "",
1219
+ confirm_label: str = "Unlock"):
1220
+ super().__init__()
1221
+ self._title = title
1222
+ self._body = body
1223
+ self._confirm_label = confirm_label
1224
+
1225
+ def compose(self) -> ComposeResult:
1226
+ widgets = [Label(Text(self._title), id="permission-title")]
1227
+ if self._body:
1228
+ widgets.append(
1229
+ ScrollBox(Static(Text(self._body), id="permission-params"),
1230
+ id="permission-params-box"))
1231
+ widgets.append(Input(password=True, id="secret-value"))
1232
+ widgets.append(Horizontal(
1233
+ Button(Text(self._confirm_label), variant="success",
1234
+ id="secret-ok"),
1235
+ Button("Cancel", variant="error", id="secret-cancel"),
1236
+ id="permission-buttons"))
1237
+ yield Vertical(*widgets, id="permission-dialog")
1238
+
1239
+ def on_mount(self) -> None:
1240
+ self.query_one("#secret-value", Input).focus()
1241
+
1242
+ def _submit(self) -> None:
1243
+ self.dismiss(self.query_one("#secret-value", Input).value)
1244
+
1245
+ def on_input_submitted(self, event: Input.Submitted) -> None:
1246
+ self._submit()
1247
+
1248
+ def on_button_pressed(self, event: Button.Pressed) -> None:
1249
+ if event.button.id == "secret-ok":
1250
+ self._submit()
1251
+ else:
1252
+ self.dismiss(None)
1253
+
1254
+ def action_cancel(self) -> None:
1255
+ self.dismiss(None)