@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
@@ -1,239 +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 memories.manager import manager
24
- from tui.commands import bind
25
- from tui.commands import registry as commands
26
-
27
-
28
- def _cmd_memories(app, args: str) -> None:
29
- """List what this session can see, with ids for /forget."""
30
- rows = manager.visible()
31
- if not rows:
32
- where = manager.scope_path() or "no project resolved"
33
- app._transcript.write_system(
34
- f"No durable memories visible here ({where}).")
35
- return
36
- app._transcript.write_system(f"{len(rows)} durable memories:")
37
- for row in rows:
38
- marker = "global" if row["scope"] == "global" else "project"
39
- category = f" [{row['category']}]" if row.get("category") else ""
40
- app._transcript.write_system(
41
- f" {row['id']} ({marker}){category} {row['content']}")
42
-
43
-
44
- def _cmd_forget(app, args: str) -> None:
45
- """Delete one memory by id.
46
-
47
- By ID and not by substring. A substring match that hit two memories
48
- would have to pick one or refuse, and picking silently deletes
49
- something the user did not name -- which is the one outcome a removal
50
- command must never have.
51
- """
52
- from storage import forget_memory
53
-
54
- raw = args.strip()
55
- if not raw:
56
- app._transcript.write_error(
57
- "Usage: /forget <id>. Run /memories to see the ids.")
58
- return
59
- try:
60
- memory_id = UUID(raw)
61
- except ValueError:
62
- app._transcript.write_error(
63
- f"Not a memory id: {raw!r}. Run /memories to see the ids.")
64
- return
65
- if forget_memory(memory_id):
66
- app._transcript.write_system(f"Forgot {memory_id}.")
67
- else:
68
- app._transcript.write_error(f"No memory with id {memory_id}.")
69
-
70
-
71
- def _cmd_summary(app, args: str) -> None:
72
- """Distil this conversation and show the result (ROADMAP_v2 §21c).
73
-
74
- DESCRIBES, DOES NOT FOLD (M20). `/compact` shortens what the model sees
75
- next turn; this leaves the conversation exactly as it is and hands the
76
- user a summary. Two different requests that happen to share a summarizer.
77
-
78
- On a worker, because it is a model call, and announced before it starts:
79
- a call the user pays for is never silent, the same rule /compact follows.
80
- """
81
- if app._busy:
82
- app._transcript.write_error(
83
- "Still working — wait for this turn to finish.")
84
- return
85
- if app._memory is None:
86
- app._transcript.write_error(
87
- "Nothing to summarise — this thread is empty.")
88
- return
89
-
90
- memory = app.memory
91
- app._busy = True
92
- app._transcript.write_system("Summarising this conversation…")
93
-
94
- def _work() -> None:
95
- from core import compaction
96
- try:
97
- notice = compaction.summarize_thread(
98
- memory.thread_id, app.model, app.provider_name,
99
- # Batch 59. /summary runs the compactor with
100
- # nothing above it, so depth 0 -- it IS the stack.
101
- # getattr: these commands are driven against stub apps
102
- # in the suite (tests/test_thread_refs.py), and a
103
- # summary must not depend on a sidebar widget
104
- # existing. None is a fully supported sink.
105
- activity=getattr(app, "_activity", None), depth=0)
106
- except Exception as e: # noqa: BLE001 — same containment as /compact
107
- app.call_from_thread(
108
- app._transcript.write_error, f"Summary failed: {e}")
109
- return
110
- finally:
111
- app.call_from_thread(setattr, app, "_busy", False)
112
- if notice is None:
113
- app.call_from_thread(
114
- app._transcript.write_error,
115
- "Could not summarise this thread.")
116
- return
117
- app.call_from_thread(app._transcript.write_system, "Summary:")
118
- app.call_from_thread(app._transcript.write_answer, notice["text"])
119
-
120
- app.run_worker(_work, thread=True, exit_on_error=False,
121
- name="summary")
122
-
123
-
124
- def _cmd_ref(app, args: str) -> None:
125
- """Attach another conversation's summary to this one (§21c).
126
-
127
- USER-INITIATED BY CONSTRUCTION, which is §21's locked decision for this
128
- feature rather than an implementation detail: the user picks what crosses
129
- between threads, so nothing fetched or argued in one conversation can
130
- steer another without their say-so. A model-callable `search_threads`
131
- stays possible later, on this same retrieval and behind D26's gate.
132
- """
133
- import storage
134
- from core.loop import clear_refs
135
- from tui.screens import ThreadPickerScreen
136
-
137
- flag = args.strip().lower()
138
- if flag in ("--list", "list"):
139
- _write_ref_list(app)
140
- return
141
- if flag in ("--clear", "clear"):
142
- if app._memory is None:
143
- app._transcript.write_error("This thread references nothing.")
144
- return
145
- dropped = clear_refs(app.memory)
146
- app._transcript.write_system(
147
- f"Dropped {dropped} reference{'' if dropped == 1 else 's'}."
148
- if dropped else "This thread references nothing.")
149
- return
150
- if flag:
151
- app._transcript.write_error(
152
- f"Unknown option {args.strip()!r}. Usage: /ref [--list|--clear].")
153
- return
154
-
155
- if app._busy:
156
- app._transcript.write_error(
157
- "Still working — wait for this turn to finish.")
158
- return
159
-
160
- current = app._memory.thread_id if app._memory is not None else None
161
- # The CURRENT thread is excluded rather than merely discouraged:
162
- # referencing yourself spends a model call to inject what the model is
163
- # already reading.
164
- threads = [t for t in storage.list_threads() if t["id"] != current]
165
- if not threads:
166
- app._transcript.write_system(
167
- "No other conversations to reference yet.")
168
- return
169
-
170
- def chosen(thread_id) -> None:
171
- if thread_id is None:
172
- return
173
- _attach_in_worker(app, thread_id, threads)
174
-
175
- app.push_screen(ThreadPickerScreen(threads), chosen)
176
-
177
-
178
- def _write_ref_list(app) -> None:
179
- refs = (app._memory.extra.get("refs") or []) if app._memory else []
180
- if not refs:
181
- app._transcript.write_system("This thread references nothing.")
182
- return
183
- app._transcript.write_system(f"Referencing {len(refs)} conversation(s):")
184
- for ref in refs:
185
- label = ref.get("label") or "(no preview)"
186
- app._transcript.write_system(f" {ref['thread_id']} {label}")
187
-
188
-
189
- def _attach_in_worker(app, thread_id, threads) -> None:
190
- """Summarise the chosen thread and attach it. On a worker: summarising is
191
- a model call unless the stored summary is still current."""
192
- from core import compaction
193
- from core.loop import attach_ref
194
-
195
- memory = app.memory
196
- label = next((t.get("preview", "") for t in threads
197
- if t["id"] == thread_id), "")
198
- app._busy = True
199
- app._transcript.write_system(f"Summarising thread {thread_id}…")
200
-
201
- def _work() -> None:
202
- try:
203
- notice = compaction.summarize_thread(
204
- thread_id, app.model, app.provider_name,
205
- # getattr: these commands are driven against stub apps
206
- # in the suite (tests/test_thread_refs.py), and a
207
- # summary must not depend on a sidebar widget
208
- # existing. None is a fully supported sink.
209
- activity=getattr(app, "_activity", None), depth=0)
210
- except Exception as e: # noqa: BLE001
211
- app.call_from_thread(
212
- app._transcript.write_error, f"Reference failed: {e}")
213
- return
214
- finally:
215
- app.call_from_thread(setattr, app, "_busy", False)
216
- if notice is None:
217
- app.call_from_thread(
218
- app._transcript.write_error,
219
- f"Could not summarise thread {thread_id}.")
220
- return
221
- ok, message = attach_ref(memory, thread_id, notice["text"], label)
222
- write = (app._transcript.write_system if ok
223
- else app._transcript.write_error)
224
- app.call_from_thread(write, message)
225
-
226
- app.run_worker(_work, thread=True, exit_on_error=False, name="ref")
227
-
228
-
229
- def register_memory_commands() -> None:
230
- """Idempotent -- registering by name overwrites, matching §16's
231
- register_builtin_commands(), §18's and §19's.
232
-
233
- §21c's two live here with §21b's rather than in a module of their own:
234
- they are the same section's family, and `/ref` reads what `/summary`
235
- writes."""
236
- commands.register(bind("memories", _cmd_memories))
237
- commands.register(bind("forget", _cmd_forget))
238
- commands.register(bind("summary", _cmd_summary))
239
- commands.register(bind("ref", _cmd_ref))
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))