@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
@@ -15,7 +15,13 @@ from typing import Literal, Optional
15
15
  import sympy
16
16
  from pydantic import BaseModel, Field
17
17
 
18
- from tools.builtin._math_common import safe_parse, serialize, MathParseError
18
+ from tools.builtin._math_common import (
19
+ MathParseError,
20
+ _split_warnings,
21
+ parse_params,
22
+ safe_parse,
23
+ serialize,
24
+ )
19
25
 
20
26
  _OPERATIONS = Literal[
21
27
  "evaluate", "simplify", "expand", "factor",
@@ -32,7 +38,42 @@ class SymbolicMathParams(BaseModel):
32
38
  "'x**2 + 3*x - 4', 'sin(x)*cos(x)', or 'x**2 - 4 = 0' for solve."
33
39
  ),
34
40
  )
35
- variable: str = Field("x", description="The variable to solve for / differentiate / integrate / expand around")
41
+ variable: str = Field(
42
+ "x",
43
+ pattern=r"^[A-Za-z_][A-Za-z0-9_]*$",
44
+ description=(
45
+ "The ONE variable to solve for / differentiate / integrate / "
46
+ "expand around. A single name, not a list: for a system, put "
47
+ "the extra equations in `equations` and the solver takes its "
48
+ "symbols from the system itself."
49
+ ),
50
+ )
51
+ # `sympy.Symbol` accepts any string, so an unvalidated value
52
+ # became a symbol that CANNOT occur in the parsed expression, and every
53
+ # operation taking a variable then had a well-defined wrong answer:
54
+ # `solve('x**2 - 4 = 0', variable='x, y')` returned `[]` and
55
+ # `differentiate('x**3', variable='x, y')` returned `'0'`, neither
56
+ # distinguishable in the result from a correct empty solution set or a
57
+ # correct zero derivative. The schema is where its neighbours are
58
+ # already validated (`order` ge=1, `precision` le=50), and the trigger
59
+ # was the schema's own invitation: the sibling field `equations` IS a
60
+ # list, and the solve-a-system path ignores `variable` entirely -- so
61
+ # the one operation where a caller has a reason to name two variables
62
+ # is the one where this field is unused (batch 143).
63
+ #
64
+ # `pattern` is a field the pinned `google-genai` `types.Schema`
65
+ # carries, checked rather than assumed, so this does not widen the
66
+ # GOOGLE-branch problem that is still open.
67
+ symbols: Optional[list[str]] = Field(
68
+ None,
69
+ description=(
70
+ "Other multi-character symbol names in the expression, e.g. "
71
+ "['force', 'mass']. `variable` is always protected; any OTHER "
72
+ "multi-character name is read as a product of single letters "
73
+ "unless listed here ('mass' becomes a*m*s**2). Single letters "
74
+ "and names containing an underscore are safe without this."
75
+ ),
76
+ )
36
77
  equations: Optional[list[str]] = Field(
37
78
  None, description="For 'solve' with a system: additional equations alongside `expression`"
38
79
  )
