lcode-cli 0.52.0__py3-none-any.whl → 0.53.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.52.0"
6
+ __version__ = "0.53.0"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/agent.py CHANGED
@@ -18,6 +18,7 @@ import uuid
18
18
  from collections.abc import Callable
19
19
  from dataclasses import dataclass
20
20
  from pathlib import Path
21
+ from typing import TYPE_CHECKING
21
22
 
22
23
  from rich.console import Console
23
24
  from rich.markdown import Markdown
@@ -41,6 +42,7 @@ from lcode import (
41
42
  review,
42
43
  sessions,
43
44
  subagents,
45
+ traces,
44
46
  vision,
45
47
  web,
46
48
  )
@@ -77,6 +79,9 @@ from lcode.tools import (
77
79
  )
78
80
  from lcode.unreachable import NOTE_AT, Sites
79
81
 
82
+ if TYPE_CHECKING:
83
+ from lcode.replay import ReplayServer
84
+
80
85
  GPU_MEMORY_ERRORS = (
81
86
  "out of memory",
82
87
  "illegal memory access",
@@ -349,6 +354,7 @@ class Settings:
349
354
  escalate_model: str | None = None # a stronger model to ask when stuck (lcode.escalate): provider/model
350
355
  escalate_url: str | None = None # its server, when not the provider's usual one
351
356
  escalate_price: str | None = None # dollars per million tokens in/out, e.g. "3/15", for the cost estimate
357
+ trace: bool = False # record each request on this machine (lcode.traces)
352
358
 
353
359
 
354
360
  class Agent:
@@ -436,6 +442,8 @@ class Agent:
436
442
  self._repo: tuple[Path, repoid.Repo | None] | None = None # the workspace's repository, for saved sessions
437
443
  self.last_speed = 0.0
438
444
  self.usage = {"requests": 0, "prompt_tokens": 0, "prompt_ns": 0, "output_tokens": 0, "output_ns": 0}
445
+ self.trace: traces.Lane | None = None # the request's trace while it's recorded (lcode.traces)
446
+ self.replay: ReplayServer | None = None # in a replay: the recorded results of tools and checks (lcode.replay)
439
447
  self.messages: list[dict] = []
440
448
  self.reset()
441
449
 
@@ -981,7 +989,10 @@ class Agent:
981
989
  added = "\n".join(f"- {note}" for note in self.turn_requests[1:])
982
990
  request += f"\n\nWhat the user added while you worked:\n{added}"
983
991
  try:
984
- with self.console.status("Reviewing the change against your request…", spinner="dots"):
992
+ with (
993
+ self.console.status("Reviewing the change against your request…", spinner="dots"),
994
+ traces.purpose(self, "review"),
995
+ ):
985
996
  problems = review.run(self, request, answer, diff)
986
997
  except OllamaError as e:
987
998
  self.say(f"The review didn't run: {e}", warning=True)
@@ -1043,8 +1054,12 @@ class Agent:
1043
1054
  def run_check(self, check: checks.Check, round_: int) -> str | None:
1044
1055
  """Run the checks after a change. Returns what to tell the model when they fail, else None."""
1045
1056
  self.say(f"Checking the work: {check.command} (from {check.source})")
1046
- result = self.tools.run("bash", {"command": check.command, "timeout": checks.TIMEOUT})
1057
+ result = self.replay.check_result(check.command) if self.replay is not None else None
1058
+ if result is None:
1059
+ result = self.tools.run("bash", {"command": check.command, "timeout": checks.TIMEOUT})
1047
1060
  code = checks.exit_code(result)
1061
+ if self.trace is not None:
1062
+ self.trace.check(check.command, result, code)
1048
1063
  self.check_results.append({"command": check.command, "exit_code": code, "by": "lcode"})
1049
1064
  if code is None:
1050
1065
  self.say(f"The checks didn't run: {result.splitlines()[0][:200]}", warning=True)
@@ -1153,9 +1168,20 @@ class Agent:
1153
1168
  def run_turn(self, user_text: str) -> None:
1154
1169
  self.turn_started = time.monotonic()
1155
1170
  self.checkpoints.begin_turn(self.session_id, user_text, len(self.messages))
1171
+ lane = traces.start(self, user_text)
1172
+ status, error = "error", ""
1156
1173
  try:
1157
1174
  self._run_turn(user_text)
1175
+ status = self.turn_status
1176
+ except KeyboardInterrupt:
1177
+ status = "interrupted"
1178
+ raise
1179
+ except Exception as e:
1180
+ error = str(e) if isinstance(e, OllamaError) else f"{type(e).__name__}: {e}"
1181
+ raise
1158
1182
  finally:
1183
+ if lane is not None:
1184
+ traces.finish(self, lane, status, error)
1159
1185
  self.checkpoints.end_turn()
1160
1186
  if self.hooks.hooks and self.allowed_tools is None:
1161
1187
  payload = {"request": user_text[:2000], "cwd": str(self.cwd), "session": self.session_id}
@@ -1189,6 +1215,8 @@ class Agent:
1189
1215
 
1190
1216
  def sandbox_root(self) -> Path | None:
1191
1217
  """The folder the model is limited to while the sandbox is on (None when it's off)."""
1218
+ if self.replay is not None:
1219
+ return self.replay.root # a replay changes nothing outside its copy of the folder (lcode.traces)
1192
1220
  if not self.sandbox:
1193
1221
  return None
1194
1222
  try:
@@ -1290,7 +1318,7 @@ class Agent:
1290
1318
  why = "its replies went round in circles or ended without an answer, twice in this request"
1291
1319
  if not escalated and self.can_escalate():
1292
1320
  escalated = True
1293
- advice = escalate.run(self, why)
1321
+ advice = self.ask_stronger(why)
1294
1322
  if advice:
1295
1323
  self.messages.append({"role": "user", "content": advice})
1296
1324
  stalls = 0
@@ -1334,7 +1362,7 @@ class Agent:
1334
1362
  if check_rounds >= checks.MAX_ROUNDS and not escalated and self.can_escalate():
1335
1363
  escalated = True
1336
1364
  why = f"the project's checks (`{check.command}`) failed {check_rounds} times in a row"
1337
- advice = escalate.run(self, why, failure=feedback)
1365
+ advice = self.ask_stronger(why, failure=feedback)
1338
1366
  if advice:
1339
1367
  self.messages.append({"role": "user", "content": advice})
1340
1368
  check_rounds -= 1 # the checks run once more after the advice
@@ -1376,8 +1404,11 @@ class Agent:
1376
1404
  self.on_tool(name, args)
1377
1405
  if name not in ("bash", "todo_write", "web_search", "web_fetch", "agent"): # those print their own
1378
1406
  self.console.print(Text(f"● {self.describe_call(name, args)}", style="bold magenta"))
1407
+ began = time.monotonic()
1408
+ if self.trace is not None:
1409
+ self.trace.tool_begin()
1379
1410
  try:
1380
- result = done[i] if i in done else self.tools.run(name, args)
1411
+ result = done[i] if i in done else self.run_tool(name, args)
1381
1412
  except KeyboardInterrupt:
1382
1413
  for rest in calls[i:]:
1383
1414
  self.messages.append(
@@ -1425,6 +1456,8 @@ class Agent:
1425
1456
  changed, verified = True, False
1426
1457
  elif name == "bash" and changed and self.model_ran_checks(str(args.get("command", "")), result):
1427
1458
  verified = True # the model ran the checks itself, after its last change
1459
+ if self.trace is not None:
1460
+ self.trace.tool(call.get("id", ""), name, args, result, time.monotonic() - began)
1428
1461
  tool_msg = {"role": "tool", "tool_name": name, "content": result}
1429
1462
  if call.get("id"):
1430
1463
  tool_msg["tool_call_id"] = call["id"]
@@ -1451,7 +1484,7 @@ class Agent:
1451
1484
  break
1452
1485
  if looping and not escalated and self.can_escalate():
1453
1486
  escalated = True
1454
- advice = escalate.run(self, f"it kept making the same call with the same result: {looping}")
1487
+ advice = self.ask_stronger(f"it kept making the same call with the same result: {looping}")
1455
1488
  if advice:
1456
1489
  self.messages.append({"role": "user", "content": advice})
1457
1490
  self.repeats.reset()
@@ -1486,6 +1519,24 @@ class Agent:
1486
1519
  self.turn_status = "success"
1487
1520
  self.print_stats()
1488
1521
 
1522
+ def run_tool(self, name: str, args: dict) -> str:
1523
+ if self.replay is not None: # a replay gives some tools their recorded results (lcode.traces)
1524
+ served = self.replay.tool_result(name, args)
1525
+ if served is not None:
1526
+ return served
1527
+ args = self.replay.moved(args) # the recorded folder's paths point into the replay's copy
1528
+ return self.tools.run(name, args)
1529
+
1530
+ def ask_stronger(self, why: str, failure: str = "") -> str | None:
1531
+ """The stronger model's advice for the local model, if one is set and the user agrees (lcode.escalate)."""
1532
+ if self.replay is not None:
1533
+ return self.replay.escalation(why)
1534
+ with traces.inside(self, "escalate"):
1535
+ advice = escalate.run(self, why, failure)
1536
+ if self.trace is not None:
1537
+ self.trace.escalation(why, advice)
1538
+ return advice
1539
+
1489
1540
  def keep_dropped(self, reply: dict) -> str:
1490
1541
  """Save a reply lcode dropped (its thinking too), so the user can see what went round in circles."""
1491
1542
  text = "\n\n".join(part for part in (reply.get("thinking"), reply.get("content")) if part)
@@ -1665,7 +1716,8 @@ class Agent:
1665
1716
  if len(self.messages) <= 2:
1666
1717
  return
1667
1718
  if self.interactive:
1668
- memory_notes.reflect(self) # what the summary leaves out is gone for good
1719
+ with traces.inside(self, "memory"):
1720
+ memory_notes.reflect(self) # what the summary leaves out is gone for good
1669
1721
  instructions = (
1670
1722
  "Summarize this conversation so the work can continue in a fresh context. Include: the user's goals "
1671
1723
  "and requests, key facts learned about the codebase (files, functions, paths with line numbers), "
@@ -1675,7 +1727,7 @@ class Agent:
1675
1727
  if focus:
1676
1728
  instructions += f" Focus especially on: {focus}"
1677
1729
  summary = ""
1678
- with self.console.status("[cyan]Compacting…[/]"):
1730
+ with self.console.status("[cyan]Compacting…[/]"), traces.purpose(self, "summary"):
1679
1731
  for chunk in self.chat([*self.messages, {"role": "user", "content": instructions}], None, False):
1680
1732
  summary += chunk.get("message", {}).get("content", "")
1681
1733
  requests = context_tools.user_requests(self.messages)
lcode/api.py CHANGED
@@ -18,12 +18,14 @@ from __future__ import annotations
18
18
  import contextlib
19
19
  import io
20
20
  import queue
21
+ import shlex
21
22
  import threading
22
23
  import time
23
24
  from collections.abc import Callable, Iterator
24
25
  from dataclasses import asdict, dataclass, field
25
26
  from pathlib import Path
26
27
  from typing import TYPE_CHECKING, Any
28
+ from urllib.parse import urlsplit
27
29
 
28
30
  from rich.console import Console
29
31
 
@@ -40,8 +42,9 @@ STATUSES = ("success", "error", "max_steps", "loop", "interrupted")
40
42
  EXIT_CODES = {"success": 0, "error": 1, "max_steps": 3, "loop": 4, "interrupted": 130}
41
43
  OLLAMA_INSTALL = {
42
44
  "linux": "curl -fsSL https://ollama.com/install.sh | sh",
43
- "darwin": "brew install ollama (or download it from https://ollama.com/download)",
45
+ "macos": "brew install ollama && brew services start ollama (or download the app from https://ollama.com/download)",
44
46
  }
47
+ DOCKER_TIMEOUT = 10 # seconds for Docker to list its containers, when Ollama doesn't answer
45
48
 
46
49
 
47
50
  class SetupError(Exception):
@@ -114,14 +117,51 @@ def check_server(ollama, hw: Hardware | None = None) -> str:
114
117
  except OllamaError as e:
115
118
  from lcode.hardware import detect
116
119
 
117
- hint = OLLAMA_INSTALL.get((hw or detect()).os, OLLAMA_INSTALL["linux"])
118
- raise SetupError(f"{e}\n\nIs Ollama installed and running? Install it with:\n {hint}") from e
120
+ raise SetupError(f"{e}\n\n{ollama_down(ollama.host, (hw or detect()).os)}") from e
119
121
  if version_tuple(version) < MIN_VERSION:
120
122
  needed = ".".join(map(str, MIN_VERSION))
121
123
  raise SetupError(f"Ollama {version} is too old; lcode needs {needed} or newer. Update Ollama.")
122
124
  return version
123
125
 
124
126
 
127
+ def ollama_down(host: str, os_name: str) -> str:
128
+ """What to do when Ollama doesn't answer at `host`: start the Docker container it runs in, or install it."""
129
+ from lcode import update
130
+
131
+ docker = urlsplit(host).hostname in update.LOCAL_HOSTS and update.docker_installed()
132
+ containers, trouble = [], ""
133
+ try:
134
+ containers = update.ollama_containers(host, stopped=True, timeout=DOCKER_TIMEOUT) if docker else []
135
+ except (update.UpdateError, ValueError) as e: # Docker isn't running, or doesn't let this user in
136
+ trouble = str(e).removeprefix("docker ps failed: ")
137
+ if len(containers) == 1:
138
+ container = containers[0]
139
+ if container.running:
140
+ return (
141
+ f"Ollama runs in Docker, in the container {container.name}, but doesn't answer. If it has just "
142
+ f"started, try again in a moment; if not, see why:\n docker logs --tail 20 {container.name}"
143
+ )
144
+ compose = container.compose
145
+ if compose and compose["files"] and all(Path(f).is_file() for f in compose["files"]):
146
+ start = shlex.join(update.compose_up(compose)[0])
147
+ else:
148
+ start = f"docker start {container.name}"
149
+ return f"Ollama runs in Docker, in the container {container.name}, which is stopped. Start it with:\n {start}"
150
+ if containers:
151
+ names = ", ".join(c.name for c in containers)
152
+ return f"Ollama runs in Docker here, in one of these containers: {names}. Start it with:\n docker start <name>"
153
+ install = OLLAMA_INSTALL.get(os_name, OLLAMA_INSTALL["linux"])
154
+ hint = f"Is Ollama installed and running? Install it with:\n {install}"
155
+ if trouble:
156
+ hint += f"\nIf you run Ollama in Docker, start Docker first. It says: {trouble}"
157
+ elif docker:
158
+ hint += (
159
+ "\nIf you ran Ollama in Docker, its container is gone: create it again (with Docker Compose: "
160
+ "docker compose up -d, in the folder of its compose file)."
161
+ )
162
+ return hint
163
+
164
+
125
165
  def switch(wanted: bool | None, configured: str, default_on: str) -> str:
126
166
  """A setting that's "off" or some mode: None keeps the config's, False turns it off, True on."""
127
167
  if wanted is None:
@@ -232,6 +272,7 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
232
272
  escalate_url=cfg["escalate_url"],
233
273
  escalate_price=cfg["escalate_price"],
234
274
  compact_at=cfg["compact_at"],
275
+ trace=cfg["trace"],
235
276
  )
236
277
  agent = Agent(ollama, settings, cwd, console=console)
237
278
  agent.hardware = hw
lcode/cli.py CHANGED
@@ -30,11 +30,6 @@ from lcode.ollama import MIN_VERSION, Ollama, OllamaError, redact, version_tuple
30
30
 
31
31
  console = Console(highlight=False)
32
32
 
33
- OLLAMA_INSTALL = {
34
- "linux": "curl -fsSL https://ollama.com/install.sh | sh",
35
- "macos": "brew install ollama && brew services start ollama (or download the app from https://ollama.com)",
36
- }
37
-
38
33
 
39
34
  class NotInstalled(Exception):
40
35
  pass
@@ -382,7 +377,10 @@ def cmd_doctor(args) -> None:
382
377
  if openai:
383
378
  line("", f"start {ollama.name}'s server, or set its address: lcode config set base_url <url>", None)
384
379
  else:
385
- line("", f"install: {OLLAMA_INSTALL.get(hw.os, OLLAMA_INSTALL['linux'])}", None)
380
+ from lcode import api
381
+
382
+ for text in api.ollama_down(ollama.host, hw.os).splitlines():
383
+ line("", escape(text.strip()), None)
386
384
  sys.exit(1)
387
385
  try:
388
386
  model, spec = resolve_model(ollama, cfg["model"])
@@ -859,7 +857,7 @@ def build_parser() -> argparse.ArgumentParser:
859
857
  parser = argparse.ArgumentParser(
860
858
  prog="lcode",
861
859
  description="A local-first terminal coding agent powered by open-weight models via Ollama.",
862
- epilog="Subcommands: lcode setup | models | doctor | config | bench | mcp | index | update "
860
+ epilog="Subcommands: lcode setup | models | doctor | config | bench | trace | mcp | index | update "
863
861
  "(lcode <subcommand> --help). "
864
862
  "Docs: https://nasser1941.github.io/lcode/",
865
863
  )
@@ -981,6 +979,25 @@ def build_subparsers() -> dict[str, argparse.ArgumentParser]:
981
979
  help="summarize at this many tokens, e.g. 64k (default: the compact_at setting; 0: only at 85%%)",
982
980
  )
983
981
  subs["bench"] = p
982
+ p = argparse.ArgumentParser(
983
+ prog="lcode trace",
984
+ description="Requests recorded on this machine (the trace setting): list them, show one step by step, "
985
+ "export one for a bug report with secrets and personal details masked, or replay one with the recorded "
986
+ "answers instead of a model and see where the tool results now differ.",
987
+ )
988
+ p.add_argument("action", nargs="?", default="list", help="list (default), show, export, replay or path")
989
+ p.add_argument("trace", nargs="?", help="a number from the list (1: the newest), a trace id or a trace file")
990
+ p.add_argument("-n", "--limit", type=int, default=20, help="list: how many (default: 20)")
991
+ p.add_argument("-v", "--verbose", action="store_true", help="show: also the model's answers and results")
992
+ p.add_argument(
993
+ "-o", "--output", help="export: the file to write (default: lcode-trace-<id>.jsonl here; - prints it)"
994
+ )
995
+ p.add_argument("--repo", help="replay: in a copy of this folder (default: the recorded folder, at its commit)")
996
+ p.add_argument(
997
+ "--commands", action="store_true", help="replay: run shell commands and the checks again too (in the copy)"
998
+ )
999
+ p.add_argument("--keep", action="store_true", help="replay: keep the copy it ran in")
1000
+ subs["trace"] = p
984
1001
  p = argparse.ArgumentParser(
985
1002
  prog="lcode index",
986
1003
  description="Build or refresh the semantic code search index of the repository (an Ollama embedding model).",
@@ -1139,6 +1156,12 @@ def cmd_media(args) -> None:
1139
1156
  console.print("[dim]Install one: lcode media install <model> · choose in image mode: /model <model>[/]")
1140
1157
 
1141
1158
 
1159
+ def cmd_trace(args) -> None:
1160
+ from lcode import traces
1161
+
1162
+ sys.exit(traces.command(args, console))
1163
+
1164
+
1142
1165
  def cmd_mcp(args) -> None:
1143
1166
  from lcode.mcp.commands import run
1144
1167
 
@@ -1152,6 +1175,7 @@ COMMANDS = {
1152
1175
  "media": cmd_media,
1153
1176
  "config": cmd_config,
1154
1177
  "bench": cmd_bench,
1178
+ "trace": cmd_trace,
1155
1179
  "mcp": cmd_mcp,
1156
1180
  "index": cmd_index,
1157
1181
  "action": cmd_action,
lcode/config.py CHANGED
@@ -88,6 +88,7 @@ SETTINGS: dict[str, tuple[object, type, str]] = {
88
88
  "secret_check": (True, bool, "before git commit and git push, look for passwords, keys and tokens they'd add"),
89
89
  "compact_at": (65536, int, "summarize at this many tokens even when the window is larger (0: only at 85%)"),
90
90
  "max_parallel_agents": (1, int, "subagents that may run at the same time (more needs OLLAMA_NUM_PARALLEL)"),
91
+ "trace": (True, bool, "record each request's steps, timings and tokens on this machine, for lcode trace"),
91
92
  }
92
93
  ENV_OVERRIDES = {
93
94
  "LCODE_MODEL": "model",
@@ -61,6 +61,7 @@ lcode config path # print the file location
61
61
  | `repeat_limit` | `3` | Identical tool calls with identical results before lcode [steps in](how-it-works.md#when-the-model-repeats-itself); `0` turns it off, along with the checks for [unreachable sites](how-it-works.md#when-a-site-cant-be-reached) and [thinking in circles](how-it-works.md#when-a-reply-goes-nowhere) |
62
62
  | `secret_check` | `true` | Before `git commit` and `git push`, look for passwords, keys and tokens they'd add ([details](usage.md#secrets-in-commits)) |
63
63
  | `checkpoints` | `true` | Save a checkpoint before the model changes files, so [`/undo`](usage.md#undo-and-checkpoints) can restore them |
64
+ | `trace` | `true` | Record each request's model calls, tool calls, times and tokens on this machine, for [`lcode trace`](traces.md) (kept 30 days) |
64
65
 
65
66
  Besides these settings, `config.toml` can hold [hooks](hooks.md) (`[[hooks]]`) and
66
67
  [permission rules](hooks.md#permission-rules) (`[permissions]`); a repository can have its own in
@@ -115,9 +116,10 @@ Environment variables override the file, which is useful for one-off runs and CI
115
116
  | `~/.local/state/lcode/lsp-logs/` | Language servers' own output |
116
117
  | `~/.local/state/lcode/index/` | [Code search](search.md#semantic-code-search) indexes, one per repository (`lcode index`) |
117
118
  | `~/.local/state/lcode/outputs/` | The full text of long command output that was cut short for the model (kept a week) |
119
+ | `~/.local/state/lcode/traces/` | [Run traces](traces.md): each request's steps, times and tokens, one file per request (kept 30 days, 200 MB at most) |
118
120
  | `~/.local/state/lcode/limits.json` | Context sizes that ran out of GPU memory on this machine (safe to delete) |
119
121
 
120
- Sessions contain everything the model read, including file contents. Delete the folder to clear them.
122
+ Sessions and traces contain everything the model read, including file contents. Delete the folders to clear them.
121
123
 
122
124
  ## Tuning for speed and memory
123
125
 
lcode/docs/quickstart.md CHANGED
@@ -12,7 +12,7 @@ lcode
12
12
 
13
13
  ```text
14
14
  ╭──────────────────────────────────────────────╮
15
- │ lcode v0.52.0 — local coding agent │
15
+ │ lcode v0.53.0 — local coding agent │
16
16
  │ │
17
17
  │ model lcode-qwen3.6-35b │
18
18
  │ context 256K tokens │
lcode/docs/traces.md ADDED
@@ -0,0 +1,183 @@
1
+ # Run traces
2
+
3
+ lcode records each request in code mode as it runs: every model call and every tool call, with
4
+ its times and tokens. A trace shows where a slow or failed request spent its time and went wrong,
5
+ it can go with a bug report, and it can be **replayed** without a model to check a change to lcode
6
+ against real runs.
7
+
8
+ ```bash
9
+ lcode trace # the newest 20 requests
10
+ lcode trace show 1 # the newest one, step by step (or just: lcode trace 1)
11
+ lcode trace show 1 -v # also the model's answers and the start of each result
12
+ lcode trace export 1 # a copy for a bug report, with secrets and personal details masked
13
+ lcode trace replay 1 # run it again with the recorded answers instead of a model
14
+ lcode trace path # the folder the traces are in
15
+ ```
16
+
17
+ ## What's recorded
18
+
19
+ - **The request** as you typed it, and what lcode added to the conversation while it ran: a
20
+ failed check, a note about a malformed tool call, a note you typed while it worked.
21
+ - **Each model call:** the answer (text, reasoning and tool calls), the time to the first token,
22
+ the total time, and the tokens in and out. With Ollama, also how long loading the model and
23
+ reading the prompt took.
24
+ - **Each tool call:** its arguments, the result the model got, and how long it took. A result
25
+ longer than 200,000 characters keeps its start and end. When lcode cut a long output for the
26
+ model, the result says where the full output was saved.
27
+ - **The setup:** the model, its context window and the model's own sampling settings
28
+ (temperature, top_p and so on: lcode doesn't change them), the settings that change how lcode
29
+ works (checks, review, `compact_at`…), the permission mode, the lcode version, the git commit
30
+ the folder was at, and a fingerprint of the system prompt and of the tool definitions.
31
+ - **Subagents:** their model and tool calls, each subagent in a lane of its own.
32
+
33
+ ## Where, and for how long
34
+
35
+ Traces stay on your machine: nothing is sent anywhere. Each request is one file in
36
+ `~/.local/state/lcode/traces/` (under `$LCODE_HOME` when that's set), named after its session and
37
+ its number in it: `20261031-142233-a1b2c3-2.jsonl` is the second request of that session. A
38
+ file holds one JSON object per line, written as the request runs, so a request that crashed
39
+ still has everything up to the crash.
40
+
41
+ - Traces older than **30 days** are deleted.
42
+ - When all of them take more than **200 MB**, the oldest go first.
43
+ - One trace stops growing at **20 MB**; it still records how the request ended.
44
+
45
+ A trace holds what the session saw, like a saved session does: the contents of files the model
46
+ read, command output, and any secrets in them. Share one with `lcode trace export`, which masks
47
+ them.
48
+
49
+ **Turn traces off** with `lcode config set trace false`. `lcode bench` doesn't record its runs.
50
+
51
+ Recording takes a few milliseconds per request (2 ms for the 88-second request below): each trace
52
+ says how long in its last line (`trace_seconds`), and `lcode trace show` as *recording*.
53
+
54
+ ## Reading a trace
55
+
56
+ ```text
57
+ $ lcode trace
58
+ # When Request Model Steps Time Status
59
+ 1 1 min ago Use two explore agents at the same time: on… lcode-qwen3.6-35b 2 1 min 13 s success
60
+ 2 5 min ago The tests fail. Find out why and fix the co… lcode-qwen3.6-35b 6 1 min 28 s success
61
+ 2 trace(s), 25 KB, in ~/.local/state/lcode/traces (kept 30 days). lcode trace show 1 · export 1 · replay 1
62
+ ```
63
+
64
+ ```text
65
+ $ lcode trace show 2
66
+ Trace 20261031-184203-3e0674-1 · 2026-10-31 18:42 · success in 1 min 28 s
67
+ Request: The tests fail. Find out why and fix the code (not the tests).
68
+ lcode-qwen3.6-35b · 256K context · thinking on · yolo mode · lcode 0.53.0 · ~/code/textstats at 958102f
69
+ Sampling (the model's own): top_k 20, top_p 0.95, min_p 0, temperature 0.6
70
+
71
+ 1.3 s model 1 10.2K in · 206 out · first token 1 min 3 s (loading 21 s, reading 41 s) · 1 min 6 s → read_file, read_file
72
+ 67.4 s read_file src/textstats/stats.py 13 lines 0.0 s
73
+ 67.4 s read_file tests/test_stats.py 13 lines 0.0 s
74
+ 67.4 s model 2 10.8K in · 50 out · first token 1.7 s · 2.4 s → bash
75
+ 69.9 s bash python3 -m pytest -q 2>&1 36 lines 0.3 s
76
+ 70.2 s model 3 11.2K in · 364 out · first token 1.6 s · 7.6 s → edit_file
77
+ 77.8 s edit_file src/textstats/stats.py 8 lines 0.8 s
78
+ 78.6 s model 4 11.7K in · 195 out · first token 1.2 s · 4.1 s → edit_file
79
+ 82.8 s edit_file src/textstats/stats.py 8 lines 0.3 s
80
+ 83.1 s model 5 12.0K in · 51 out · first token 1.4 s · 2.1 s → bash
81
+ 85.2 s bash python3 -m pytest -q 2>&1 4 lines 0.2 s
82
+ 85.4 s model 6 12.1K in · 144 out · first token 0.8 s · 3.1 s → answer
83
+
84
+ success · 6 model call(s) · 68.0K tokens in, 1.0K out · model 1 min 25 s · tools 1.6 s (6 calls) · recording 2 ms
85
+ Changed: src/textstats/stats.py
86
+ ```
87
+
88
+ Each line shows when its step started. Here the first model call waited a minute for
89
+ its first token: 21 seconds loading the model into memory and 41 seconds reading the prompt into
90
+ a fresh 256K context. After that, each step answered within two seconds. A subagent's steps
91
+ show its lane (`agent 1`, `agent 2`) and the task it was given.
92
+
93
+ The file itself is plain JSON lines, one per event, for scripts: `start`, `env` (the git commit
94
+ and sampling settings), `message`, `model`, `tool`, `check`, `escalate`, `compacted`, and `end`
95
+ with the totals.
96
+
97
+ ## Exporting for a bug report
98
+
99
+ `lcode trace export 1` writes `lcode-trace-<id>.jsonl` in the current folder (`-o FILE` names
100
+ another; `-o -` prints it) with these masked:
101
+
102
+ - **secrets:** keys and tokens lcode's [secret check](usage.md#secrets-in-commits) recognizes,
103
+ passwords in web addresses and in `password = …` style settings, private keys, and the values
104
+ of your environment variables whose names say KEY, TOKEN, SECRET, PASSWORD and the like,
105
+ wherever they turn up;
106
+ - **your home folder** (shown as `~`) and other users' home folders;
107
+ - **names:** your user name, your full name, the name and email address in your git settings,
108
+ and the computer's name;
109
+ - **email addresses and IP addresses** (except 127.0.0.1).
110
+
111
+ It says how many of each it masked. Masking errs on the side of too much, but it can still miss
112
+ something, so read the file before you share it.
113
+
114
+ ## Replaying a trace
115
+
116
+ `lcode trace replay` runs a recorded request again, with the recorded answers standing in for the
117
+ model: no GPU and no model server needed. The tools run again in a temporary copy of the folder,
118
+ and lcode compares each result with the recorded one. It answers "does this change to lcode still
119
+ behave the same on real runs?" and, when it doesn't, shows exactly where.
120
+
121
+ ```text
122
+ $ lcode trace replay 2
123
+ Replaying 20261031-184203-3e0674-1 (6 model answer(s)) in ~/code/textstats at the recorded commit 958102f.
124
+ Shell commands get their recorded results; --commands runs them again in the copy.
125
+ Tool calls run again: 4, with the same result: 4. Given their recorded result: 2. Model calls: 6 recorded, 6 in the replay.
126
+ Status: recorded success, now success
127
+ No differences.
128
+ ```
129
+
130
+ When something differs, the replay shows where, with the recorded and the new result:
131
+
132
+ ```text
133
+ Tool calls run again: 4, with the same result: 3. Given their recorded result: 2. Model calls: 6 recorded, 6 in the replay.
134
+ Status: recorded success, now success
135
+ 1 difference(s):
136
+ step 1 · read_file src/textstats/stats.py
137
+ @@ -1,2 +1,2 @@
138
+ - 1 """Small text statistics."""
139
+ + 1 """Small text statistics: word counts and lengths."""
140
+ 2
141
+ ```
142
+
143
+ - **Where it runs:** never in your folder. In a copy of the git repository at the commit the
144
+ request started from (the copy doesn't have changes that weren't committed then; the replay
145
+ says so), or, outside git, in a copy of the folder as it is now. `--repo DIR` replays in a copy
146
+ of another folder, and `--keep` keeps the copy afterwards. Recorded paths into your folder point
147
+ into the copy, file tools can't reach anything outside it, and the copy has no git remotes.
148
+ - **What runs again:** reading, searching, writing and editing files, the todo list, skills, the
149
+ repository map, subagents and plans.
150
+ - **What gets its recorded result:** shell commands and the project's checks (`--commands` runs
151
+ them again, in the copy, as they were recorded: use it for traces whose commands you'd run
152
+ yourself), web searches and pages, MCP tools, language servers, code search,
153
+ images and screenshots, memory notes and a stronger model's advice; and whatever you answered,
154
+ such as a refused permission or your decision on a plan.
155
+ - **What's compared:** each tool call and its result, lcode's notes to the model, the checks' exit
156
+ codes, the number of model calls, and how the request ended. The folder's path, the names of
157
+ saved outputs, timings, and lines drawn to the terminal's width (pytest's `=====`) don't count.
158
+ Commands run with the terminal size the recorded ones had.
159
+
160
+ It exits with 0 when nothing differs and 1 when something does, so it fits in a script.
161
+
162
+ A replay doesn't repeat notes you typed while the request ran. Subagents that ran at the same time
163
+ replay one after another. An exported trace has its folder masked: replay it with `--repo`.
164
+
165
+ ### In tests
166
+
167
+ Any trace replays in a test, without a model server:
168
+
169
+ ```python
170
+ from pathlib import Path
171
+
172
+ from lcode import replay, traces
173
+
174
+
175
+ def test_the_parser_fix_still_replays(tmp_path):
176
+ folder = tmp_path / "parser"
177
+ ... # the files as they were when the trace was recorded
178
+ report = replay.run(traces.load(Path("tests/traces/parser-fix.jsonl")), folder)
179
+ assert report.ok, report.differences
180
+ ```
181
+
182
+ `report.differences` lists each difference with its step, the call, and the recorded and new
183
+ result.
@@ -17,9 +17,19 @@ Ollama isn't running (or isn't installed).
17
17
 
18
18
  - Linux: `sudo systemctl start ollama` (check with `systemctl status ollama`).
19
19
  - macOS: open the Ollama app, or `brew services start ollama`.
20
- - Docker: `docker start <container>`, and make sure port 11434 is published.
20
+ - Docker: lcode looks for the Ollama container that publishes port 11434, and says how to start it: with
21
+ `docker compose up` when Docker Compose made it, or `docker start <container>`. If there's no such
22
+ container any more (for example after `docker system prune`), create it again; when its volume was removed
23
+ as well (`docker volume prune -a`), so were the models: download them again with `lcode setup`.
21
24
  - Remote server: `lcode config set ollama_host http://host:11434`.
22
25
 
26
+ ### Docker: `all predefined address pools have been fully subnetted`
27
+
28
+ Docker Compose can't create a network for the Ollama container. A VPN that routes all traffic (for example
29
+ with routes `0.0.0.0/1` and `128.0.0.0/1`) covers every address range Docker would use. Put the
30
+ container on Docker's default network instead: add `network_mode: bridge` to the Ollama service in the
31
+ compose file, and run `docker compose up -d` again.
32
+
23
33
  ### `lcode isn't set up yet` / `… is not installed yet`
24
34
 
25
35
  Run `lcode setup` (or `lcode setup <model>`) to download a model.
lcode/docs/usage.md CHANGED
@@ -10,6 +10,7 @@ lcode doctor # check the installation (include this in bug repor
10
10
  lcode media [install MODEL] # image and video models: what fits here, what's installed; install one
11
11
  lcode config [set|unset] # show or change settings
12
12
  lcode bench [models] # score models on small coding tasks on this machine
13
+ lcode trace [action] [N] # past requests: show one step by step, export or replay it (see Run traces)
13
14
  lcode mcp [catalog|add|list] # connect MCP servers: Jira, GitHub, AWS, databases… (see MCP servers)
14
15
  lcode acp # run inside an editor over the Agent Client Protocol (see Editors)
15
16
  lcode update [--check] # update lcode, and Ollama when it runs in Docker (see Installation)
@@ -519,6 +520,9 @@ a screen and sees what you would, measured:
519
520
  - Needs: Xvfb for other desktop programs (`sudo apt install xvfb x11-apps`), and Chrome or
520
521
  Chromium for web pages. On macOS only Qt programs and web pages work, since there's no virtual
521
522
  display.
523
+ - The first web page after a restart can take a few seconds longer, while the browser loads from
524
+ disk: lcode gives it 90 seconds to start. If it doesn't start, or quits, the error says which and
525
+ quotes the browser's last lines.
522
526
 
523
527
  ## Permissions
524
528
 
@@ -766,6 +770,10 @@ model has to read a file again before editing it.
766
770
  `LCODE_HOME`, or `XDG_STATE_HOME`, moves that folder: a terminal that sets one of them (some IDEs
767
771
  and test scripts do) sees other sessions. `lcode bench` doesn't save its runs as sessions.
768
772
 
773
+ Each request is also recorded as a [run trace](traces.md): its model and tool calls with their
774
+ times and tokens. `lcode trace` lists them, and `lcode trace show 1` shows the last one step by
775
+ step.
776
+
769
777
  ## Scripting
770
778
 
771
779
  `-p` runs one request and exits, which is handy in scripts and git hooks: