@yahyahammad/venastine 0.2.0 → 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 (152) hide show
  1. package/.env.example +9 -4
  2. package/CONFIG_ARCHITECTURE.md +2030 -0
  3. package/LICENSE +201 -201
  4. package/NOTICE +1 -1
  5. package/README.md +1034 -895
  6. package/agents/builtin/build.md +73 -0
  7. package/agents/builtin/compactor.md +75 -75
  8. package/agents/builtin/explore.md +77 -77
  9. package/agents/builtin/general.md +80 -0
  10. package/agents/builtin/pipeline-reviewer.md +100 -100
  11. package/agents/builtin/plan.md +106 -88
  12. package/agents/builtin/review.md +74 -74
  13. package/agents/builtin/test.md +65 -0
  14. package/agents/builtin/writer.md +67 -0
  15. package/agents/manager.py +68 -2
  16. package/agents/subagent_tool.py +472 -238
  17. package/agents/tui_commands.py +238 -151
  18. package/bin/venastine.mjs +150 -4
  19. package/bin/venastine.py +71 -0
  20. package/cli_commands.py +838 -0
  21. package/config.py +95 -1198
  22. package/config.yaml +1103 -0
  23. package/config_edit.py +1301 -0
  24. package/config_schema.py +971 -0
  25. package/config_update.py +749 -0
  26. package/core/agent_activity.py +256 -118
  27. package/core/ansi.py +452 -0
  28. package/core/approval.py +137 -115
  29. package/core/call_view.py +364 -0
  30. package/core/cancel.py +121 -0
  31. package/core/chatgpt_auth.py +747 -0
  32. package/core/claims_view.py +107 -0
  33. package/core/client.py +2715 -1559
  34. package/core/commands.py +460 -0
  35. package/core/compaction.py +1735 -971
  36. package/core/config_loader.py +1982 -1563
  37. package/core/connect.py +686 -0
  38. package/core/events.py +123 -61
  39. package/core/file_mentions.py +280 -0
  40. package/core/interaction.py +411 -328
  41. package/core/line_pattern.py +128 -0
  42. package/core/loop.py +2566 -1490
  43. package/core/memory.py +482 -370
  44. package/core/pipeline_models.py +190 -176
  45. package/core/provider_errors.py +234 -0
  46. package/core/reasoning/authorization.py +130 -130
  47. package/core/reasoning/base.py +219 -219
  48. package/core/reasoning/confidence_scoring.py +484 -468
  49. package/core/reasoning/events.py +149 -149
  50. package/core/reasoning/json_retry.py +19 -1
  51. package/core/reasoning/orchestrator.py +1561 -1382
  52. package/core/reasoning/output_writer.py +345 -286
  53. package/core/reasoning/payload_validation.py +524 -398
  54. package/core/reasoning/pipeline_storage.py +88 -22
  55. package/core/reasoning/review.py +659 -615
  56. package/core/reasoning/scholar.py +458 -434
  57. package/core/reasoning/source_corpus.py +433 -327
  58. package/core/reasoning/source_scoring.py +855 -855
  59. package/core/replay.py +315 -183
  60. package/core/session.py +36 -12
  61. package/core/session_view.py +259 -0
  62. package/core/session_wake.py +259 -0
  63. package/core/shell_sessions.py +1553 -0
  64. package/core/workspace_trust.py +1 -1
  65. package/credentials.py +148 -20
  66. package/database.py +333 -252
  67. package/{PRIVACY.md → docs/PRIVACY.md} +78 -66
  68. package/docs/SECURITY.md +108 -0
  69. package/docs/THIRD_PARTY_NOTICES.md +148 -0
  70. package/env_secrets.py +50 -9
  71. package/json_store.py +343 -123
  72. package/logging_setup.py +295 -185
  73. package/main.py +3433 -1961
  74. package/mcp_client/client.py +733 -499
  75. package/mcp_client/config.py +126 -21
  76. package/mcp_client/registration.py +343 -182
  77. package/memories/manager.py +147 -132
  78. package/memories/tui_commands.py +319 -244
  79. package/package.json +303 -73
  80. package/project_init/config_files.py +282 -278
  81. package/project_init/generator.py +728 -564
  82. package/project_init/manifest.py +18 -6
  83. package/project_init/tui_commands.py +147 -144
  84. package/prompts/critic_pass.md +24 -24
  85. package/prompts/revalidate.md +25 -25
  86. package/prompts/revise.md +2 -0
  87. package/prompts/source_grounding.md +66 -66
  88. package/prompts/system_prompts.py +316 -262
  89. package/providers.json.example +4 -2
  90. package/pyproject.toml +149 -100
  91. package/requirements.txt +295 -72
  92. package/safety/policy_enforcement.py +1082 -746
  93. package/security/askpass.py +419 -0
  94. package/security/capability.py +207 -177
  95. package/security/confine.py +484 -0
  96. package/security/hosted.py +182 -0
  97. package/security/permissions.py +237 -190
  98. package/security/posture.py +124 -12
  99. package/security/protected_paths.py +501 -309
  100. package/security/sandbox.py +4108 -985
  101. package/security/secrets.py +855 -0
  102. package/skills/builtin/math/formal-specification.md +67 -67
  103. package/skills/builtin/math/numerical-methods.md +66 -66
  104. package/skills/builtin/research/experiment-design.md +62 -62
  105. package/skills/builtin/research/reproducibility.md +55 -55
  106. package/skills/builtin/research/source-evaluation.md +70 -70
  107. package/skills/builtin/research/statistical-inference.md +63 -63
  108. package/skills/builtin/research/technical-writing.md +59 -59
  109. package/skills/builtin/software/code-review.md +61 -61
  110. package/skills/builtin/software/debugging.md +61 -61
  111. package/skills/builtin/software/test-design.md +67 -67
  112. package/skills/tui_commands.py +110 -111
  113. package/storage.py +1338 -1005
  114. package/tools/base.py +161 -1
  115. package/tools/builtin/_math_common.py +667 -377
  116. package/tools/builtin/_net_common.py +225 -19
  117. package/tools/builtin/arxiv.py +497 -39
  118. package/tools/builtin/ask_user.py +231 -213
  119. package/tools/builtin/discrete_math.py +35 -4
  120. package/tools/builtin/fetch_url.py +371 -153
  121. package/tools/builtin/file_ops.py +720 -412
  122. package/tools/builtin/geometry.py +48 -12
  123. package/tools/builtin/get_time.py +2 -2
  124. package/tools/builtin/linear_algebra.py +66 -23
  125. package/tools/builtin/load_skill.py +76 -66
  126. package/tools/builtin/logic.py +171 -12
  127. package/tools/builtin/pin.py +227 -193
  128. package/tools/builtin/probability_stats.py +12 -16
  129. package/tools/builtin/project_docs.py +464 -405
  130. package/tools/builtin/remember.py +175 -158
  131. package/tools/builtin/shell.py +980 -461
  132. package/tools/builtin/shell_sessions.py +613 -0
  133. package/tools/builtin/symbolic_math.py +80 -10
  134. package/tools/builtin/todo.py +149 -147
  135. package/tools/builtin/web_search.py +191 -13
  136. package/tools/context.py +159 -136
  137. package/tools/isolation.py +107 -34
  138. package/tools/registry.py +1242 -925
  139. package/tui/app.py +8318 -4100
  140. package/tui/app.tcss +747 -556
  141. package/tui/commands.py +26 -170
  142. package/tui/diffs.py +34 -13
  143. package/tui/history.py +128 -128
  144. package/tui/hosted_driver.py +102 -0
  145. package/tui/markdown.py +1329 -1279
  146. package/tui/meters.py +364 -268
  147. package/tui/ravens.py +146 -146
  148. package/tui/screens.py +1255 -943
  149. package/tui/themes.py +599 -559
  150. package/tui/widgets.py +3813 -2332
  151. package/SECURITY.md +0 -88
  152. package/THIRD_PARTY_NOTICES.md +0 -100