@@ -59,11 +100,23 @@ TOOL_SCHEMA = {
59
100
 
60
101
 
61
102
  def run(params: dict) -> dict:
62
- parsed = SymbolicMathParams(**params)
103
+ try:
104
+ parsed = parse_params(SymbolicMathParams, params)
105
+ except MathParseError as e:
106
+ return {"error": str(e)}
107
+ # `variable` PLUS whatever the caller declared, on EVERY parsed field.
108
+ # Before batch 131 this tool passed `symbols=` on two of its six parses,
109
+ # the one name a caller could protect survived and any other name in the
110
+ # same expression was rewritten into a product of single letters --
111
+ # `integrate('force*distance', variable='distance')` answered about
112
+ # `c*e*f*o*r` without saying so.
113
+ rewritten: set = set()
114
+ syms = [parsed.variable] + [s for s in (parsed.symbols or [])
115
+ if s != parsed.variable]
63
116
 
64
117
  try:
65
118
  var = sympy.Symbol(parsed.variable)
66
- expr = safe_parse(parsed.expression, symbols=[parsed.variable])
119
+ expr = safe_parse(parsed.expression, symbols=syms, rewritten=rewritten)
67
120
  op = parsed.operation
68
121
 
69
122
  if op == "evaluate":
@@ -83,23 +136,28 @@ def run(params: dict) -> dict:
83
136
 
84
137
  elif op == "integrate":
85
138
  if parsed.lower_bound is not None and parsed.upper_bound is not None:
86
- lo = safe_parse(parsed.lower_bound)
87
- hi = safe_parse(parsed.upper_bound)
139
+ lo = safe_parse(parsed.lower_bound, symbols=syms,
140
+ rewritten=rewritten)
141
+ hi = safe_parse(parsed.upper_bound, symbols=syms,
142
+ rewritten=rewritten)
88
143
  result = sympy.integrate(expr, (var, lo, hi))
89
144
  else:
90
145
  result = sympy.integrate(expr, var)
91
146
 
92
147
  elif op == "limit":
93
- point = safe_parse(parsed.point) if parsed.point is not None else 0
148
+ point = (safe_parse(parsed.point, symbols=syms, rewritten=rewritten)
149
+ if parsed.point is not None else 0)
94
150
  result = sympy.limit(expr, var, point, dir=parsed.direction)
95
151
 
96
152
  elif op == "series":
97
- point = safe_parse(parsed.point) if parsed.point is not None else 0
153
+ point = (safe_parse(parsed.point, symbols=syms, rewritten=rewritten)
154
+ if parsed.point is not None else 0)
98
155
  result = expr.series(var, point, parsed.order).removeO()
99
156
 
100
157
  elif op == "solve":
101
158
  if parsed.equations:
102
- extra = [safe_parse(e, symbols=[parsed.variable]) for e in parsed.equations]
159
+ extra = [safe_parse(e, symbols=syms, rewritten=rewritten)
160
+ for e in parsed.equations]
103
161
  all_exprs = [expr] + extra
104
162
  symbols_found = sorted(
105
163
  set().union(*[e.free_symbols for e in all_exprs]), key=str
@@ -116,4 +174,16 @@ def run(params: dict) -> dict:
116
174
  except Exception as e:
117
175
  return {"error": f"Computation failed: {e}"}
118
176
 
119
- return {"result": serialize(result), "operation": op}
177
+ # H6, one batch late (batch 143). `serialize` is the SECOND place this function can fail
178
+ # and it used to sit outside every try, so a correct answer merely too
179
+ # large to print left `run()` as a bare ValueError and was reported as
180
+ # a harness bug with a traceback. A tail handler rather than one try
181
+ # round the whole body, which is the shape `discrete_math` -- the one
182
+ # tool H6 reached -- already uses.
183
+ try:
184
+ out: dict = {"result": serialize(result, what=op), "operation": op}
185
+ except MathParseError as e:
186
+ return {"error": str(e)}
187
+ if rewritten:
188
+ out["warnings"] = _split_warnings(rewritten)
189
+ return out
@@ -1,147 +1,149 @@
1
- """
2
- tools/builtin/todo.py
3
-
4
- ROADMAP_v2 §23 slice 2: the todo list. "A model-maintained checklist,
5
- persisted per thread."
6
-
7
- WHOLE-LIST WRITE, NOT GRANULAR OPERATIONS (J13). One call replaces the list,
8
- so it is always internally consistent, reordering is free, and no item is
9
- ever addressed by name or index. Granular add/complete/remove would each need
10
- a stable way to name one item -- which is the problem `clear_refs` refused to
11
- solve ("a per-reference removal needs a stable way for a person to name one")
12
- and the problem §21b's "removal is by id, never by substring" rule exists to
13
- prevent. A model naming the wrong id silently mutates the wrong entry; a model
14
- rewriting the list cannot.
15
-
16
- STORED IN extra_data (J14), under its own key beside §18's goal and §21c's
17
- refs. storage.py's `get_thread_extra` docstring has said "goal mode §18, todo
18
- list §23" since §18, and §27's column-versus-extra_data argument was about
19
- keeping `list_threads()` cheap -- a todo list is only ever read for the
20
- current thread, so queryability buys nothing.
21
-
22
- WORKS HEADLESS (J9). §23 AC2 says "both tools deny cleanly with no way to ask",
23
- but that was written before this tool's shape was settled: the deny rule
24
- exists because a blocking prompt nobody answers turns into a hang, and this
25
- tool never blocks and never asks anyone anything. A ten-pass research run
26
- keeping its own checklist is arguably where one helps most. It needs a
27
- conversation, not a person.
28
- """
29
-
30
- import config
31
-
32
-
33
- TOOL_SCHEMA = {
34
- "name": "todo_write",
35
- "description": (
36
- "Record or update your checklist for this conversation. Pass the "
37
- "WHOLE list every time -- it replaces what was there, so include "
38
- "the items that have not changed. Use it for multi-step work the "
39
- "user can then see the shape of: plan the steps up front, mark one "
40
- "in_progress while you do it, and mark it completed before starting "
41
- "the next. Do not use it for single-step requests, where the list "
42
- "is noise."
43
- ),
44
- "input_schema": {
45
- "type": "object",
46
- "properties": {
47
- "items": {
48
- "type": "array",
49
- "description": f"The complete list, in order, at most "
50
- f"{config.MAX_TODO_ITEMS} items. An empty "
51
- f"list clears it.",
52
- "items": {
53
- "type": "object",
54
- "properties": {
55
- "content": {
56
- "type": "string",
57
- "description": "What the step is, imperative and "
58
- "short.",
59
- },
60
- "status": {
61
- "type": "string",
62
- "enum": list(config.TODO_STATUSES),
63
- "description": "Defaults to pending.",
64
- },
65
- },
66
- "required": ["content"],
67
- },
68
- },
69
- },
70
- "required": ["items"],
71
- },
72
- }
73
-
74
-
75
- def _normalise(raw) -> tuple:
76
- """Validate one list. Returns (items, error) -- exactly one is truthy.
77
-
78
- Every failure is an error result the model can correct, never an
79
- exception: a bare KeyError or TypeError here escapes the loop's
80
- ToolCallDenied handler and takes down the whole turn. pin.py's rule.
81
- """
82
- if not isinstance(raw, (list, tuple)):
83
- return None, ("todo_write requires 'items' to be a list of "
84
- "{content, status} objects.")
85
- if len(raw) > config.MAX_TODO_ITEMS:
86
- # REFUSED, not truncated. A list silently cut would leave the model
87
- # believing it had recorded work it can no longer see.
88
- return None, (f"todo_write allows at most {config.MAX_TODO_ITEMS} "
89
- f"items; {len(raw)} were given. Keep the list to the "
90
- f"work actually in hand.")
91
-
92
- items = []
93
- for index, entry in enumerate(raw, start=1):
94
- if not isinstance(entry, dict):
95
- return None, (f"todo_write item {index} is not an object with a "
96
- f"'content' field.")
97
- content = entry.get("content")
98
- if not content or not isinstance(content, str):
99
- return None, (f"todo_write item {index} needs a non-empty "
100
- f"'content' string.")
101
- status = entry.get("status") or "pending"
102
- if status not in config.TODO_STATUSES:
103
- # Names the offender and the vocabulary. A silent coercion to
104
- # pending would report success while losing the state the model
105
- # meant to record.
106
- return None, (
107
- f"todo_write item {index} has status {status!r}; expected one "
108
- f"of {', '.join(config.TODO_STATUSES)}.")
109
- items.append({"content": content.strip(), "status": status})
110
- return items, None
111
-
112
-
113
- def _summary(items: list) -> str:
114
- """One line, for the transcript and for the CLI, which has no panel."""
115
- if not items:
116
- return "todo list cleared"
117
- done = sum(1 for i in items if i["status"] == "completed")
118
- active = next((i["content"] for i in items
119
- if i["status"] == "in_progress"), None)
120
- head = f"todo {done}/{len(items)}"
121
- return f"{head} — {active}" if active else head
122
-
123
-
124
- def run(params: dict, memory=None) -> dict:
125
- items, error = _normalise(params.get("items"))
126
- if error:
127
- return {"error": error}
128
- if memory is None:
129
- # Reachable only if dispatched outside a run. An explained error
130
- # rather than a silent no-op reported as success: the model would
131
- # otherwise believe a plan is recorded when nothing is, which is
132
- # worse than not having the tool. pin.py's reasoning.
133
- return {"error": "todo_write is only available inside a conversation."}
134
-
135
- # THE WHOLE LIST, through set_extra, which persists write-through. Not
136
- # `memory.extra[...] = ...`: `extra` is a COPY (core/memory.py), so
137
- # mutating it changes nothing and reports success.
138
- memory.set_extra("todos", items)
139
-
140
- return {
141
- "result": {"items": items},
142
- # §23 slice 2's event route (J10). The loop forwards any `notice` on
143
- # a tool result as a LoopEvent and strips it, so this reaches the TUI
144
- # panel without a tool name appearing in core/loop.py. The panel
145
- # re-reads the list from thread state -- this only says WHEN.
146
- "notice": {"kind": "todo_changed", "text": _summary(items)},
147
- }
1
+ """
2
+ tools/builtin/todo.py
3
+
4
+ ROADMAP_v2 §23 slice 2: the todo list. "A model-maintained checklist,
5
+ persisted per thread."
6
+
7
+ WHOLE-LIST WRITE, NOT GRANULAR OPERATIONS (J13). One call replaces the list,
8
+ so it is always internally consistent, reordering is free, and no item is
9
+ ever addressed by name or index. Granular add/complete/remove would each need
10
+ a stable way to name one item -- which is the problem `clear_refs` refused to
11
+ solve ("a per-reference removal needs a stable way for a person to name one")
12
+ and the problem §21b's "removal is by id, never by substring" rule exists to
13
+ prevent. A model naming the wrong id silently mutates the wrong entry; a model
14
+ rewriting the list cannot.
15
+
16
+ STORED IN extra_data (J14), under its own key beside §18's goal and §21c's
17
+ refs. storage.py's `get_thread_extra` docstring has said "goal mode §18, todo
18
+ list §23" since §18, and §27's column-versus-extra_data argument was about
19
+ keeping `list_threads()` cheap -- a todo list is only ever read for the
20
+ current thread, so queryability buys nothing.
21
+
22
+ WORKS HEADLESS (J9). §23 AC2 says "both tools deny cleanly with no way to ask",
23
+ but that was written before this tool's shape was settled: the deny rule
24
+ exists because a blocking prompt nobody answers turns into a hang, and this
25
+ tool never blocks and never asks anyone anything. A ten-pass research run
26
+ keeping its own checklist is arguably where one helps most. It needs a
27
+ conversation, not a person.
28
+ """
29
+
30
+ import config
31
+
32
+ TOOL_SCHEMA = {
33
+ "name": "todo_write",
34
+ "description": (
35
+ "Record or update your checklist for this conversation. Pass the "
36
+ "WHOLE list every time -- it replaces what was there, so include "
37
+ "the items that have not changed. Use it for multi-step work the "
38
+ "user can then see the shape of: plan the steps up front, mark one "
39
+ "in_progress while you do it, and mark it completed before starting "
40
+ "the next. Do not use it for single-step requests, where the list "
41
+ "is noise."
42
+ ),
43
+ "input_schema": {
44
+ "type": "object",
45
+ "properties": {
46
+ "items": {
47
+ "type": "array",
48
+ "description": f"The complete list, in order, at most "
49
+ f"{config.MAX_TODO_ITEMS} items. An empty "
50
+ f"list clears it.",
51
+ "items": {
52
+ "type": "object",
53
+ "properties": {
54
+ "content": {
55
+ "type": "string",
56
+ "description": "What the step is, imperative and "
57
+ "short.",
58
+ },
59
+ "status": {
60
+ "type": "string",
61
+ "enum": list(config.TODO_STATUSES),
62
+ "description": "Defaults to pending.",
63
+ },
64
+ },
65
+ "required": ["content"],
66
+ },
67
+ },
68
+ },
69
+ "required": ["items"],
70
+ },
71
+ }
72
+
73
+
74
+ def _normalise(raw) -> tuple:
75
+ """Validate one list. Returns (items, error) -- exactly one is truthy.
76
+
77
+ Every failure is an error result the model can correct, never an
78
+ exception -- tools/base.py carries the one copy of why, under "WHAT A
79
+ CALLABLE REGISTERED BELOW MAY RAISE". The short version is not the one
80
+ this used to give: a raise here is CONTAINED, and what an error result
81
+ buys is a message the model can act on instead of a generic wrapper
82
+ (batch 146).
83
+ """
84
+ if not isinstance(raw, (list, tuple)):
85
+ return None, ("todo_write requires 'items' to be a list of "
86
+ "{content, status} objects.")
87
+ if len(raw) > config.MAX_TODO_ITEMS:
88
+ # REFUSED, not truncated. A list silently cut would leave the model
89
+ # believing it had recorded work it can no longer see.
90
+ return None, (f"todo_write allows at most {config.MAX_TODO_ITEMS} "
91
+ f"items; {len(raw)} were given. Keep the list to the "
92
+ f"work actually in hand.")
93
+
94
+ items = []
95
+ for index, entry in enumerate(raw, start=1):
96
+ if not isinstance(entry, dict):
97
+ return None, (f"todo_write item {index} is not an object with a "
98
+ f"'content' field.")
99
+ content = entry.get("content")
100
+ if not content or not isinstance(content, str):
101
+ return None, (f"todo_write item {index} needs a non-empty "
102
+ f"'content' string.")
103
+ status = entry.get("status") or "pending"
104
+ if status not in config.TODO_STATUSES:
105
+ # Names the offender and the vocabulary. A silent coercion to
106
+ # pending would report success while losing the state the model
107
+ # meant to record.
108
+ return None, (
109
+ f"todo_write item {index} has status {status!r}; expected one "
110
+ f"of {', '.join(config.TODO_STATUSES)}.")
111
+ items.append({"content": content.strip(), "status": status})
112
+ return items, None
113
+
114
+
115
+ def _summary(items: list) -> str:
116
+ """One line, for the transcript and for the CLI, which has no panel."""
117
+ if not items:
118
+ return "todo list cleared"
119
+ done = sum(1 for i in items if i["status"] == "completed")
120
+ active = next((i["content"] for i in items
121
+ if i["status"] == "in_progress"), None)
122
+ head = f"todo {done}/{len(items)}"
123
+ return f"{head} — {active}" if active else head
124
+
125
+
126
+ def run(params: dict, memory=None) -> dict:
127
+ items, error = _normalise(params.get("items"))
128
+ if error:
129
+ return {"error": error}
130
+ if memory is None:
131
+ # Reachable only if dispatched outside a run. An explained error
132
+ # rather than a silent no-op reported as success: the model would
133
+ # otherwise believe a plan is recorded when nothing is, which is
134
+ # worse than not having the tool. pin.py's reasoning.
135
+ return {"error": "todo_write is only available inside a conversation."}
136
+
137
+ # THE WHOLE LIST, through set_extra, which persists write-through. Not
138
+ # `memory.extra[...] = ...`: `extra` is a COPY (core/memory.py), so
139
+ # mutating it changes nothing and reports success.
140
+ memory.set_extra("todos", items)
141
+
142
+ return {
143
+ "result": {"items": items},
144
+ # §23 slice 2's event route (J10). The loop forwards any `notice` on
145
+ # a tool result as a LoopEvent and strips it, so this reaches the TUI
146
+ # panel without a tool name appearing in core/loop.py. The panel
147
+ # re-reads the list from thread state -- this only says WHEN.
148
+ "notice": {"kind": "todo_changed", "text": _summary(items)},
149
+ }