@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
@@ -1,244 +1,319 @@
1
- """
2
- memories/tui_commands.py
3
-
4
- ROADMAP_v2 §21b (M15): `/memories` and `/forget`, registered into §16's
5
- slash registry. Mirrors skills/tui_commands.py and agents/tui_commands.py.
6
-
7
- WHY THESE SHIP NOW rather than as D26's fallback. §21 frames `/forget` as
8
- what to build *if* the approval prompt turns out to fire too often. But
9
- staleness is a different problem the gate never touches: "we use React 17"
10
- was true when it was approved and survives the upgrade regardless. Without
11
- removal, one memory that stops being true is permanent -- and listing is
12
- what makes removal usable at all, since the model never shows ids.
13
-
14
- Reading is deliberately not model-callable. A `forget` tool would let the
15
- model retire a memory it judged outdated, which is convenient and is also
16
- a deletion capability that would need its own gate: D26's argument for
17
- gating `remember` applies at least as strongly to silently removing
18
- something the user relies on.
19
- """
20
-
21
- from uuid import UUID
22
-
23
- from tui.commands import SlashCommand, registry as commands
24
- from memories.manager import manager
25
-
26
-
27
- def _cmd_memories(app, args: str) -> None:
28
- """List what this session can see, with ids for /forget."""
29
- rows = manager.visible()
30
- if not rows:
31
- where = manager.scope_path() or "no project resolved"
32
- app._transcript.write_system(
33
- f"No durable memories visible here ({where}).")
34
- return
35
- app._transcript.write_system(f"{len(rows)} durable memories:")
36
- for row in rows:
37
- marker = "global" if row["scope"] == "global" else "project"
38
- category = f" [{row['category']}]" if row.get("category") else ""
39
- app._transcript.write_system(
40
- f" {row['id']} ({marker}){category} {row['content']}")
41
-
42
-
43
- def _cmd_forget(app, args: str) -> None:
44
- """Delete one memory by id.
45
-
46
- By ID and not by substring. A substring match that hit two memories
47
- would have to pick one or refuse, and picking silently deletes
48
- something the user did not name -- which is the one outcome a removal
49
- command must never have.
50
- """
51
- from storage import forget_memory
52
-
53
- raw = args.strip()
54
- if not raw:
55
- app._transcript.write_error(
56
- "Usage: /forget <id>. Run /memories to see the ids.")
57
- return
58
- try:
59
- memory_id = UUID(raw)
60
- except ValueError:
61
- app._transcript.write_error(
62
- f"Not a memory id: {raw!r}. Run /memories to see the ids.")
63
- return
64
- if forget_memory(memory_id):
65
- app._transcript.write_system(f"Forgot {memory_id}.")
66
- else:
67
- app._transcript.write_error(f"No memory with id {memory_id}.")
68
-
69
-
70
- def _cmd_summary(app, args: str) -> None:
71
- """Distil this conversation and show the result (ROADMAP_v2 §21c).
72
-
73
- DESCRIBES, DOES NOT FOLD (M20). `/compact` shortens what the model sees
74
- next turn; this leaves the conversation exactly as it is and hands the
75
- user a summary. Two different requests that happen to share a summarizer.
76
-
77
- On a worker, because it is a model call, and announced before it starts:
78
- a call the user pays for is never silent, the same rule /compact follows.
79
- """
80
- if app._busy:
81
- app._transcript.write_error(
82
- "Still working — wait for this turn to finish.")
83
- return
84
- if app._memory is None:
85
- app._transcript.write_error(
86
- "Nothing to summarise — this thread is empty.")
87
- return
88
-
89
- memory = app.memory
90
- app._busy = True
91
- app._transcript.write_system("Summarising this conversation…")
92
-
93
- def _work() -> None:
94
- from core import compaction
95
- try:
96
- notice = compaction.summarize_thread(
97
- memory.thread_id, app.model, app.provider_name,
98
- # Batch 59. /summary runs the compactor with
99
- # nothing above it, so depth 0 -- it IS the stack.
100
- # getattr: these commands are driven against stub apps
101
- # in the suite (tests/test_thread_refs.py), and a
102
- # summary must not depend on a sidebar widget
103
- # existing. None is a fully supported sink.
104
- activity=getattr(app, "_activity", None), depth=0)
105
- except Exception as e: # noqa: BLE001 — same containment as /compact
106
- app.call_from_thread(
107
- app._transcript.write_error, f"Summary failed: {e}")
108
- return
109
- finally:
110
- app.call_from_thread(setattr, app, "_busy", False)
111
- if notice is None:
112
- app.call_from_thread(
113
- app._transcript.write_error,
114
- "Could not summarise this thread.")
115
- return
116
- app.call_from_thread(app._transcript.write_system, "Summary:")
117
- app.call_from_thread(app._transcript.write_answer, notice["text"])
118
-
119
- app.run_worker(_work, thread=True, exit_on_error=False,
120
- name="summary")
121
-
122
-
123
- def _cmd_ref(app, args: str) -> None:
124
- """Attach another conversation's summary to this one (§21c).
125
-
126
- USER-INITIATED BY CONSTRUCTION, which is §21's locked decision for this
127
- feature rather than an implementation detail: the user picks what crosses
128
- between threads, so nothing fetched or argued in one conversation can
129
- steer another without their say-so. A model-callable `search_threads`
130
- stays possible later, on this same retrieval and behind D26's gate.
131
- """
132
- from core.loop import clear_refs
133
- from tui.screens import ThreadPickerScreen
134
- import storage
135
-
136
- flag = args.strip().lower()
137
- if flag in ("--list", "list"):
138
- _write_ref_list(app)
139
- return
140
- if flag in ("--clear", "clear"):
141
- if app._memory is None:
142
- app._transcript.write_error("This thread references nothing.")
143
- return
144
- dropped = clear_refs(app.memory)
145
- app._transcript.write_system(
146
- f"Dropped {dropped} reference{'' if dropped == 1 else 's'}."
147
- if dropped else "This thread references nothing.")
148
- return
149
- if flag:
150
- app._transcript.write_error(
151
- f"Unknown option {args.strip()!r}. Usage: /ref [--list|--clear].")
152
- return
153
-
154
- if app._busy:
155
- app._transcript.write_error(
156
- "Still working — wait for this turn to finish.")
157
- return
158
-
159
- current = app._memory.thread_id if app._memory is not None else None
160
- # The CURRENT thread is excluded rather than merely discouraged:
161
- # referencing yourself spends a model call to inject what the model is
162
- # already reading.
163
- threads = [t for t in storage.list_threads() if t["id"] != current]
164
- if not threads:
165
- app._transcript.write_system(
166
- "No other conversations to reference yet.")
167
- return
168
-
169
- def chosen(thread_id) -> None:
170
- if thread_id is None:
171
- return
172
- _attach_in_worker(app, thread_id, threads)
173
-
174
- app.push_screen(ThreadPickerScreen(threads), chosen)
175
-
176
-
177
- def _write_ref_list(app) -> None:
178
- refs = (app._memory.extra.get("refs") or []) if app._memory else []
179
- if not refs:
180
- app._transcript.write_system("This thread references nothing.")
181
- return
182
- app._transcript.write_system(f"Referencing {len(refs)} conversation(s):")
183
- for ref in refs:
184
- label = ref.get("label") or "(no preview)"
185
- app._transcript.write_system(f" {ref['thread_id']} {label}")
186
-
187
-
188
- def _attach_in_worker(app, thread_id, threads) -> None:
189
- """Summarise the chosen thread and attach it. On a worker: summarising is
190
- a model call unless the stored summary is still current."""
191
- from core import compaction
192
- from core.loop import attach_ref
193
-
194
- memory = app.memory
195
- label = next((t.get("preview", "") for t in threads
196
- if t["id"] == thread_id), "")
197
- app._busy = True
198
- app._transcript.write_system(f"Summarising thread {thread_id}…")
199
-
200
- def _work() -> None:
201
- try:
202
- notice = compaction.summarize_thread(
203
- thread_id, app.model, app.provider_name,
204
- # getattr: these commands are driven against stub apps
205
- # in the suite (tests/test_thread_refs.py), and a
206
- # summary must not depend on a sidebar widget
207
- # existing. None is a fully supported sink.
208
- activity=getattr(app, "_activity", None), depth=0)
209
- except Exception as e: # noqa: BLE001
210
- app.call_from_thread(
211
- app._transcript.write_error, f"Reference failed: {e}")
212
- return
213
- finally:
214
- app.call_from_thread(setattr, app, "_busy", False)
215
- if notice is None:
216
- app.call_from_thread(
217
- app._transcript.write_error,
218
- f"Could not summarise thread {thread_id}.")
219
- return
220
- ok, message = attach_ref(memory, thread_id, notice["text"], label)
221
- write = (app._transcript.write_system if ok
222
- else app._transcript.write_error)
223
- app.call_from_thread(write, message)
224
-
225
- app.run_worker(_work, thread=True, exit_on_error=False, name="ref")
226
-
227
-
228
- def register_memory_commands() -> None:
229
- """Idempotent -- registering by name overwrites, matching §16's
230
- register_builtin_commands(), §18's and §19's.
231
-
232
- §21c's two live here with §21b's rather than in a module of their own:
233
- they are the same section's family, and `/ref` reads what `/summary`
234
- writes."""
235
- commands.register(SlashCommand(
236
- "memories", "list durable memories visible here", _cmd_memories))
237
- commands.register(SlashCommand(
238
- "forget", "delete one durable memory", _cmd_forget, "<id>"))
239
- commands.register(SlashCommand(
240
- "summary", "distil this conversation without folding it",
241
- _cmd_summary))
242
- commands.register(SlashCommand(
243
- "ref", "reference another conversation's summary", _cmd_ref,
244
- "[--list|--clear]"))
1
+ """
2
+ memories/tui_commands.py
3
+
4
+ ROADMAP_v2 §21b (M15): `/memories` and `/forget`, registered into §16's
5
+ slash registry. Mirrors skills/tui_commands.py and agents/tui_commands.py.
6
+
7
+ WHY THESE SHIP NOW rather than as D26's fallback. §21 frames `/forget` as
8
+ what to build *if* the approval prompt turns out to fire too often. But
9
+ staleness is a different problem the gate never touches: "we use React 17"
10
+ was true when it was approved and survives the upgrade regardless. Without
11
+ removal, one memory that stops being true is permanent -- and listing is
12
+ what makes removal usable at all, since the model never shows ids.
13
+
14
+ Reading is deliberately not model-callable. A `forget` tool would let the
15
+ model retire a memory it judged outdated, which is convenient and is also
16
+ a deletion capability that would need its own gate: D26's argument for
17
+ gating `remember` applies at least as strongly to silently removing
18
+ something the user relies on.
19
+ """
20
+
21
+ from uuid import UUID
22
+
23
+ from memories.manager import manager
24
+ from tui.commands import bind
25
+ from tui.commands import registry as commands
26
+
27
+ #: Longest memory text one picker row shows (ROADMAP_v3 §59). The confirm
28
+ #: that follows shows each ticked memory whole, so this cuts only the list.
29
+ PICKER_ROW_CHARS = 160
30
+
31
+
32
+ def _describe(row) -> str:
33
+ """`(project) [category] text`: what /memories prints after the id, and
34
+ what the picker and its confirm show. One function, so the three
35
+ surfaces name a memory the same way."""
36
+ marker = "global" if row["scope"] == "global" else "project"
37
+ category = f" [{row['category']}]" if row.get("category") else ""
38
+ return f"({marker}){category} {row['content']}"
39
+
40
+
41
+ def _picker_label(row) -> str:
42
+ """One line: whitespace collapsed, cut at PICKER_ROW_CHARS."""
43
+ text = " ".join(_describe(row).split())
44
+ if len(text) > PICKER_ROW_CHARS:
45
+ text = text[:PICKER_ROW_CHARS - 1].rstrip() + "…"
46
+ return text
47
+
48
+
49
+ def _cmd_memories(app, args: str) -> None:
50
+ """List what this session can see, with ids for /forget."""
51
+ rows = manager.visible()
52
+ if not rows:
53
+ app._transcript.write_system(_nothing_visible())
54
+ return
55
+ app._transcript.write_system(f"{len(rows)} durable memories:")
56
+ for row in rows:
57
+ app._transcript.write_system(f" {row['id']} {_describe(row)}")
58
+
59
+
60
+ def _nothing_visible() -> str:
61
+ where = manager.scope_path() or "no project resolved"
62
+ return f"No durable memories visible here ({where})."
63
+
64
+
65
+ def _cmd_forget(app, args: str) -> None:
66
+ """Delete memories: pick them with no id (§59), or name one by id.
67
+
68
+ By ID and not by substring. A substring match that hit two memories
69
+ would have to pick one or refuse, and picking silently deletes
70
+ something the user did not name -- which is the one outcome a removal
71
+ command must never have. The picker keeps that rule: a row IS an id.
72
+
73
+ The by-id form does not confirm, and §59 did not change it (UI4).
74
+ Copying a uuid back is the deliberation; ticking five rows is not.
75
+ """
76
+ raw = args.strip()
77
+ if not raw:
78
+ _pick_and_forget(app)
79
+ return
80
+ from storage import forget_memory
81
+
82
+ try:
83
+ memory_id = UUID(raw)
84
+ except ValueError:
85
+ app._transcript.write_error(
86
+ f"Not a memory id: {raw!r}. Run /memories to see the ids.")
87
+ return
88
+ if forget_memory(memory_id):
89
+ app._transcript.write_system(f"Forgot {memory_id}.")
90
+ else:
91
+ app._transcript.write_error(f"No memory with id {memory_id}.")
92
+
93
+
94
+ def _pick_and_forget(app) -> None:
95
+ """`/forget` alone: tick memories, confirm, then forget them
96
+ (ROADMAP_v3 §59, UI1 and UI4).
97
+
98
+ The confirm lists every ticked memory WHOLE, with its focus on No.
99
+ UI4: the picker takes away the friction a typed uuid was, so the
100
+ second look has to come from somewhere, and a list the user just
101
+ ticked is the cheapest place to give it.
102
+ """
103
+ from tui.screens import ConfirmScreen, MemoryPickerScreen
104
+
105
+ rows = manager.visible()
106
+ if not rows:
107
+ app._transcript.write_system(_nothing_visible())
108
+ return
109
+ by_id = {str(row["id"]): row for row in rows}
110
+
111
+ def picked(chosen) -> None:
112
+ if not chosen:
113
+ # None is Escape or Cancel; an empty set is Forget with nothing
114
+ # ticked. Both delete nothing, and both say so.
115
+ app._transcript.write_system("Nothing forgotten.")
116
+ return
117
+ # The picker's order, newest first, not the set's.
118
+ ids = [memory_id for memory_id in by_id if memory_id in chosen]
119
+ count = len(ids)
120
+ title = ("Forget this memory?" if count == 1
121
+ else f"Forget these {count} memories?")
122
+ body = "\n".join(f"- {_describe(by_id[memory_id])}"
123
+ for memory_id in ids)
124
+ app.push_screen(
125
+ ConfirmScreen(title, body, confirm_label="Forget"),
126
+ lambda confirmed: _forget_confirmed(app, ids, confirmed))
127
+
128
+ app.push_screen(
129
+ MemoryPickerScreen([(_picker_label(row), memory_id)
130
+ for memory_id, row in by_id.items()]),
131
+ picked)
132
+
133
+
134
+ def _forget_confirmed(app, ids: list, confirmed: bool) -> None:
135
+ from storage import forget_memory
136
+
137
+ if not confirmed:
138
+ app._transcript.write_system("Nothing forgotten.")
139
+ return
140
+ gone = [memory_id for memory_id in ids if forget_memory(UUID(memory_id))]
141
+ if gone:
142
+ app._transcript.write_system(
143
+ f"Forgot {len(gone)} memor{'y' if len(gone) == 1 else 'ies'}.")
144
+ # A row another session deleted while the picker was open. Named,
145
+ # because "Forgot 3" after ticking 4 would otherwise be a mystery.
146
+ for memory_id in ids:
147
+ if memory_id not in gone:
148
+ app._transcript.write_error(f"No memory with id {memory_id}.")
149
+
150
+
151
+ def _cmd_summary(app, args: str) -> None:
152
+ """Distil this conversation and show the result (ROADMAP_v2 §21c).
153
+
154
+ DESCRIBES, DOES NOT FOLD (M20). `/compact` shortens what the model sees
155
+ next turn; this leaves the conversation exactly as it is and hands the
156
+ user a summary. Two different requests that happen to share a summarizer.
157
+
158
+ On a worker, because it is a model call, and announced before it starts:
159
+ a call the user pays for is never silent, the same rule /compact follows.
160
+ """
161
+ if app._busy:
162
+ app._transcript.write_error(
163
+ "Still working — wait for this turn to finish.")
164
+ return
165
+ if app._memory is None:
166
+ app._transcript.write_error(
167
+ "Nothing to summarise — this thread is empty.")
168
+ return
169
+
170
+ memory = app.memory
171
+ app._busy = True
172
+ app._transcript.write_system("Summarising this conversation…")
173
+
174
+ def _work() -> None:
175
+ from core import compaction
176
+ try:
177
+ notice = compaction.summarize_thread(
178
+ memory.thread_id, app.model, app.provider_name,
179
+ # Batch 59. /summary runs the compactor with
180
+ # nothing above it, so depth 0 -- it IS the stack.
181
+ # getattr: these commands are driven against stub apps
182
+ # in the suite (tests/test_thread_refs.py), and a
183
+ # summary must not depend on a sidebar widget
184
+ # existing. None is a fully supported sink.
185
+ activity=getattr(app, "_activity", None), depth=0)
186
+ except Exception as e: # noqa: BLE001 — same containment as /compact
187
+ app.call_from_thread(
188
+ app._transcript.write_error, f"Summary failed: {e}")
189
+ return
190
+ finally:
191
+ app.call_from_thread(setattr, app, "_busy", False)
192
+ if notice is None:
193
+ app.call_from_thread(
194
+ app._transcript.write_error,
195
+ "Could not summarise this thread.")
196
+ return
197
+ app.call_from_thread(app._transcript.write_system, "Summary:")
198
+ app.call_from_thread(app._transcript.write_answer, notice["text"])
199
+
200
+ app.run_worker(_work, thread=True, exit_on_error=False,
201
+ name="summary")
202
+
203
+
204
+ def _cmd_ref(app, args: str) -> None:
205
+ """Attach another conversation's summary to this one (§21c).
206
+
207
+ USER-INITIATED BY CONSTRUCTION, which is §21's locked decision for this
208
+ feature rather than an implementation detail: the user picks what crosses
209
+ between threads, so nothing fetched or argued in one conversation can
210
+ steer another without their say-so. A model-callable `search_threads`
211
+ stays possible later, on this same retrieval and behind D26's gate.
212
+ """
213
+ import storage
214
+ from core.loop import clear_refs
215
+ from tui.screens import ThreadPickerScreen
216
+
217
+ flag = args.strip().lower()
218
+ if flag in ("--list", "list"):
219
+ _write_ref_list(app)
220
+ return
221
+ if flag in ("--clear", "clear"):
222
+ if app._memory is None:
223
+ app._transcript.write_error("This thread references nothing.")
224
+ return
225
+ dropped = clear_refs(app.memory)
226
+ app._transcript.write_system(
227
+ f"Dropped {dropped} reference{'' if dropped == 1 else 's'}."
228
+ if dropped else "This thread references nothing.")
229
+ return
230
+ if flag:
231
+ app._transcript.write_error(
232
+ f"Unknown option {args.strip()!r}. Usage: /ref [--list|--clear].")
233
+ return
234
+
235
+ if app._busy:
236
+ app._transcript.write_error(
237
+ "Still working — wait for this turn to finish.")
238
+ return
239
+
240
+ current = app._memory.thread_id if app._memory is not None else None
241
+ # The CURRENT thread is excluded rather than merely discouraged:
242
+ # referencing yourself spends a model call to inject what the model is
243
+ # already reading.
244
+ threads = [t for t in storage.list_threads() if t["id"] != current]
245
+ if not threads:
246
+ app._transcript.write_system(
247
+ "No other conversations to reference yet.")
248
+ return
249
+
250
+ def chosen(thread_id) -> None:
251
+ if thread_id is None:
252
+ return
253
+ _attach_in_worker(app, thread_id, threads)
254
+
255
+ app.push_screen(ThreadPickerScreen(threads), chosen)
256
+
257
+
258
+ def _write_ref_list(app) -> None:
259
+ refs = (app._memory.extra.get("refs") or []) if app._memory else []
260
+ if not refs:
261
+ app._transcript.write_system("This thread references nothing.")
262
+ return
263
+ app._transcript.write_system(f"Referencing {len(refs)} conversation(s):")
264
+ for ref in refs:
265
+ label = ref.get("label") or "(no preview)"
266
+ app._transcript.write_system(f" {ref['thread_id']} {label}")
267
+
268
+
269
+ def _attach_in_worker(app, thread_id, threads) -> None:
270
+ """Summarise the chosen thread and attach it. On a worker: summarising is
271
+ a model call unless the stored summary is still current."""
272
+ from core import compaction
273
+ from core.loop import attach_ref
274
+
275
+ memory = app.memory
276
+ label = next((t.get("preview", "") for t in threads
277
+ if t["id"] == thread_id), "")
278
+ app._busy = True
279
+ app._transcript.write_system(f"Summarising thread {thread_id}…")
280
+
281
+ def _work() -> None:
282
+ try:
283
+ notice = compaction.summarize_thread(
284
+ thread_id, app.model, app.provider_name,
285
+ # getattr: these commands are driven against stub apps
286
+ # in the suite (tests/test_thread_refs.py), and a
287
+ # summary must not depend on a sidebar widget
288
+ # existing. None is a fully supported sink.
289
+ activity=getattr(app, "_activity", None), depth=0)
290
+ except Exception as e: # noqa: BLE001
291
+ app.call_from_thread(
292
+ app._transcript.write_error, f"Reference failed: {e}")
293
+ return
294
+ finally:
295
+ app.call_from_thread(setattr, app, "_busy", False)
296
+ if notice is None:
297
+ app.call_from_thread(
298
+ app._transcript.write_error,
299
+ f"Could not summarise thread {thread_id}.")
300
+ return
301
+ ok, message = attach_ref(memory, thread_id, notice["text"], label)
302
+ write = (app._transcript.write_system if ok
303
+ else app._transcript.write_error)
304
+ app.call_from_thread(write, message)
305
+
306
+ app.run_worker(_work, thread=True, exit_on_error=False, name="ref")
307
+
308
+
309
+ def register_memory_commands() -> None:
310
+ """Idempotent -- registering by name overwrites, matching §16's
311
+ register_builtin_commands(), §18's and §19's.
312
+
313
+ §21c's two live here with §21b's rather than in a module of their own:
314
+ they are the same section's family, and `/ref` reads what `/summary`
315
+ writes."""
316
+ commands.register(bind("memories", _cmd_memories))
317
+ commands.register(bind("forget", _cmd_forget))
318
+ commands.register(bind("summary", _cmd_summary))
319
+ commands.register(bind("ref", _cmd_ref))