package/tui/commands.py CHANGED
@@ -1,170 +1,26 @@
1
- """
2
- tui/commands.py
3
-
4
- ROADMAP_v2 §16 slash-command registry.
5
-
6
- The registry is §16's; the commands registered into it are not all §16's.
7
- D7 assigns `/skill <name>` to §19, and §18/§21 add their own -- each
8
- registers here rather than editing a match statement in the app, which is
9
- the same mechanism-vs-policy split tools/registry.py already uses for
10
- tools.
11
-
12
- A handler takes (app, argument_string) and returns None. It runs on the UI
13
- thread, so anything slow belongs in a worker.
14
- """
15
-
16
- from dataclasses import dataclass
17
- from typing import Callable, Optional
18
-
19
-
20
- @dataclass
21
- class SlashCommand:
22
- name: str # without the leading slash
23
- summary: str # one line, shown by /help
24
- handler: Callable # (app, args: str) -> None
25
- usage: Optional[str] = None # shown by /help when the shape is not obvious
26
- # Other names the same command answers to (batch 57). A FIELD rather
27
- # than two more registrations, and the difference is what the LISTS
28
- # say: `all()` and `names()` stay canonical, so `/help` prints one row
29
- # per command and a bare slash still offers the menu it always did.
30
- # Registering `/exit` and `/bye` outright would have sorted `bye`
31
- # second in that menu, ahead of `/claims`, for a name nobody browses
32
- # for -- and moved every window position batch 56 measured.
33
- aliases: tuple[str, ...] = ()
34
-
35
-
36
- class CommandRegistry:
37
- def __init__(self) -> None:
38
- self._commands: dict[str, SlashCommand] = {}
39
- # alias -> canonical name. A second index rather than a scan, and
40
- # it is what makes an alias collision detectable at REGISTRATION
41
- # instead of at the keystroke that silently reached the wrong
42
- # handler.
43
- self._aliases: dict[str, str] = {}
44
-
45
- def register(self, command: SlashCommand) -> None:
46
- """Register by name; re-registering the same name overwrites.
47
-
48
- Idempotent on purpose -- `register_builtin_commands()` runs on
49
- import AND is called again by tests, so a second pass must not
50
- duplicate or raise.
51
-
52
- An alias that would shadow something REFUSES, both ways round: a
53
- name already taken by a command, and a command name already taken
54
- by somebody's alias. Both resolve silently otherwise -- `get()`
55
- prefers real names, so the alias would simply stop working and
56
- nothing would say why.
57
- """
58
- for alias in command.aliases:
59
- if alias in self._commands:
60
- raise ValueError(
61
- f"/{alias} is already a command; it cannot also be an "
62
- f"alias of /{command.name}")
63
- owner = self._aliases.get(alias)
64
- if owner is not None and owner != command.name:
65
- raise ValueError(
66
- f"/{alias} is already an alias of /{owner}; it cannot "
67
- f"also be an alias of /{command.name}")
68
- owner = self._aliases.get(command.name)
69
- if owner is not None and owner != command.name:
70
- raise ValueError(
71
- f"/{command.name} is already an alias of /{owner}")
72
- old = self._commands.get(command.name)
73
- if old is not None:
74
- for alias in old.aliases:
75
- if alias not in command.aliases \
76
- and self._aliases.get(alias) == command.name:
77
- del self._aliases[alias]
78
- self._commands[command.name] = command
79
- for alias in command.aliases:
80
- self._aliases[alias] = command.name
81
-
82
- def get(self, name: str) -> Optional[SlashCommand]:
83
- """The command called `name`, by its own name or by an alias.
84
-
85
- Names win over aliases, which is also the collision `register`
86
- refuses -- so the precedence can never actually be exercised.
87
- """
88
- command = self._commands.get(name)
89
- if command is not None:
90
- return command
91
- canonical = self._aliases.get(name)
92
- return self._commands.get(canonical) if canonical else None
93
-
94
- def names(self) -> list[str]:
95
- return sorted(self._commands)
96
-
97
- def all(self) -> list[SlashCommand]:
98
- return [self._commands[n] for n in self.names()]
99
-
100
- def matching(self, text: str) -> list[SlashCommand]:
101
- """Commands whose name starts with the token in `text`.
102
-
103
- The suggestion panel's source, and it reads `all()` so the panel and
104
- `/help` cannot disagree about what exists -- register a command
105
- anywhere and both change, which is the whole reason the matching
106
- lives here rather than in the widget.
107
-
108
- Empty unless `text` is a BARE slash token: leading whitespace
109
- allowed (`dispatch` tolerates it, so `" /help"` runs and had
110
- better offer), a leading `/`, and NO whitespace after that.
111
-
112
- `lstrip`, not `strip`, and the difference is a bug this had: a
113
- TRAILING space survives `strip()`, so `"/copy "` read as `"/copy"`
114
- and the panel stayed open over a line that had already moved on to
115
- its arguments. Once a space is typed there is nothing left to
116
- complete, whichever end of the token it is on.
117
-
118
- Lowercased for the same reason `dispatch` lowercases: `/HELP` runs,
119
- so `/HEL` had better offer it.
120
-
121
- ALIASES join the list once a prefix is typed, and never on a bare
122
- slash (batch 57). The bare slash is the MENU -- it is what someone
123
- who does not know the commands presses, and a menu lists each
124
- thing once, under its own name. `/ex` is not browsing: it is a
125
- guess, and the answer to a guess is whether it works. So
126
- `matching("/") == all()` still holds exactly, and typing toward an
127
- alias surfaces it.
128
- """
129
- token = text.lstrip()
130
- if not token.startswith("/") or any(c.isspace() for c in token):
131
- return []
132
- prefix = token[1:].lower()
133
- matches = [c for c in self.all() if c.name.startswith(prefix)]
134
- if not prefix:
135
- return matches
136
- matches.extend(self._alias_row(a) for a in self._aliases
137
- if a.startswith(prefix))
138
- return sorted(matches, key=lambda command: command.name)
139
-
140
- def _alias_row(self, alias: str) -> SlashCommand:
141
- """One offer for `alias`, carrying the canonical command's handler.
142
-
143
- A real `SlashCommand` rather than a flag on the canonical one, so
144
- the panel needs to know nothing about aliases: it draws the name
145
- it is given and completes the name it drew, which has to be the
146
- alias the user was typing rather than the name they were not.
147
- """
148
- command = self._commands[self._aliases[alias]]
149
- return SlashCommand(
150
- alias, f"{command.summary} (alias of /{command.name})",
151
- command.handler, command.usage)
152
-
153
- def dispatch(self, app, raw: str) -> bool:
154
- """Run the command in `raw` (a line starting with '/').
155
-
156
- Returns True if a command handled the line, False if the name is
157
- unknown -- the caller decides what to do about it. Unknown names are
158
- NOT sent to the model: a mistyped slash command should say so, not
159
- silently become a chat turn that burns a request.
160
- """
161
- stripped = raw[1:].strip()
162
- name, _, args = stripped.partition(" ")
163
- command = self.get(name.lower())
164
- if command is None:
165
- return False
166
- command.handler(app, args.strip())
167
- return True
168
-
169
-
170
- registry = CommandRegistry()
1
+ """
2
+ tui/commands.py
3
+
4
+ ROADMAP_v2 §16 slash-command registry -- the TUI's.
5
+
6
+ The registry is §16's; the commands registered into it are not all §16's.
7
+ D7 assigns `/skill <name>` to §19, and §18/§21 add their own -- each
8
+ registers here rather than editing a match statement in the app, which is
9
+ the same mechanism-vs-policy split tools/registry.py already uses for
10
+ tools.
11
+
12
+ Since ROADMAP_v3 §89 (#8) the MECHANISM lives in `core/commands.py`, beside
13
+ the catalog both shells bind to, because the CLI binds to it too and must
14
+ not import from `tui/` to do so. This module is the TUI's registry
15
+ instance: it takes only what the catalog declares for the TUI, built with
16
+ `bind()`.
17
+
18
+ A handler takes (app, argument_string) and returns None. It runs on the UI
19
+ thread, so anything slow belongs in a worker.
20
+ """
21
+
22
+ from core.commands import TUI, CommandRegistry, SlashCommand, bind
23
+
24
+ __all__ = ["CommandRegistry", "SlashCommand", "bind", "registry"]
25
+
26
+ registry = CommandRegistry(TUI)
package/tui/diffs.py CHANGED
@@ -46,7 +46,9 @@ the call's own arguments and need no file at all.
46
46
  from __future__ import annotations
