lcode-cli 0.57.0__py3-none-any.whl → 0.58.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.58.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,442 @@
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 subprocess
14
+ import sys
15
+ import tempfile
16
+ from pathlib import Path
17
+
18
+ MODELS = '''\
19
+ """Expenses."""
20
+
21
+ from dataclasses import dataclass
22
+ from decimal import Decimal
23
+
24
+
25
+ @dataclass
26
+ class Expense:
27
+ date: str # YYYY-MM-DD
28
+ amount: Decimal
29
+ currency: str # EUR, USD, GBP or CHF
30
+ category: str
31
+ note: str = ""
32
+
33
+ def to_json(self) -> dict:
34
+ return {
35
+ "date": self.date,
36
+ "amount": str(self.amount),
37
+ "currency": self.currency,
38
+ "category": self.category,
39
+ "note": self.note,
40
+ }
41
+
42
+ @classmethod
43
+ def from_json(cls, data: dict) -> "Expense":
44
+ return cls(data["date"], Decimal(data["amount"]), data["currency"], data["category"], data.get("note", ""))
45
+ '''
46
+
47
+ STORAGE = '''\
48
+ """The data file: expenses.json in the current folder, or the file EXPENSES_FILE names."""
49
+
50
+ import json
51
+ import os
52
+ from pathlib import Path
53
+
54
+ from expenses.models import Expense
55
+
56
+ VERSION = 1
57
+
58
+
59
+ def data_path() -> Path:
60
+ return Path(os.environ.get("EXPENSES_FILE", "expenses.json"))
61
+
62
+
63
+ def load() -> list:
64
+ path = data_path()
65
+ if not path.exists():
66
+ return []
67
+ data = json.loads(path.read_text())
68
+ return [Expense.from_json(item) for item in data.get("expenses", [])]
69
+
70
+
71
+ def save(expenses: list) -> None:
72
+ data = {"version": VERSION, "expenses": [expense.to_json() for expense in expenses]}
73
+ data_path().write_text(json.dumps(data, indent=2) + "\\n")
74
+ '''
75
+
76
+ CURRENCY = '''\
77
+ """Currencies, converted to euros."""
78
+
79
+ from decimal import Decimal
80
+
81
+ RATES = {"EUR": Decimal("1"), "USD": Decimal("0.92"), "GBP": Decimal("1.17"), "CHF": Decimal("1.05")}
82
+
83
+
84
+ def to_eur(amount: Decimal, currency: str) -> Decimal:
85
+ """An amount in euros, to the cent."""
86
+ if currency not in RATES:
87
+ raise ValueError(f"unknown currency {currency}; use one of {', '.join(RATES)}")
88
+ return (amount * RATES[currency]).quantize(Decimal("0.01"))
89
+ '''
90
+
91
+ FORMATTING = '''\
92
+ """Money as text."""
93
+
94
+ from decimal import Decimal
95
+
96
+
97
+ def money(amount: Decimal) -> str:
98
+ """Like €1,234.50."""
99
+ return f"€{amount:,.2f}"
100
+ '''
101
+
102
+ REPORT = '''\
103
+ """Monthly reports."""
104
+
105
+ from decimal import Decimal
106
+
107
+ from expenses.currency import to_eur
108
+ from expenses.formatting import money
109
+
110
+
111
+ def monthly(expenses: list, month: str) -> dict:
112
+ """What was spent in each category in a month (YYYY-MM), in euros, by category name."""
113
+ totals = {}
114
+ for expense in expenses:
115
+ if expense.date.startswith(month + "-"):
116
+ totals[expense.category] = totals.get(expense.category, Decimal(0)) + to_eur(
117
+ expense.amount, expense.currency
118
+ )
119
+ return dict(sorted(totals.items()))
120
+
121
+
122
+ def report_lines(totals: dict) -> list:
123
+ lines = [f"{category}: {money(spent)}" for category, spent in totals.items()]
124
+ lines.append(f"total: {money(sum(totals.values(), Decimal(0)))}")
125
+ return lines
126
+
127
+
128
+ def report_json(totals: dict, month: str) -> dict:
129
+ return {
130
+ "month": month,
131
+ "categories": [{"category": category, "spent": float(spent)} for category, spent in totals.items()],
132
+ "total": float(sum(totals.values(), Decimal(0))),
133
+ }
134
+ '''
135
+
136
+ CLI = '''\
137
+ """The command line: python -m expenses add|list|report."""
138
+
139
+ import argparse
140
+ import datetime as dt
141
+ import json
142
+ import sys
143
+ from decimal import Decimal, InvalidOperation
144
+
145
+ from expenses import storage
146
+ from expenses.currency import RATES
147
+ from expenses.formatting import money
148
+ from expenses.models import Expense
149
+ from expenses.report import monthly, report_json, report_lines
150
+
151
+
152
+ def amount(text: str) -> Decimal:
153
+ try:
154
+ value = Decimal(text)
155
+ except InvalidOperation:
156
+ raise argparse.ArgumentTypeError(f"not an amount: {text}") from None
157
+ if value <= 0:
158
+ raise argparse.ArgumentTypeError("the amount must be more than 0")
159
+ return value
160
+
161
+
162
+ def main(argv=None) -> int:
163
+ parser = argparse.ArgumentParser(prog="expenses")
164
+ commands = parser.add_subparsers(dest="command", required=True)
165
+ add = commands.add_parser("add", help="record an expense")
166
+ add.add_argument("amount", type=amount)
167
+ add.add_argument("category")
168
+ add.add_argument("--currency", default="EUR", choices=sorted(RATES))
169
+ add.add_argument("--date", default=dt.date.today().isoformat())
170
+ add.add_argument("--note", default="")
171
+ listing = commands.add_parser("list", help="list expenses")
172
+ listing.add_argument("--month", help="YYYY-MM")
173
+ report = commands.add_parser("report", help="spending per category in a month")
174
+ report.add_argument("--month", required=True, help="YYYY-MM")
175
+ report.add_argument("--json", action="store_true")
176
+ args = parser.parse_args(argv)
177
+
178
+ expenses = storage.load()
179
+ if args.command == "add":
180
+ expenses.append(Expense(args.date, args.amount, args.currency, args.category.lower(), args.note))
181
+ storage.save(expenses)
182
+ print(f"Added {args.amount} {args.currency} for {args.category.lower()} on {args.date}")
183
+ elif args.command == "list":
184
+ for expense in expenses:
185
+ if args.month is None or expense.date.startswith(args.month + "-"):
186
+ note = f" ({expense.note})" if expense.note else ""
187
+ print(f"{expense.date} {expense.amount} {expense.currency} {expense.category}{note}")
188
+ elif args.command == "report":
189
+ totals = monthly(expenses, args.month)
190
+ if args.json:
191
+ print(json.dumps(report_json(totals, args.month)))
192
+ else:
193
+ print("\\n".join(report_lines(totals)))
194
+ return 0
195
+
196
+
197
+ if __name__ == "__main__":
198
+ sys.exit(main())
199
+ '''
200
+
201
+ README = """\
202
+ # expenses
203
+
204
+ Track what you spend, in any of four currencies, and see it per category each month.
205
+
206
+ python -m expenses add 12.50 food --note lunch
207
+ python -m expenses add 30 travel --currency USD --date 2026-10-02
208
+ python -m expenses list --month 2026-10
209
+ python -m expenses report --month 2026-10 [--json]
210
+
211
+ The data is kept in `expenses.json` in the current folder, or in the file `EXPENSES_FILE` names.
212
+ Amounts in other currencies count in euros at the rates in `expenses/currency.py`.
213
+ """
214
+
215
+ TEST_CLI = """\
216
+ import io
217
+ import json
218
+ import os
219
+ import tempfile
220
+ import unittest
221
+ from contextlib import redirect_stdout
222
+ from pathlib import Path
223
+
224
+ from expenses.cli import main
225
+
226
+
227
+ def run(*argv):
228
+ out = io.StringIO()
229
+ with redirect_stdout(out):
230
+ main(list(argv))
231
+ return out.getvalue()
232
+
233
+
234
+ class CliTest(unittest.TestCase):
235
+ def setUp(self):
236
+ self.folder = tempfile.TemporaryDirectory()
237
+ os.environ["EXPENSES_FILE"] = str(Path(self.folder.name) / "data.json")
238
+
239
+ def tearDown(self):
240
+ del os.environ["EXPENSES_FILE"]
241
+ self.folder.cleanup()
242
+
243
+ def test_add_and_report(self):
244
+ run("add", "12.50", "Food", "--date", "2026-10-01")
245
+ run("add", "10", "travel", "--currency", "USD", "--date", "2026-10-03")
246
+ run("add", "99", "food", "--date", "2026-11-01")
247
+ self.assertEqual(
248
+ run("report", "--month", "2026-10").splitlines(), ["food: €12.50", "travel: €9.20", "total: €21.70"]
249
+ )
250
+
251
+ def test_report_json(self):
252
+ run("add", "1000", "rent", "--date", "2026-10-01")
253
+ data = json.loads(run("report", "--month", "2026-10", "--json"))
254
+ self.assertEqual(data["categories"], [{"category": "rent", "spent": 1000.0}])
255
+ self.assertEqual(data["total"], 1000.0)
256
+
257
+ def test_list_a_month(self):
258
+ run("add", "5", "fun", "--date", "2026-09-30", "--note", "cards")
259
+ run("add", "7", "fun", "--date", "2026-10-01")
260
+ self.assertEqual(run("list", "--month", "2026-09"), "2026-09-30 5 EUR fun (cards)\\n")
261
+ """
262
+
263
+ TEST_STORAGE = """\
264
+ import os
265
+ import tempfile
266
+ import unittest
267
+ from decimal import Decimal
268
+ from pathlib import Path
269
+
270
+ from expenses import storage
271
+ from expenses.models import Expense
272
+
273
+
274
+ class StorageTest(unittest.TestCase):
275
+ def setUp(self):
276
+ self.folder = tempfile.TemporaryDirectory()
277
+ os.environ["EXPENSES_FILE"] = str(Path(self.folder.name) / "data.json")
278
+
279
+ def tearDown(self):
280
+ del os.environ["EXPENSES_FILE"]
281
+ self.folder.cleanup()
282
+
283
+ def test_nothing_saved_yet(self):
284
+ self.assertEqual(storage.load(), [])
285
+
286
+ def test_round_trip(self):
287
+ expense = Expense("2026-10-01", Decimal("12.50"), "GBP", "food", "lunch")
288
+ storage.save([expense])
289
+ self.assertEqual(storage.load(), [expense])
290
+ """
291
+
292
+ FILES = {
293
+ "README.md": README,
294
+ "expenses/__init__.py": '"""An expense tracker."""\n',
295
+ "expenses/__main__.py": "import sys\n\nfrom expenses.cli import main\n\nsys.exit(main())\n",
296
+ "expenses/cli.py": CLI,
297
+ "expenses/models.py": MODELS,
298
+ "expenses/storage.py": STORAGE,
299
+ "expenses/currency.py": CURRENCY,
300
+ "expenses/formatting.py": FORMATTING,
301
+ "expenses/report.py": REPORT,
302
+ "tests/__init__.py": "",
303
+ "tests/test_cli.py": TEST_CLI,
304
+ "tests/test_storage.py": TEST_STORAGE,
305
+ }
306
+
307
+ PROMPT = """\
308
+ Add monthly budgets per category to this expense tracker:
309
+ - `python -m expenses budget set CATEGORY AMOUNT` sets a category's monthly budget in euros, replacing \
310
+ any it had; `budget unset CATEGORY` removes it; `budget list` prints the budgets in alphabetical order, one \
311
+ per line, like `food: €300.00`.
312
+ - In `report --month YYYY-MM`, a category with a budget shows as `food: €320.50 of €300.00 (over by €20.50)`, \
313
+ or as `food: €120.00 of €300.00` when it isn't over. A category with a budget and nothing spent that month \
314
+ is shown too, as `€0.00 of €50.00`. Other categories and the total stay as they are.
315
+ - `report --json` gives each category `budget` (a number, or null without one) and `over` (how much over \
316
+ budget, 0 when it isn't), and includes the budgeted categories with nothing spent, with `spent` 0.
317
+ - Budgets are saved in the data file. Data files written before this change have no budgets and must keep \
318
+ working; files written after it have `"version": 2`.
319
+ Update the README and the tests, and run them."""
320
+
321
+ OLD_DATA = {
322
+ "version": 1,
323
+ "expenses": [
324
+ {"date": "2026-09-28", "amount": "80.00", "currency": "EUR", "category": "food", "note": "market"},
325
+ {"date": "2026-10-02", "amount": "120.00", "currency": "EUR", "category": "food", "note": "groceries"},
326
+ {"date": "2026-10-05", "amount": "45.00", "currency": "USD", "category": "travel", "note": "taxi"},
327
+ {"date": "2026-10-09", "amount": "100.00", "currency": "GBP", "category": "food", "note": "dinner"},
328
+ {"date": "2026-10-15", "amount": "15.99", "currency": "EUR", "category": "fun", "note": "cinema"},
329
+ {"date": "2026-10-21", "amount": "19.90", "currency": "CHF", "category": "food", "note": "chocolate"},
330
+ {"date": "2026-11-01", "amount": "9.00", "currency": "EUR", "category": "food", "note": "bakery"},
331
+ ],
332
+ }
333
+
334
+ # The session the check runs, from OLD_DATA: (what it checks, arguments, the expected output or None for any).
335
+ OCTOBER = [
336
+ "books: €0.00 of €40.00",
337
+ "food: €257.90 of €250.00 (over by €7.90)",
338
+ "fun: €15.99",
339
+ "travel: €41.40 of €50.50",
340
+ "total: €315.29",
341
+ ]
342
+ SESSION = [
343
+ (
344
+ "an old data file still reports",
345
+ ["report", "--month", "2026-10"],
346
+ ["food: €257.90", "fun: €15.99", "travel: €41.40", "total: €315.29"],
347
+ ),
348
+ ("no budgets yet", ["budget", "list"], []),
349
+ ("budget set", ["budget", "set", "food", "300"], None),
350
+ ("budget set", ["budget", "set", "travel", "50.5"], None),
351
+ ("budget set replaces", ["budget", "set", "food", "250"], None),
352
+ ("budget set", ["budget", "set", "books", "40"], None),
353
+ ("budget list", ["budget", "list"], ["books: €40.00", "food: €250.00", "travel: €50.50"]),
354
+ ("the report with budgets", ["report", "--month", "2026-10"], OCTOBER),
355
+ ("adding an expense keeps the budgets", ["add", "12.50", "food", "--date", "2026-10-20"], None),
356
+ (
357
+ "the report after adding",
358
+ ["report", "--month", "2026-10"],
359
+ [*OCTOBER[:1], "food: €270.40 of €250.00 (over by €20.40)", *OCTOBER[2:4], "total: €327.79"],
360
+ ),
361
+ ("budget unset", ["budget", "unset", "travel"], None),
362
+ ("budget list after unset", ["budget", "list"], ["books: €40.00", "food: €250.00"]),
363
+ (
364
+ "a month without spending",
365
+ ["report", "--month", "2026-12"],
366
+ ["books: €0.00 of €40.00", "food: €0.00 of €250.00", "total: €0.00"],
367
+ ),
368
+ ]
369
+ JSON_REPORT = { # report --month 2026-10 --json at the end: category -> (spent, budget, over)
370
+ "books": (0, 40, 0),
371
+ "food": (270.40, 250, 20.40),
372
+ "fun": (15.99, None, 0),
373
+ "travel": (41.40, None, 0),
374
+ }
375
+
376
+
377
+ def run(folder: Path, data: Path, argv: list[str]) -> subprocess.CompletedProcess:
378
+ env = {**os.environ, "EXPENSES_FILE": str(data), "PYTHONDONTWRITEBYTECODE": "1"}
379
+ env.pop("PYTHONPATH", None)
380
+ return subprocess.run(
381
+ [sys.executable, "-m", "expenses", *argv],
382
+ cwd=folder,
383
+ env=env,
384
+ capture_output=True,
385
+ text=True,
386
+ stdin=subprocess.DEVNULL,
387
+ timeout=30,
388
+ )
389
+
390
+
391
+ def lines(text: str) -> list[str]:
392
+ return [line.rstrip() for line in text.strip().splitlines()]
393
+
394
+
395
+ def json_problem(text: str) -> str | None:
396
+ try:
397
+ categories = {c["category"]: c for c in json.loads(text)["categories"]}
398
+ except (ValueError, KeyError, TypeError):
399
+ return "report --json isn't the report with a list of categories"
400
+ for name, (spent, budget, over) in JSON_REPORT.items():
401
+ got = categories.get(name)
402
+ if got is None:
403
+ return f"report --json leaves out {name}"
404
+ want = {"spent": spent, "budget": budget, "over": over}
405
+ for key, value in want.items():
406
+ have = got.get(key, "missing")
407
+ if value is None:
408
+ if have is not None:
409
+ return f"report --json: {name}'s {key} is {have!r}, not null"
410
+ elif not isinstance(have, (int, float)) or isinstance(have, bool) or abs(have - value) > 0.001:
411
+ return f"report --json: {name}'s {key} is {have!r}, not {value}"
412
+ return None
413
+
414
+
415
+ def check(folder: Path, answer: str):
416
+ from lcode.bench import Check, last_line, run_python
417
+
418
+ if not (folder / "expenses" / "cli.py").is_file():
419
+ return Check(False, "expenses/cli.py is missing")
420
+ r = run_python(folder, "-m", "unittest", "-q")
421
+ if r.returncode != 0:
422
+ return Check(False, f"its tests fail: {last_line(r.stderr) or last_line(r.stdout)}")
423
+ with tempfile.TemporaryDirectory(prefix="lcode-bench-budgets-") as tmp:
424
+ data = Path(tmp) / "old.json"
425
+ data.write_text(json.dumps(OLD_DATA, indent=2))
426
+ for what, argv, want in SESSION:
427
+ r = run(folder, data, argv)
428
+ if r.returncode != 0:
429
+ return Check(False, f"{what}: `{' '.join(argv)}` failed: {last_line(r.stderr)}")
430
+ if want is not None and lines(r.stdout) != want:
431
+ got = " / ".join(lines(r.stdout)) or "nothing"
432
+ return Check(False, f"{what}: `{' '.join(argv)}` printed {got[:150]}")
433
+ r = run(folder, data, ["report", "--month", "2026-10", "--json"])
434
+ problem = json_problem(r.stdout) if r.returncode == 0 else f"report --json failed: {last_line(r.stderr)}"
435
+ if problem:
436
+ return Check(False, problem)
437
+ saved = json.loads(data.read_text())
438
+ if saved.get("version") != 2:
439
+ return Check(False, f'the data file has "version": {saved.get("version")!r}, not 2')
440
+ if len(saved.get("expenses", [])) != len(OLD_DATA["expenses"]) + 1:
441
+ return Check(False, "the data file lost expenses")
442
+ return Check(True, "budgets work in the report, in JSON and with old data, and its tests pass")