lcode-cli 0.57.0__py3-none-any.whl → 0.59.0__py3-none-any.whl

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.
lcode/__init__.py CHANGED
@@ -3,7 +3,7 @@
3
3
  From a program: `from lcode import Session` (see lcode.api).
4
4
  """
5
5
 
6
- __version__ = "0.57.0"
6
+ __version__ = "0.59.0"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/bench.py CHANGED
@@ -39,6 +39,7 @@ from lcode.ollama import Ollama, OllamaError
39
39
  SCHEMA_VERSION = 1
40
40
  DEFAULT_CONTEXT = 32768 # the same everywhere, so results compare across machines
41
41
  DEFAULT_TIMEOUT = 300 # seconds per task
42
+ LONGER_TIMEOUT = 600 # for the longer tasks, which take a strong model up to five minutes
42
43
  DEFAULT_ATTEMPTS = 3 # each task's attempts: one run is within the noise between runs
43
44
  CHECK_TIMEOUT = 60
44
45
  PROBE_WORDS = 3000 # about 4,000 tokens
@@ -65,6 +66,7 @@ class Task:
65
66
  prompt: str
66
67
  files: dict[str, str]
67
68
  check: Callable[[Path, str], Check] # (task folder, the model's final answer) -> result
69
+ timeout: float = DEFAULT_TIMEOUT # seconds before it stops, unless --timeout says otherwise
68
70
 
69
71
 
70
72
  # ----------------------------------------------------------------------------- helpers for checks
@@ -747,32 +749,41 @@ TASKS = [
747
749
 
748
750
 
749
751
  def extra_tasks() -> list[Task]:
750
- """Tasks that only run when asked for with --tasks (they're slower, or test optional features)."""
751
- from lcode import bench_backend, bench_runtime
752
+ """Tasks that only run when asked for with --tasks (for optional features such as --code-search)."""
753
+ from lcode import bench_backend
754
+
755
+ return [Task("find-concept", "Find code by what it does (40 files)", *parts(bench_backend))]
756
+
757
+
758
+ def work_tasks() -> list[Task]:
759
+ """Tasks closer to real work, after the quick ones: longer, and where good models still slip."""
760
+ from lcode import bench_budgets, bench_dedupe, bench_flaky, bench_logsum, bench_quotes, bench_runtime
752
761
 
753
762
  return [
754
- Task(
755
- "find-concept",
756
- "Find code by what it does (40 files)",
757
- bench_backend.PROMPT,
758
- bench_backend.FILES,
759
- bench_backend.check,
760
- ),
761
- Task(
762
- "runtime-bug",
763
- "Fix a bug that shows only when it runs",
764
- bench_runtime.PROMPT,
765
- bench_runtime.FILES,
766
- bench_runtime.check,
767
- ),
763
+ Task("cli-tool", "Build a tool from a spec", *parts(bench_logsum), LONGER_TIMEOUT),
764
+ Task("flaky-test", "Find why a test is flaky", *parts(bench_flaky), LONGER_TIMEOUT),
765
+ Task("repo-bug", "Fix a bug in a 47-file repo", *parts(bench_quotes), LONGER_TIMEOUT),
766
+ Task("wide-feature", "Add a feature across modules", *parts(bench_budgets), LONGER_TIMEOUT),
767
+ Task("fast-dedupe", "Make a slow job fast, same output", *parts(bench_dedupe), LONGER_TIMEOUT),
768
+ Task("runtime-bug", "Fix a bug that shows only when it runs", *parts(bench_runtime), LONGER_TIMEOUT),
768
769
  ]
769
770
 
770
771
 
772
+ def parts(module) -> tuple:
773
+ """A task module's prompt, files and check."""
774
+ return module.PROMPT, module.FILES, module.check
775
+
776
+
777
+ def default_tasks() -> list[Task]:
778
+ """What `lcode bench` runs: the quick tasks, then the longer ones."""
779
+ return [*TASKS, *work_tasks()]
780
+
781
+
771
782
  def select_tasks(ids: str | None) -> list[Task]:
772
783
  if not ids:
773
- return list(TASKS)
784
+ return default_tasks()
774
785
  wanted = [i.strip() for i in ids.split(",") if i.strip()]
775
- known = {task.id: task for task in [*TASKS, *extra_tasks()]}
786
+ known = {task.id: task for task in [*default_tasks(), *extra_tasks()]}
776
787
  unknown = [i for i in wanted if i not in known]
777
788
  if unknown:
778
789
  raise ValueError(f"unknown task(s) {', '.join(unknown)}; choose from {', '.join(known)}")
@@ -1082,7 +1093,7 @@ def run_model(
1082
1093
  settings: Settings,
1083
1094
  tasks: list[Task],
1084
1095
  console: Console,
1085
- timeout: float = DEFAULT_TIMEOUT,
1096
+ timeout: float | None = None,
1086
1097
  keep: bool = False,
1087
1098
  verbose: bool = False,
1088
1099
  session: bool = False,
@@ -1133,6 +1144,7 @@ def run_model(
1133
1144
  pruned, compacted = pruned + shared.pruned, compacted + shared.compacted
1134
1145
  shared = None
1135
1146
  for task in tasks:
1147
+ limit = timeout or task.timeout # --timeout, or the task's own
1136
1148
  log = console if verbose else Console(file=io.StringIO(), width=120, force_terminal=False)
1137
1149
  if session and shared is None:
1138
1150
  shared = Agent(ollama, settings, Path(tempfile.gettempdir()), console=log)
@@ -1141,10 +1153,10 @@ def run_model(
1141
1153
  try:
1142
1154
  if verbose:
1143
1155
  console.rule(f"{task.id}: {task.title}")
1144
- result = run_task(ollama, settings, task, timeout, log, keep, run.usage, shared, retry)
1156
+ result = run_task(ollama, settings, task, limit, log, keep, run.usage, shared, retry)
1145
1157
  else:
1146
1158
  with console.status(Elapsed(f" {task.id:<13} {task.title}")):
1147
- result = run_task(ollama, settings, task, timeout, log, keep, run.usage, shared, retry)
1159
+ result = run_task(ollama, settings, task, limit, log, keep, run.usage, shared, retry)
1148
1160
  except KeyboardInterrupt:
1149
1161
  console.print(" [yellow]Stopped.[/]")
1150
1162
  run.interrupted = True
@@ -1250,7 +1262,7 @@ def report(runs: list[ModelRun], hardware: Hardware, ollama_version: str, server
1250
1262
  "server": server or f"Ollama {ollama_version}",
1251
1263
  "date": dt.datetime.now().astimezone().isoformat(timespec="seconds"),
1252
1264
  "hardware": {**asdict(hardware), "description": hardware.describe()},
1253
- "tasks": [{"id": t.id, "title": t.title} for t in TASKS],
1265
+ "tasks": [{"id": t.id, "title": t.title} for t in default_tasks()],
1254
1266
  "runs": [run.to_json() for run in runs],
1255
1267
  }
1256
1268
 
@@ -1280,7 +1292,11 @@ def print_tasks(console: Console) -> None:
1280
1292
  table = Table(title="lcode bench tasks", title_justify="left", header_style="bold")
1281
1293
  table.add_column("Task", style="cyan")
1282
1294
  table.add_column("What it tests")
1283
- for task in TASKS:
1284
- table.add_row(task.id, task.title)
1295
+ table.add_column("Runs", style="dim")
1296
+ for tasks, when in [(TASKS, "always"), (work_tasks(), "not with --quick"), (extra_tasks(), "only with --tasks")]:
1297
+ for task in tasks:
1298
+ table.add_row(task.id, task.title, when)
1285
1299
  console.print(table)
1286
- console.print("[dim]Run a subset with --tasks, e.g. lcode bench --tasks fix-bug,rename[/]")
1300
+ console.print(
1301
+ "[dim]--quick runs the quick ones once; --tasks picks some, e.g. lcode bench --tasks fix-bug,rename[/]"
1302
+ )
lcode/bench_budgets.py ADDED
@@ -0,0 +1,454 @@
1
+ """A feature across several modules, for `lcode bench --tasks feature-wide`.
2
+
3
+ An expense tracker gets monthly budgets: a new command with three subcommands, a change to the report in
4
+ text and JSON, budgets saved in the data file next to the expenses, with data files from before the change
5
+ still working. The check runs a scripted session from an old data file and compares every output; it also
6
+ adds an expense after setting budgets, which loses them if `add` saves only the expenses.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ from pathlib import Path
18
+
19
+ MODELS = '''\
20
+ """Expenses."""
21
+
22
+ from dataclasses import dataclass
23
+ from decimal import Decimal
24
+
25
+
26
+ @dataclass
27
+ class Expense:
28
+ date: str # YYYY-MM-DD
29
+ amount: Decimal
30
+ currency: str # EUR, USD, GBP or CHF
31
+ category: str
32
+ note: str = ""
33
+
34
+ def to_json(self) -> dict:
35
+ return {
36
+ "date": self.date,
37
+ "amount": str(self.amount),
38
+ "currency": self.currency,
39
+ "category": self.category,
40
+ "note": self.note,
41
+ }
42
+
43
+ @classmethod
44
+ def from_json(cls, data: dict) -> "Expense":
45
+ return cls(data["date"], Decimal(data["amount"]), data["currency"], data["category"], data.get("note", ""))
46
+ '''
47
+
48
+ STORAGE = '''\
49
+ """The data file: expenses.json in the current folder, or the file EXPENSES_FILE names."""
50
+
51
+ import json
52
+ import os
53
+ from pathlib import Path
54
+
55
+ from expenses.models import Expense
56
+
57
+ VERSION = 1
58
+
59
+
60
+ def data_path() -> Path:
61
+ return Path(os.environ.get("EXPENSES_FILE", "expenses.json"))
62
+
63
+
64
+ def load() -> list:
65
+ path = data_path()
66
+ if not path.exists():
67
+ return []
68
+ data = json.loads(path.read_text())
69
+ return [Expense.from_json(item) for item in data.get("expenses", [])]
70
+
71
+
72
+ def save(expenses: list) -> None:
73
+ data = {"version": VERSION, "expenses": [expense.to_json() for expense in expenses]}
74
+ data_path().write_text(json.dumps(data, indent=2) + "\\n")
75
+ '''
76
+
77
+ CURRENCY = '''\
78
+ """Currencies, converted to euros."""
79
+
80
+ from decimal import Decimal
81
+
82
+ RATES = {"EUR": Decimal("1"), "USD": Decimal("0.92"), "GBP": Decimal("1.17"), "CHF": Decimal("1.05")}
83
+
84
+
85
+ def to_eur(amount: Decimal, currency: str) -> Decimal:
86
+ """An amount in euros, to the cent."""
87
+ if currency not in RATES:
88
+ raise ValueError(f"unknown currency {currency}; use one of {', '.join(RATES)}")
89
+ return (amount * RATES[currency]).quantize(Decimal("0.01"))
90
+ '''
91
+
92
+ FORMATTING = '''\
93
+ """Money as text."""
94
+
95
+ from decimal import Decimal
96
+
97
+
98
+ def money(amount: Decimal) -> str:
99
+ """Like €1,234.50."""
100
+ return f"€{amount:,.2f}"
101
+ '''
102
+
103
+ REPORT = '''\
104
+ """Monthly reports."""
105
+
106
+ from decimal import Decimal
107
+
108
+ from expenses.currency import to_eur
109
+ from expenses.formatting import money
110
+
111
+
112
+ def monthly(expenses: list, month: str) -> dict:
113
+ """What was spent in each category in a month (YYYY-MM), in euros, by category name."""
114
+ totals = {}
115
+ for expense in expenses:
116
+ if expense.date.startswith(month + "-"):
117
+ totals[expense.category] = totals.get(expense.category, Decimal(0)) + to_eur(
118
+ expense.amount, expense.currency
119
+ )
120
+ return dict(sorted(totals.items()))
121
+
122
+
123
+ def report_lines(totals: dict) -> list:
124
+ lines = [f"{category}: {money(spent)}" for category, spent in totals.items()]
125
+ lines.append(f"total: {money(sum(totals.values(), Decimal(0)))}")
126
+ return lines
127
+
128
+
129
+ def report_json(totals: dict, month: str) -> dict:
130
+ return {
131
+ "month": month,
132
+ "categories": [{"category": category, "spent": float(spent)} for category, spent in totals.items()],
133
+ "total": float(sum(totals.values(), Decimal(0))),
134
+ }
135
+ '''
136
+
137
+ CLI = '''\
138
+ """The command line: python -m expenses add|list|report."""
139
+
140
+ import argparse
141
+ import datetime as dt
142
+ import json
143
+ import sys
144
+ from decimal import Decimal, InvalidOperation
145
+
146
+ from expenses import storage
147
+ from expenses.currency import RATES
148
+ from expenses.formatting import money
149
+ from expenses.models import Expense
150
+ from expenses.report import monthly, report_json, report_lines
151
+
152
+
153
+ def amount(text: str) -> Decimal:
154
+ try:
155
+ value = Decimal(text)
156
+ except InvalidOperation:
157
+ raise argparse.ArgumentTypeError(f"not an amount: {text}") from None
158
+ if value <= 0:
159
+ raise argparse.ArgumentTypeError("the amount must be more than 0")
160
+ return value
161
+
162
+
163
+ def main(argv=None) -> int:
164
+ parser = argparse.ArgumentParser(prog="expenses")
165
+ commands = parser.add_subparsers(dest="command", required=True)
166
+ add = commands.add_parser("add", help="record an expense")
167
+ add.add_argument("amount", type=amount)
168
+ add.add_argument("category")
169
+ add.add_argument("--currency", default="EUR", choices=sorted(RATES))
170
+ add.add_argument("--date", default=dt.date.today().isoformat())
171
+ add.add_argument("--note", default="")
172
+ listing = commands.add_parser("list", help="list expenses")
173
+ listing.add_argument("--month", help="YYYY-MM")
174
+ report = commands.add_parser("report", help="spending per category in a month")
175
+ report.add_argument("--month", required=True, help="YYYY-MM")
176
+ report.add_argument("--json", action="store_true")
177
+ args = parser.parse_args(argv)
178
+
179
+ expenses = storage.load()
180
+ if args.command == "add":
181
+ expenses.append(Expense(args.date, args.amount, args.currency, args.category.lower(), args.note))
182
+ storage.save(expenses)
183
+ print(f"Added {args.amount} {args.currency} for {args.category.lower()} on {args.date}")
184
+ elif args.command == "list":
185
+ for expense in expenses:
186
+ if args.month is None or expense.date.startswith(args.month + "-"):
187
+ note = f" ({expense.note})" if expense.note else ""
188
+ print(f"{expense.date} {expense.amount} {expense.currency} {expense.category}{note}")
189
+ elif args.command == "report":
190
+ totals = monthly(expenses, args.month)
191
+ if args.json:
192
+ print(json.dumps(report_json(totals, args.month)))
193
+ else:
194
+ print("\\n".join(report_lines(totals)))
195
+ return 0
196
+
197
+
198
+ if __name__ == "__main__":
199
+ sys.exit(main())
200
+ '''
201
+
202
+ README = """\
203
+ # expenses
204
+
205
+ Track what you spend, in any of four currencies, and see it per category each month.
206
+
207
+ python -m expenses add 12.50 food --note lunch
208
+ python -m expenses add 30 travel --currency USD --date 2026-10-02
209
+ python -m expenses list --month 2026-10
210
+ python -m expenses report --month 2026-10 [--json]
211
+
212
+ The data is kept in `expenses.json` in the current folder, or in the file `EXPENSES_FILE` names.
213
+ Amounts in other currencies count in euros at the rates in `expenses/currency.py`.
214
+ """
215
+
216
+ TEST_CLI = """\
217
+ import io
218
+ import json
219
+ import os
220
+ import tempfile
221
+ import unittest
222
+ from contextlib import redirect_stdout
223
+ from pathlib import Path
224
+
225
+ from expenses.cli import main
226
+
227
+
228
+ def run(*argv):
229
+ out = io.StringIO()
230
+ with redirect_stdout(out):
231
+ main(list(argv))
232
+ return out.getvalue()
233
+
234
+
235
+ class CliTest(unittest.TestCase):
236
+ def setUp(self):
237
+ self.folder = tempfile.TemporaryDirectory()
238
+ os.environ["EXPENSES_FILE"] = str(Path(self.folder.name) / "data.json")
239
+
240
+ def tearDown(self):
241
+ del os.environ["EXPENSES_FILE"]
242
+ self.folder.cleanup()
243
+
244
+ def test_add_and_report(self):
245
+ run("add", "12.50", "Food", "--date", "2026-10-01")
246
+ run("add", "10", "travel", "--currency", "USD", "--date", "2026-10-03")
247
+ run("add", "99", "food", "--date", "2026-11-01")
248
+ self.assertEqual(
249
+ run("report", "--month", "2026-10").splitlines(), ["food: €12.50", "travel: €9.20", "total: €21.70"]
250
+ )
251
+
252
+ def test_report_json(self):
253
+ run("add", "1000", "rent", "--date", "2026-10-01")
254
+ data = json.loads(run("report", "--month", "2026-10", "--json"))
255
+ self.assertEqual(data["categories"], [{"category": "rent", "spent": 1000.0}])
256
+ self.assertEqual(data["total"], 1000.0)
257
+
258
+ def test_list_a_month(self):
259
+ run("add", "5", "fun", "--date", "2026-09-30", "--note", "cards")
260
+ run("add", "7", "fun", "--date", "2026-10-01")
261
+ self.assertEqual(run("list", "--month", "2026-09"), "2026-09-30 5 EUR fun (cards)\\n")
262
+ """
263
+
264
+ TEST_STORAGE = """\
265
+ import os
266
+ import tempfile
267
+ import unittest
268
+ from decimal import Decimal
269
+ from pathlib import Path
270
+
271
+ from expenses import storage
272
+ from expenses.models import Expense
273
+
274
+
275
+ class StorageTest(unittest.TestCase):
276
+ def setUp(self):
277
+ self.folder = tempfile.TemporaryDirectory()
278
+ os.environ["EXPENSES_FILE"] = str(Path(self.folder.name) / "data.json")
279
+
280
+ def tearDown(self):
281
+ del os.environ["EXPENSES_FILE"]
282
+ self.folder.cleanup()
283
+
284
+ def test_nothing_saved_yet(self):
285
+ self.assertEqual(storage.load(), [])
286
+
287
+ def test_round_trip(self):
288
+ expense = Expense("2026-10-01", Decimal("12.50"), "GBP", "food", "lunch")
289
+ storage.save([expense])
290
+ self.assertEqual(storage.load(), [expense])
291
+ """
292
+
293
+ FILES = {
294
+ "README.md": README,
295
+ "expenses/__init__.py": '"""An expense tracker."""\n',
296
+ "expenses/__main__.py": "import sys\n\nfrom expenses.cli import main\n\nsys.exit(main())\n",
297
+ "expenses/cli.py": CLI,
298
+ "expenses/models.py": MODELS,
299
+ "expenses/storage.py": STORAGE,
300
+ "expenses/currency.py": CURRENCY,
301
+ "expenses/formatting.py": FORMATTING,
302
+ "expenses/report.py": REPORT,
303
+ "tests/__init__.py": "",
304
+ "tests/test_cli.py": TEST_CLI,
305
+ "tests/test_storage.py": TEST_STORAGE,
306
+ }
307
+
308
+ PROMPT = """\
309
+ Add monthly budgets per category to this expense tracker:
310
+ - `python -m expenses budget set CATEGORY AMOUNT` sets a category's monthly budget in euros, replacing \
311
+ any it had; `budget unset CATEGORY` removes it; `budget list` prints the budgets in alphabetical order, one \
312
+ per line, like `food: €300.00`.
313
+ - In `report --month YYYY-MM`, a category with a budget shows as `food: €320.50 of €300.00 (over by €20.50)`, \
314
+ or as `food: €120.00 of €300.00` when it isn't over. A category with a budget and nothing spent that month \
315
+ is shown too, as `€0.00 of €50.00`. Other categories and the total stay as they are.
316
+ - `report --json` gives each category `budget` (a number, or null without one) and `over` (how much over \
317
+ budget, 0 when it isn't), and includes the budgeted categories with nothing spent, with `spent` 0.
318
+ - Budgets are saved in the data file. Data files written before this change have no budgets and must keep \
319
+ working; files written after it have `"version": 2`.
320
+ Update the README and the tests, and run them."""
321
+
322
+ OLD_DATA = {
323
+ "version": 1,
324
+ "expenses": [
325
+ {"date": "2026-09-28", "amount": "80.00", "currency": "EUR", "category": "food", "note": "market"},
326
+ {"date": "2026-10-02", "amount": "120.00", "currency": "EUR", "category": "food", "note": "groceries"},
327
+ {"date": "2026-10-05", "amount": "45.00", "currency": "USD", "category": "travel", "note": "taxi"},
328
+ {"date": "2026-10-09", "amount": "100.00", "currency": "GBP", "category": "food", "note": "dinner"},
329
+ {"date": "2026-10-15", "amount": "15.99", "currency": "EUR", "category": "fun", "note": "cinema"},
330
+ {"date": "2026-10-21", "amount": "19.90", "currency": "CHF", "category": "food", "note": "chocolate"},
331
+ {"date": "2026-11-01", "amount": "9.00", "currency": "EUR", "category": "food", "note": "bakery"},
332
+ ],
333
+ }
334
+
335
+ # The session the check runs, from OLD_DATA: (what it checks, arguments, the expected output or None for any).
336
+ OCTOBER = [
337
+ "books: €0.00 of €40.00",
338
+ "food: €257.90 of €250.00 (over by €7.90)",
339
+ "fun: €15.99",
340
+ "travel: €41.40 of €50.50",
341
+ "total: €315.29",
342
+ ]
343
+ NO_BUDGETS: list[str] = [] # `budget list` without budgets: no budget lines, whatever else it says ("No budgets set.")
344
+ SESSION = [
345
+ (
346
+ "an old data file still reports",
347
+ ["report", "--month", "2026-10"],
348
+ ["food: €257.90", "fun: €15.99", "travel: €41.40", "total: €315.29"],
349
+ ),
350
+ ("no budgets yet", ["budget", "list"], NO_BUDGETS),
351
+ ("budget set", ["budget", "set", "food", "300"], None),
352
+ ("budget set", ["budget", "set", "travel", "50.5"], None),
353
+ ("budget set replaces", ["budget", "set", "food", "250"], None),
354
+ ("budget set", ["budget", "set", "books", "40"], None),
355
+ ("budget list", ["budget", "list"], ["books: €40.00", "food: €250.00", "travel: €50.50"]),
356
+ ("the report with budgets", ["report", "--month", "2026-10"], OCTOBER),
357
+ ("adding an expense keeps the budgets", ["add", "12.50", "food", "--date", "2026-10-20"], None),
358
+ (
359
+ "the report after adding",
360
+ ["report", "--month", "2026-10"],
361
+ [*OCTOBER[:1], "food: €270.40 of €250.00 (over by €20.40)", *OCTOBER[2:4], "total: €327.79"],
362
+ ),
363
+ ("budget unset", ["budget", "unset", "travel"], None),
364
+ ("budget list after unset", ["budget", "list"], ["books: €40.00", "food: €250.00"]),
365
+ (
366
+ "a month without spending",
367
+ ["report", "--month", "2026-12"],
368
+ ["books: €0.00 of €40.00", "food: €0.00 of €250.00", "total: €0.00"],
369
+ ),
370
+ ]
371
+ JSON_REPORT = { # report --month 2026-10 --json at the end: category -> (spent, budget, over)
372
+ "books": (0, 40, 0),
373
+ "food": (270.40, 250, 20.40),
374
+ "fun": (15.99, None, 0),
375
+ "travel": (41.40, None, 0),
376
+ }
377
+
378
+
379
+ def run(folder: Path, data: Path, argv: list[str]) -> subprocess.CompletedProcess:
380
+ env = {**os.environ, "EXPENSES_FILE": str(data), "PYTHONDONTWRITEBYTECODE": "1"}
381
+ env.pop("PYTHONPATH", None)
382
+ return subprocess.run(
383
+ [sys.executable, "-m", "expenses", *argv],
384
+ cwd=folder,
385
+ env=env,
386
+ capture_output=True,
387
+ text=True,
388
+ stdin=subprocess.DEVNULL,
389
+ timeout=30,
390
+ )
391
+
392
+
393
+ def lines(text: str) -> list[str]:
394
+ return [line.rstrip() for line in text.strip().splitlines()]
395
+
396
+
397
+ def same(got: list[str], want: list[str], argv: list[str]) -> bool:
398
+ """Whether a command printed what it should. The task fixes the order of `budget list` (alphabetical), not of
399
+ the report's categories, so those may come in any order before the total."""
400
+ if want is NO_BUDGETS:
401
+ return not any(re.match(r"\S+: €", line) for line in got)
402
+ if argv[0] == "report":
403
+ return bool(got) and got[-1] == want[-1] and sorted(got[:-1]) == sorted(want[:-1])
404
+ return got == want
405
+
406
+
407
+ def json_problem(text: str) -> str | None:
408
+ try:
409
+ categories = {c["category"]: c for c in json.loads(text)["categories"]}
410
+ except (ValueError, KeyError, TypeError):
411
+ return "report --json isn't the report with a list of categories"
412
+ for name, (spent, budget, over) in JSON_REPORT.items():
413
+ got = categories.get(name)
414
+ if got is None:
415
+ return f"report --json leaves out {name}"
416
+ want = {"spent": spent, "budget": budget, "over": over}
417
+ for key, value in want.items():
418
+ have = got.get(key, "missing")
419
+ if value is None:
420
+ if have is not None:
421
+ return f"report --json: {name}'s {key} is {have!r}, not null"
422
+ elif not isinstance(have, (int, float)) or isinstance(have, bool) or abs(have - value) > 0.001:
423
+ return f"report --json: {name}'s {key} is {have!r}, not {value}"
424
+ return None
425
+
426
+
427
+ def check(folder: Path, answer: str):
428
+ from lcode.bench import Check, last_line, run_python
429
+
430
+ if not (folder / "expenses" / "cli.py").is_file():
431
+ return Check(False, "expenses/cli.py is missing")
432
+ r = run_python(folder, "-m", "unittest", "-q")
433
+ if r.returncode != 0:
434
+ return Check(False, f"its tests fail: {last_line(r.stderr) or last_line(r.stdout)}")
435
+ with tempfile.TemporaryDirectory(prefix="lcode-bench-budgets-") as tmp:
436
+ data = Path(tmp) / "old.json"
437
+ data.write_text(json.dumps(OLD_DATA, indent=2))
438
+ for what, argv, want in SESSION:
439
+ r = run(folder, data, argv)
440
+ if r.returncode != 0:
441
+ return Check(False, f"{what}: `{' '.join(argv)}` failed: {last_line(r.stderr)}")
442
+ if want is not None and not same(lines(r.stdout), want, argv):
443
+ got = " / ".join(lines(r.stdout)) or "nothing"
444
+ return Check(False, f"{what}: `{' '.join(argv)}` printed {got[:150]}")
445
+ r = run(folder, data, ["report", "--month", "2026-10", "--json"])
446
+ problem = json_problem(r.stdout) if r.returncode == 0 else f"report --json failed: {last_line(r.stderr)}"
447
+ if problem:
448
+ return Check(False, problem)
449
+ saved = json.loads(data.read_text())
450
+ if saved.get("version") != 2:
451
+ return Check(False, f'the data file has "version": {saved.get("version")!r}, not 2')
452
+ if len(saved.get("expenses", [])) != len(OLD_DATA["expenses"]) + 1:
453
+ return Check(False, "the data file lost expenses")
454
+ return Check(True, "budgets work in the report, in JSON and with old data, and its tests pass")