47
47
 
48
48
  import difflib
49
- from typing import List, Optional, Tuple
49
+ from typing import Optional
50
+
51
+ from rich.cells import cell_len
50
52
 
51
53
  #: Lines of unchanged context either side of a change.
52
54
  CONTEXT_LINES = 3
@@ -71,7 +73,7 @@ _ELIDE_MARK = "…"
71
73
  #: (kind, gutter, text). `gutter` is a string, not an int: a `-` row
72
74
  #: carries the OLD line number and a `+` row the NEW one, and a row from a
73
75
  #: degraded block carries neither.
74
- Row = Tuple[str, str, str]
76
+ Row = tuple[str, str, str]
75
77
 
76
78
 
77
79
  def build_block(path: str, pre: Optional[str], post: str, *,
@@ -106,13 +108,21 @@ def wrap_source(text: str, width: int) -> list:
106
108
  would land on the first rendered row only, so a wrapped addition
107
109
  would be half green. Width <= 0 means nothing is measurable (a
108
110
  widget built bare in the suite) and the line is returned whole.
111
+
112
+ IN CELLS, NOT CHARACTERS (#224, batch 214), because the terminal
113
+ measures cells: twenty double-width characters are twenty `len` and
114
+ forty cells, so a row this sized as fitting was one Rich wrapped
115
+ itself, with the background landing on half of it -- the very thing
116
+ the pre-wrap exists to prevent. A glyph wider than the row is kept
117
+ whole for Rich to wrap, as `markdown.plain_split` does.
109
118
  """
110
- if width <= 0 or len(text) <= width:
119
+ if width <= 0 or cell_len(text) <= width:
111
120
  return [text]
112
121
  rows, rest = [], text
113
- while len(rest) > width:
114
- space = rest.rfind(" ", 1, width + 1)
115
- cut = space if space > 0 else width
122
+ while cell_len(rest) > width:
123
+ fit = _chars_within(rest, width)
124
+ space = rest.rfind(" ", 1, fit + 1)
125
+ cut = space if space > 0 else fit
116
126
  rows.append(rest[:cut])
117
127
  rest = rest[cut:].lstrip(" ") if space > 0 else rest[cut:]
118
128
  if not rest:
@@ -122,6 +132,17 @@ def wrap_source(text: str, width: int) -> list:
122
132
  return rows
123
133
 
124
134
 
135
+ def _chars_within(text: str, width: int) -> int:
136
+ """How many leading characters of `text` fit in `width` cells -- at
137
+ least one, so a glyph wider than the row still makes progress."""
138
+ cells = 0
139
+ for index, char in enumerate(text):
140
+ cells += cell_len(char)
141
+ if cells > width:
142
+ return max(1, index)
143
+ return len(text)
144
+
145
+
125
146
  def build_replacement_block(path: str, old: str, new: str, *,
126
147
  max_rows: int = MAX_ROWS) -> str:
127
148
  """The degraded form for an `edit` whose file could not be read (X6).
@@ -136,7 +157,7 @@ def build_replacement_block(path: str, old: str, new: str, *,
136
157
  return _render(path, _capped(rows, max_rows))
137
158
 
138
159
 
139
- def parse(block: str) -> Tuple[str, List[Row]]:
160
+ def parse(block: str) -> tuple[str, list[Row]]:
140
161
  """A block back into (path, rows). The renderer's half of the format.
141
162
 
142
163
  Tolerant by construction: a line this cannot make sense of comes back
@@ -147,7 +168,7 @@ def parse(block: str) -> Tuple[str, List[Row]]:
147
168
  """
148
169
  lines = block.split("\n")
149
170
  path = lines[0] if lines else ""
150
- rows: List[Row] = []
171
+ rows: list[Row] = []
151
172
  for line in lines[1:]:
152
173
  if not line:
153
174
  continue
@@ -170,7 +191,7 @@ def parse(block: str) -> Tuple[str, List[Row]]:
170
191
  # ---- internals ------------------------------------------------------------
171
192
  # ---------------------------------------------------------------------------
172
193
 
173
- def _rows(pre_lines: List[str], post_lines: List[str], context: int) -> List[Row]:
194
+ def _rows(pre_lines: list[str], post_lines: list[str], context: int) -> list[Row]:
174
195
  """Changed lines with `context` unchanged lines either side.
175
196
 
176
197
  `SequenceMatcher` rather than `unified_diff`, because what is wanted
@@ -179,7 +200,7 @@ def _rows(pre_lines: List[str], post_lines: List[str], context: int) -> List[Row
179
200
  format one line after emitting it is the second definition this module
180
201
  exists to avoid.
181
202
  """
182
- rows: List[Row] = []
203
+ rows: list[Row] = []
183
204
  opcodes = difflib.SequenceMatcher(None, pre_lines, post_lines).get_opcodes()
184
205
  if all(tag == "equal" for tag, *_rest in opcodes):
185
206
  return rows
@@ -202,7 +223,7 @@ def _rows(pre_lines: List[str], post_lines: List[str], context: int) -> List[Row
202
223
  return rows
203
224
 
204
225
 
205
- def _equal_rows(post_lines, length, j1, j2, head, tail) -> List[Row]:
226
+ def _equal_rows(post_lines, length, j1, j2, head, tail) -> list[Row]:
206
227
  """One unchanged run, trimmed to `head` lines at its start and `tail`
207
228
  at its end.
208
229
 
@@ -231,7 +252,7 @@ def _equal_rows(post_lines, length, j1, j2, head, tail) -> List[Row]:
231
252
  return rows
232
253
 
233
254
 
234
- def _capped(rows: List[Row], max_rows: int) -> List[Row]:
255
+ def _capped(rows: list[Row], max_rows: int) -> list[Row]:
235
256
  """At most `max_rows`, with the remainder counted rather than dropped
236
257
  silently -- M14's no-silent-caps rule, applied to a rendering."""
237
258
  if max_rows <= 0 or len(rows) <= max_rows:
@@ -243,7 +264,7 @@ def _capped(rows: List[Row], max_rows: int) -> List[Row]:
243
264
  return kept
244
265
 
245
266
 
246
- def _render(path: str, rows: List[Row]) -> str:
267
+ def _render(path: str, rows: list[Row]) -> str:
247
268
  # An EMPTY string when nothing changed, so a caller can treat the
248
269
  # block as falsy rather than inspecting it. `write` with identical
249
270
  # content is a real call and a real no-op, and a block carrying a
package/tui/history.py CHANGED
@@ -1,128 +1,128 @@
1
- """
2
- tui/history.py
3
-
4
- Batch 63. What you already sent, so a misfire does not cost the typing.
5
-
6
- PURE, like `tui/markdown.py`, `tui/diffs.py` and `tui/meters.py` beside it:
7
- no I/O, no `core/` import, no widget, no clock. `tui/app.py` owns the keys
8
- and the box; this owns the arithmetic, so every test here is a function
9
- call rather than a pilot pressing keys at a live TextArea.
10
- """
11
-
12
- # A hundred prompts is more than a sitting produces and costs nothing to
13
- # hold; the cap exists so a very long session cannot grow this without
14
- # bound, not because anyone will reach it.
15
- HISTORY_LIMIT = 100
16
-
17
-
18
- class PromptHistory:
19
- """The prompts submitted this session, and where a browse has got to.
20
-
21
- Session-scoped and in memory: it survives `/new` and `/resume` because
22
- it records what the PERSON typed, not what a thread holds, and a
23
- misfire bad enough to start a new thread is exactly when the text is
24
- wanted back. Nothing here is persisted.
25
-
26
- **Both movers take the box's current text, and that one parameter is
27
- the whole design.** The history remembers what it last handed out, so
28
- a `current` that differs from it means the user has typed since --
29
- which ends the browse and starts a new one with `current` saved as the
30
- draft. Recall a prompt, edit it, press previous again: the edit is not
31
- discarded, it becomes the thing `following()` hands back.
32
-
33
- The alternative was to hook `PromptInput.on_text_area_changed`, where
34
- batch 55's `_api_edit` flag already separates assignment from typing.
35
- It is the wrong seam: that message is POSTED, so the app would be
36
- holding a flag across an async hop, and the panel's own
37
- `SuggestionsChanged` fires on both halves of the split anyway. Asking
38
- the box what it holds, at the only two moments it matters, needs
39
- neither.
40
-
41
- `previous()` STOPS at the oldest entry rather than wrapping. A
42
- suggestion panel wraps because its list is a menu; this is a walk
43
- backwards through time, and arriving at the start of it by pressing a
44
- key twelve times should not deposit you at the end.
45
- """
46
-
47
- def __init__(self) -> None:
48
- self._entries: list[str] = [] # oldest first
49
- # The index being shown, or None when the box holds a live draft.
50
- self._cursor = None
51
- self._draft = ""
52
- # The exact string last handed out. `None` while not browsing.
53
- self._served = None
54
-
55
- def __len__(self) -> int:
56
- """How many prompts are recallable. `check_action` reads this."""
57
- return len(self._entries)
58
-
59
- @property
60
- def browsing(self) -> bool:
61
- """True while a recalled entry is being shown. For tests."""
62
- return self._cursor is not None
63
-
64
- def remember(self, text: str) -> None:
65
- """Record a submitted prompt and end any browse in progress.
66
-
67
- Slash commands included: a mistyped `/research --attended --grant`
68
- is the worst retyping in the shell, and `on_prompt_input_submitted`
69
- is one funnel for both kinds.
70
-
71
- A CONSECUTIVE repeat is not appended twice -- sending the same
72
- thing twice is one thing to walk back past, not two. A repeat with
73
- something else between them is kept, because the order is the
74
- record of what happened.
75
- """
76
- if not text:
77
- return
78
- if not self._entries or self._entries[-1] != text:
79
- self._entries.append(text)
80
- del self._entries[:-HISTORY_LIMIT]
81
- self._forget_browse()
82
-
83
- def previous(self, current: str):
84
- """The next older prompt, or None when there is nowhere to go.
85
-
86
- None means the caller writes nothing -- an empty history, or a
87
- browse already at the oldest entry. The browse state is left
88
- alone in both cases, so a press at the oldest is inert rather
89
- than a reset.
90
- """
91
- if not self._entries:
92
- return None
93
- if not self._is_browsing(current):
94
- self._draft = current
95
- self._cursor = len(self._entries)
96
- if self._cursor == 0:
97
- return None
98
- self._cursor -= 1
99
- self._served = self._entries[self._cursor]
100
- return self._served
101
-
102
- def following(self, current: str):
103
- """The next newer prompt, or the draft once past the newest.
104
-
105
- None when no browse is in progress, which is what makes the key
106
- inert on a box the user is typing into fresh: there is nothing
107
- newer than what they are already looking at.
108
- """
109
- if not self._is_browsing(current):
110
- return None
111
- self._cursor += 1
112
- if self._cursor < len(self._entries):
113
- self._served = self._entries[self._cursor]
114
- return self._served
115
- draft = self._draft
116
- self._forget_browse()
117
- return draft
118
-
119
- # -- internals ----------------------------------------------------------
120
-
121
- def _is_browsing(self, current: str) -> bool:
122
- """Whether `current` is still the string this last handed out."""
123
- return self._cursor is not None and current == self._served
124
-
125
- def _forget_browse(self) -> None:
126
- self._cursor = None
127
- self._draft = ""
128
- self._served = None
1
+ """
2
+ tui/history.py
3
+
4
+ Batch 63. What you already sent, so a misfire does not cost the typing.
5
+
6
+ PURE, like `tui/markdown.py`, `tui/diffs.py` and `tui/meters.py` beside it:
7
+ no I/O, no `core/` import, no widget, no clock. `tui/app.py` owns the keys
8
+ and the box; this owns the arithmetic, so every test here is a function
9
+ call rather than a pilot pressing keys at a live TextArea.
10
+ """
11
+
12
+ # A hundred prompts is more than a sitting produces and costs nothing to
13
+ # hold; the cap exists so a very long session cannot grow this without
14
+ # bound, not because anyone will reach it.
15
+ HISTORY_LIMIT = 100
16
+
17
+
18
+ class PromptHistory:
19
+ """The prompts submitted this session, and where a browse has got to.
20
+
21
+ Session-scoped and in memory: it survives `/new` and `/resume` because
22
+ it records what the PERSON typed, not what a thread holds, and a
23
+ misfire bad enough to start a new thread is exactly when the text is
24
+ wanted back. Nothing here is persisted.
25
+
26
+ **Both movers take the box's current text, and that one parameter is
27
+ the whole design.** The history remembers what it last handed out, so
28
+ a `current` that differs from it means the user has typed since --
29
+ which ends the browse and starts a new one with `current` saved as the
30
+ draft. Recall a prompt, edit it, press previous again: the edit is not
31
+ discarded, it becomes the thing `following()` hands back.
32
+
33
+ The alternative was to hook `PromptInput.on_text_area_changed`, where
34
+ batch 55's `_api_edit` flag already separates assignment from typing.
35
+ It is the wrong seam: that message is POSTED, so the app would be
36
+ holding a flag across an async hop, and the panel's own
37
+ `SuggestionsChanged` fires on both halves of the split anyway. Asking
38
+ the box what it holds, at the only two moments it matters, needs
39
+ neither.
40
+
41
+ `previous()` STOPS at the oldest entry rather than wrapping. A
42
+ suggestion panel wraps because its list is a menu; this is a walk
43
+ backwards through time, and arriving at the start of it by pressing a
44
+ key twelve times should not deposit you at the end.
45
+ """
46
+
47
+ def __init__(self) -> None:
48
+ self._entries: list[str] = [] # oldest first
49
+ # The index being shown, or None when the box holds a live draft.
50
+ self._cursor = None
51
+ self._draft = ""
52
+ # The exact string last handed out. `None` while not browsing.
53
+ self._served = None
54
+
55
+ def __len__(self) -> int:
56
+ """How many prompts are recallable. `check_action` reads this."""
57
+ return len(self._entries)
58
+
59
+ @property
60
+ def browsing(self) -> bool:
61
+ """True while a recalled entry is being shown. For tests."""
62
+ return self._cursor is not None
63
+
64
+ def remember(self, text: str) -> None:
65
+ """Record a submitted prompt and end any browse in progress.
66
+
67
+ Slash commands included: a mistyped `/research --attended --grant`
68
+ is the worst retyping in the shell, and `on_prompt_input_submitted`
69
+ is one funnel for both kinds.
70
+
71
+ A CONSECUTIVE repeat is not appended twice -- sending the same
72
+ thing twice is one thing to walk back past, not two. A repeat with
73
+ something else between them is kept, because the order is the
74
+ record of what happened.
75
+ """
76
+ if not text:
77
+ return
78
+ if not self._entries or self._entries[-1] != text:
79
+ self._entries.append(text)
80
+ del self._entries[:-HISTORY_LIMIT]
81
+ self._forget_browse()
82
+
83
+ def previous(self, current: str):
84
+ """The next older prompt, or None when there is nowhere to go.
85
+
86
+ None means the caller writes nothing -- an empty history, or a
87
+ browse already at the oldest entry. The browse state is left
88
+ alone in both cases, so a press at the oldest is inert rather
89
+ than a reset.
90
+ """
91
+ if not self._entries:
92
+ return None
93
+ if not self._is_browsing(current):
94
+ self._draft = current
95
+ self._cursor = len(self._entries)
96
+ if self._cursor == 0:
97
+ return None
98
+ self._cursor -= 1
99
+ self._served = self._entries[self._cursor]
100
+ return self._served
101
+
102
+ def following(self, current: str):
103
+ """The next newer prompt, or the draft once past the newest.
104
+
105
+ None when no browse is in progress, which is what makes the key
106
+ inert on a box the user is typing into fresh: there is nothing
107
+ newer than what they are already looking at.
108
+ """
109
+ if not self._is_browsing(current):
110
+ return None
111
+ self._cursor += 1
112
+ if self._cursor < len(self._entries):
113
+ self._served = self._entries[self._cursor]
114
+ return self._served
115
+ draft = self._draft
116
+ self._forget_browse()
117
+ return draft
118
+
119
+ # -- internals ----------------------------------------------------------
120
+
121
+ def _is_browsing(self, current: str) -> bool:
122
+ """Whether `current` is still the string this last handed out."""
123
+ return self._cursor is not None and current == self._served
124
+
125
+ def _forget_browse(self) -> None:
126
+ self._cursor = None
127
+ self._draft = ""
128
+ self._served = None