lcode-cli 0.60.0__py3-none-any.whl → 0.62.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.60.0"
6
+ __version__ = "0.62.0"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/agent.py CHANGED
@@ -42,7 +42,8 @@ from lcode.tool_helpers import ToolError, is_binary, tree
42
42
  if TYPE_CHECKING:
43
43
  pass
44
44
 
45
- MAX_STALLS = 2 # replies that go round in circles or say nothing, per request, before lcode stops it
45
+ MAX_STALLS = 2 # replies in a row that go round in circles or say nothing, before lcode stops the request
46
+ MAX_STALLS_PER_REQUEST = 4 # such replies in one request, even with work in between
46
47
  STALLED = {
47
48
  "circles": "the reply went round in circles, so lcode stopped it",
48
49
  "cut_off": "the reply filled the context before it said anything",
@@ -50,15 +51,16 @@ STALLED = {
50
51
  }
51
52
 
52
53
 
53
- def stall_note(trouble: str) -> str:
54
+ def stall_note(trouble: str, thinking_off: bool = False) -> str:
54
55
  """What the model is told after a reply that went round in circles or ended without a word."""
55
56
  first = {
56
57
  "circles": "Your last reply went round in circles (the same thoughts over and over), so lcode stopped it.",
57
58
  "cut_off": "Your last reply filled the rest of the context before you said anything.",
58
59
  "": "Your last reply was empty.",
59
60
  }[trouble]
61
+ off = ": thinking is off for this reply" if thinking_off else ""
60
62
  return (
61
- f"[lcode] {first} Don't deliberate at length now. Either make your next tool call, or, if you're stuck, "
63
+ f"[lcode] {first} Don't deliberate at length now{off}. Either make your next tool call, or, if you're stuck, "
62
64
  "tell the user in a few lines what you did, what fails, and what they could do. If you were about to check "
63
65
  "something by running it, run it now instead of reasoning about it: for a window, take a screenshot (with "
64
66
  "actions for clicks or keys)."
@@ -280,9 +282,13 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
280
282
  malformed = 0
281
283
  looping = "" # the call the model kept repeating, when lcode stopped the request for it
282
284
  blocked = None # the site that couldn't be reached, when lcode stopped the request for it
283
- stalls = 0 # replies that went round in circles or ended without a word
285
+ stalls = 0 # replies in a row that went round in circles or ended without a word
286
+ stalled = 0 # such replies in this request
284
287
  commands: list[str] = [] # shell commands run in this request
285
288
  scripts_noted = False # the model was told about scripts it wrote and never ran
289
+ untested: dict[str, None] = {} # code files the model wrote in this request and hasn't run since (#242)
290
+ untested_noted = False # the model was told about them
291
+ missing: dict[str, None] = {} # programs a command in this request found missing
286
292
  tools_used: set[str] = set() # tools called in this request
287
293
  windows_noted = False # the model was told about windows it changed and never looked at
288
294
  for step in range(self.max_steps):
@@ -294,7 +300,8 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
294
300
  self.save() # a crash or a closed terminal loses at most this step
295
301
  self.maybe_compact()
296
302
  try:
297
- reply = self.assistant_step()
303
+ # After a reply that went nowhere, the next one runs without thinking, so the model acts.
304
+ reply = self.assistant_step(think=not (stalls and self.can_skip_thinking()))
298
305
  calls = reply.get("tool_calls") or []
299
306
  for i, call in enumerate(calls):
300
307
  call.setdefault("id", f"call_{step}_{i}") # so a tool result can name its call
@@ -336,15 +343,22 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
336
343
  continue
337
344
  if not calls and (self.reply_trouble == "circles" or not (reply.get("content") or "").strip()):
338
345
  stalls += 1
346
+ stalled += 1
339
347
  dropped = self.messages.pop() # no answer, and circles would only fill the context
340
348
  kept = self.keep_dropped(dropped)
341
- if stalls < MAX_STALLS:
349
+ if stalls < MAX_STALLS and stalled < MAX_STALLS_PER_REQUEST:
350
+ # The next reply runs with thinking off: asked again with it on, the model mostly started
351
+ # the same deliberation over (all 6 polyglot-rust-c attempts on the dev slice, #241).
352
+ pause = self.settings.think and self.can_skip_thinking()
353
+ off = ", with thinking off" if pause else ""
342
354
  self.console.print(
343
- Text(f" ⎿ {STALLED[self.reply_trouble]}: asking for a short answer{kept}", style="yellow")
355
+ Text(f" ⎿ {STALLED[self.reply_trouble]}: asking for a short answer{off}{kept}", style="yellow")
344
356
  )
345
- self.messages.append({"role": "user", "content": stall_note(self.reply_trouble)})
357
+ note = stall_note(self.reply_trouble, thinking_off=pause)
358
+ self.messages.append({"role": "user", "content": note})
346
359
  continue
347
- why = "its replies went round in circles or ended without an answer, twice in this request"
360
+ times = "twice in a row" if stalls >= MAX_STALLS else f"{stalled} times in this request"
361
+ why = f"its replies went round in circles or ended without an answer, {times}"
348
362
  if not escalated and self.can_escalate():
349
363
  escalated = True
350
364
  advice = self.ask_stronger(why)
@@ -355,12 +369,13 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
355
369
  self.turn_status = "loop"
356
370
  self.console.print(
357
371
  Text(
358
- "Stopped: the model's replies went round in circles or ended without an answer, twice in "
359
- f"this request{kept}. Try again with a smaller step, or tell it what to do differently.",
372
+ f"Stopped: the model's replies went round in circles or ended without an answer, {times}"
373
+ f"{kept}. Try again with a smaller step, or tell it what to do differently.",
360
374
  style="yellow",
361
375
  )
362
376
  )
363
377
  return
378
+ stalls = 0 # it acted or answered: a later reply that goes nowhere starts the count again
364
379
  if not calls:
365
380
  if self.reply_trouble == "cut_off":
366
381
  self.say(
@@ -383,6 +398,19 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
383
398
  )
384
399
  self.messages.append({"role": "user", "content": checks.unseen_note(unseen)})
385
400
  continue
401
+ untried = [] if untested_noted else self.untested_code(untested)
402
+ if untried:
403
+ untested_noted = True
404
+ it = "it" if len(untried) == 1 else "them"
405
+ self.console.print(
406
+ Text(
407
+ f" ⎿ never ran {', '.join(untried)} after writing {it}: asking the model to",
408
+ style="yellow",
409
+ )
410
+ )
411
+ note = checks.untested_note(untried, list(missing), checks.uv_available())
412
+ self.messages.append({"role": "user", "content": note})
413
+ continue
386
414
  check = self.project_check() if changed and not verified else None
387
415
  if check is not None and check_rounds < checks.MAX_ROUNDS:
388
416
  check_rounds += 1
@@ -436,6 +464,7 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
436
464
  began = time.monotonic()
437
465
  if self.trace is not None:
438
466
  self.trace.tool_begin()
467
+ self.tools.wrote = []
439
468
  try:
440
469
  result = done[i] if i in done else self.run_tool(name, args)
441
470
  except KeyboardInterrupt:
@@ -479,8 +508,16 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
479
508
  if out_of_reach.stop:
480
509
  blocked = out_of_reach
481
510
  tools_used.add(name)
511
+ for rel in self.tools.wrote:
512
+ if self.tools.before.get(rel, "") is None and checks.is_code(rel):
513
+ untested[rel] = None # new in this request: it should run before the model says it works
482
514
  if name == "bash":
483
- commands.append(str(args.get("command", "")))
515
+ command = str(args.get("command", ""))
516
+ commands.append(command)
517
+ if not result.startswith(REFUSED): # a command that wasn't allowed, or failed to start, ran nothing
518
+ for rel in checks.exercised(command, result, untested):
519
+ del untested[rel]
520
+ missing.update(dict.fromkeys(checks.not_found(result)))
484
521
  if name in ("edit_file", "write_file", "apply_patch") and not result.startswith(REFUSED):
485
522
  changed, verified = True, False
486
523
  elif name == "bash" and changed and self.model_ran_checks(str(args.get("command", "")), result):
lcode/agent_base.py CHANGED
@@ -18,6 +18,7 @@ from lcode import (
18
18
  extensions,
19
19
  repoid,
20
20
  repomap,
21
+ residency,
21
22
  subagents,
22
23
  traces,
23
24
  )
@@ -34,7 +35,6 @@ from lcode.tools import Toolbox
34
35
  from lcode.unreachable import NOTE_AT, Sites
35
36
 
36
37
  if TYPE_CHECKING:
37
- from lcode import residency
38
38
  from lcode.agent import Agent
39
39
  from lcode.agent_model import Progress
40
40
  from lcode.hardware import Hardware
@@ -196,6 +196,7 @@ class AgentBase:
196
196
  self.ctx_used = 0
197
197
  self._repo: tuple[Path, repoid.Repo | None] | None = None # the workspace's repository, for saved sessions
198
198
  self.last_speed = 0.0
199
+ self.reply_speeds = residency.SpeedWatch() # to say why, when replies get far slower (lcode.residency)
199
200
  self.usage = {"requests": 0, "prompt_tokens": 0, "prompt_ns": 0, "output_tokens": 0, "output_ns": 0}
200
201
  self.trace: traces.Lane | None = None # the request's trace while it's recorded (lcode.traces)
201
202
  self.replay: ReplayServer | None = None # in a replay: the recorded results of tools and checks (lcode.replay)
lcode/agent_checks.py CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from collections.abc import Iterable
6
+ from pathlib import Path
5
7
  from typing import TYPE_CHECKING, cast
6
8
 
7
9
  from lcode import (
@@ -77,6 +79,25 @@ class Checks(AgentBase):
77
79
  return []
78
80
  return checks.unrun_scripts(project_root_or_cwd(self.cwd), list(self.tools.before), commands)
79
81
 
82
+ def untested_code(self, written: Iterable[str]) -> list[str]:
83
+ """Code files the model wrote in this request and hasn't run since their last change (#242): only where the
84
+ checks would run, and when the project has no checks of its own (lcode runs those instead). Window code has
85
+ its own check: a screenshot shows it."""
86
+ if self.allowed_tools is not None or self.planning() or self.no_changes or self.settings.checks == "off":
87
+ return []
88
+ if self.project_check() is not None:
89
+ return []
90
+ root = project_root_or_cwd(self.cwd)
91
+ found = []
92
+ for rel in written:
93
+ path = root / rel
94
+ try:
95
+ if path.is_file() and not checks.GUI_IMPORT.search(path.read_text(errors="replace")):
96
+ found.append(rel)
97
+ except OSError:
98
+ continue
99
+ return found
100
+
80
101
  def unseen_windows(self, tools_used: set[str]) -> dict[str, str]:
81
102
  """Window code the model changed in this request and never looked at (only where the checks would run)."""
82
103
  if self.allowed_tools is not None or self.planning() or self.no_changes or self.settings.checks == "off":
@@ -95,17 +116,30 @@ class Checks(AgentBase):
95
116
  def model_ran_checks(self, command: str, result: str) -> bool:
96
117
  """Whether a command the model ran was the project's checks, and they passed."""
97
118
  check = self.project_check()
98
- if check is None or not checks.covers(check, command) or checks.exit_code(result) != 0:
119
+ if check is None or not checks.covers(check, command) or not checks.run_passed(check, command, result):
99
120
  return False
100
121
  self.check_results.append({"command": check.command, "exit_code": 0, "by": "model"})
101
122
  return True
102
123
 
124
+ def check_folder(self, check: checks.Check) -> Path:
125
+ """Where the checks run: the project's root, wherever the model's last `cd` left its shell. A command from the
126
+ user's own setting runs where they started lcode."""
127
+ return self.workspace if check.source == checks.YOUR_SETTING else project_root_or_cwd(self.cwd)
128
+
129
+ def files_changed(self) -> list[str]:
130
+ """The files this request changed, with the model's file tools or with its shell commands."""
131
+ return [*self.tools.before, *self.checkpoints.changed_so_far()]
132
+
103
133
  def run_check(self, check: checks.Check, round_: int) -> str | None:
104
134
  """Run the checks after a change. Returns what to tell the model when they fail, else None."""
105
135
  self.say(f"Checking the work: {check.command} (from {check.source})")
106
136
  result = self.replay.check_result(check.command) if self.replay is not None else None
107
137
  if result is None:
108
- result = self.tools.run("bash", {"command": check.command, "timeout": checks.TIMEOUT})
138
+ here, self.cwd = self.cwd, self.check_folder(check)
139
+ try:
140
+ result = self.tools.run("bash", {"command": check.command, "timeout": checks.TIMEOUT})
141
+ finally:
142
+ self.cwd = here
109
143
  code = checks.exit_code(result)
110
144
  if self.trace is not None:
111
145
  self.trace.check(check.command, result, code)
@@ -118,15 +152,34 @@ class Checks(AgentBase):
118
152
  return None
119
153
  if checks.no_tests(check, result):
120
154
  self.say(f"The checks found no tests to run ({check.command}).")
121
- return None
122
- if checks.missing(check, result):
155
+ elif checks.missing(check, result):
123
156
  self.say(
124
157
  f"The checks couldn't run ({check.command}): {result.splitlines()[0][:160]}. Install what they need, "
125
158
  'or set the command: lcode config set checks "…" (or checks off).',
126
159
  warning=True,
127
160
  )
128
- return None
129
- if round_ >= checks.MAX_ROUNDS:
161
+ elif checks.no_test_ran(check, result) and not checks.names_any(result, self.files_changed()):
162
+ self.say(
163
+ f"The checks stopped before running a test ({check.command}): {checks.stop_reason(result)} It doesn't "
164
+ "name a file this request changed, so the model isn't asked to fix it. To get checks that run, fix "
165
+ 'that or set the command: lcode config set checks "…" (or checks off).',
166
+ warning=True,
167
+ )
168
+ else:
169
+ return self.failed_check(check, result, code, round_)
170
+ self.check_results[-1]["exit_code"] = None # no test ran: whoever reads this later shouldn't read a failure
171
+ return None
172
+
173
+ def failed_check(self, check: checks.Check, result: str, code: int, round_: int) -> str:
174
+ """Say that the checks failed, or didn't finish; what to tell the model."""
175
+ if checks.timed_out(result):
176
+ self.check_results[-1]["exit_code"] = None
177
+ self.say(
178
+ f"The checks didn't finish in {checks.TIMEOUT} seconds and were stopped ({check.command}). To use a "
179
+ 'faster command: lcode config set checks "…" (or checks off).',
180
+ warning=True,
181
+ )
182
+ elif round_ >= checks.MAX_ROUNDS:
130
183
  then = "" if self.can_escalate() else ": the model will say what's left"
131
184
  self.say(f"Checks still fail ({check.command}, exit code {code}){then}.", warning=True)
132
185
  else:
lcode/agent_model.py CHANGED
@@ -214,13 +214,22 @@ class ModelCalls(AgentBase):
214
214
  ) from e
215
215
  raise
216
216
 
217
+ def can_skip_thinking(self) -> bool:
218
+ """Whether one reply can be asked for without thinking while thinking is on: Ollama's API has a switch for
219
+ it. Other servers take a chat template argument instead (vLLM, llama.cpp), which hosted APIs refuse, so
220
+ lcode doesn't send it unless thinking is off in the settings."""
221
+ return getattr(self.ollama, "kind", "ollama") == "ollama"
222
+
217
223
  def _opened(self, response) -> None:
218
224
  self.response = response
219
225
  if self.cancel is not None and self.cancel.is_set():
220
226
  subagents.abort(response)
221
227
 
222
- def assistant_step(self) -> dict:
223
- """Stream one model response, rendering thinking/content live. Returns the assistant message."""
228
+ def assistant_step(self, think: bool = True) -> dict:
229
+ """Stream one model response, rendering thinking/content live. Returns the assistant message.
230
+
231
+ `think=False` asks for this reply without thinking, even when thinking is on: after a reply that went
232
+ round in circles, so the model acts instead of starting the same deliberation over."""
224
233
  content, thinking, tool_calls, final = "", "", [], {}
225
234
  md = MarkdownStreamer(self.console)
226
235
  progress = Progress(steering=self.steering)
@@ -243,7 +252,7 @@ class ModelCalls(AgentBase):
243
252
  start_spinner()
244
253
  circles = Circles()
245
254
  self.reply_trouble = ""
246
- stream = self.chat(self.messages, self.tool_schemas(), self.settings.think)
255
+ stream = self.chat(self.messages, self.tool_schemas(), self.settings.think and think)
247
256
  try:
248
257
  for chunk in stream:
249
258
  if self.cancel is not None and self.cancel.is_set():
@@ -315,4 +324,20 @@ class ModelCalls(AgentBase):
315
324
  self.sent_chars = self.counted_chars = conversation_chars(self.messages)
316
325
  seconds = final.get("eval_duration", 0) / 1e9
317
326
  self.last_speed = final.get("eval_count", 0) / seconds if seconds else 0.0
327
+ self.explain_slowdown(final.get("eval_count", 0), seconds)
318
328
  return message
329
+
330
+ def explain_slowdown(self, tokens: int, seconds: float) -> None:
331
+ """When replies fall far below this session's earlier speed and RAM is short, say that's likely why, once."""
332
+ context, spec = self.settings.context, catalog.find(self.settings.model)
333
+ if spec is None or self.hardware is None or self.reply_speeds.explained:
334
+ return
335
+ slowed = self.reply_speeds.add(self.settings.model, context, tokens, seconds)
336
+ fit = residency.ram_fit(self.ollama, spec, context, self.hardware) if slowed else None
337
+ if slowed and fit and fit.short:
338
+ self.reply_speeds.explained = True
339
+ self.say(
340
+ f"Replies slowed from {slowed[0]:.0f} to {slowed[1]:.0f} tokens a second, most likely because RAM is "
341
+ f"short: {fit.describe()}. {fit.advice(residency.SESSION_COMMANDS)}",
342
+ warning=True,
343
+ )
lcode/api.py CHANGED
@@ -317,13 +317,18 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
317
317
 
318
318
  def close_agent(agent: Agent) -> None:
319
319
  """Stop what lcode started (background jobs, servers, the sandbox, ComfyUI), then say so: the terminal may be
320
- gone already (closed), and saying it then fails."""
320
+ gone already (closed), and saying it then fails. Kept jobs, services the user asked for, keep running."""
321
321
  from lcode import media
322
322
 
323
323
  said = []
324
324
  stopped = agent.jobs.stop_all()
325
325
  if stopped:
326
326
  said.append(f"Stopped {stopped} background job(s).")
327
+ for job in agent.jobs.kept():
328
+ said.append(
329
+ f"Left job {job.id} running, as asked: {job.command} (process group {job.proc.pid}: "
330
+ f"`kill -- -{job.proc.pid}` stops it; its output is in {job.log})"
331
+ )
327
332
  if media.stop_engine(agent):
328
333
  said.append("Stopped ComfyUI.")
329
334
  if agent.lsp is not None:
lcode/catalog.py CHANGED
@@ -16,6 +16,7 @@ else: # pragma: no cover
16
16
 
17
17
  OVERHEAD_GIB = 1.0 # compute buffers and runtime; measured <1 GiB for qwen3.6-35b and qwen3.5-9b on CUDA
18
18
  HEADROOM_GIB = 0.5 # keep a little memory free so estimates at the edge don't run out
19
+ OLLAMA_RAM_GIB = 10.0 # Ollama's server in a long session: its prompt cache (8 GiB by default) and 1-2 GiB of its own
19
20
  CONTEXT_STEPS = [1048576, 524288, 262144, 131072, 65536, 32768]
20
21
  MIN_USEFUL_CONTEXT = 32768
21
22
 
@@ -45,6 +46,15 @@ class ModelSpec:
45
46
  def memory_gib(self, context: int) -> float:
46
47
  return self.size_gb * 1e9 / GIB + self.kv_kib_per_token * 1024 * context / GIB + OVERHEAD_GIB
47
48
 
49
+ def in_ram_gib(self, context: int, hw: Hardware) -> float:
50
+ """The part of the model that doesn't fit in GPU memory and stays in system RAM. Ollama's /api/ps leaves out
51
+ an MoE model's: its experts stay mapped from the model's file, so they have to stay in the page cache."""
52
+ return max(0.0, self.memory_gib(context) - hw.vram_gib)
53
+
54
+ def ram_needed_gib(self, context: int, hw: Hardware) -> float:
55
+ """System RAM a long session needs: the part of the model outside GPU memory, and Ollama's prompt cache."""
56
+ return self.in_ram_gib(context, hw) + OLLAMA_RAM_GIB
57
+
48
58
  def best_context(self, budget_gib: float) -> int | None:
49
59
  """Largest standard context window whose estimated memory fits the budget."""
50
60
  for ctx in CONTEXT_STEPS:
lcode/checkpoints.py CHANGED
@@ -386,6 +386,18 @@ class Checkpoints:
386
386
  f"[dim]↶ Checkpoint {cp.n}: {count} file{'' if count == 1 else 's'} changed · /undo reverts them[/]"
387
387
  )
388
388
 
389
+ def changed_so_far(self) -> list[str]:
390
+ """The files changed so far in the running request, by shell commands too, without a nested repository's."""
391
+ cp = self._current
392
+ if cp is None:
393
+ return []
394
+ store = Store(Path(cp.worktree))
395
+ try:
396
+ changes = store.changes(cp.before, store.tree())
397
+ except CheckpointError:
398
+ return []
399
+ return [c["path"] for c in changes if not (store.worktree / c["path"]).is_dir()]
400
+
389
401
  def ref(self, n: int) -> str:
390
402
  return f"refs/lcode/{self.session_id}/{n}"
391
403
 
lcode/checks.py CHANGED
@@ -3,7 +3,8 @@
3
3
  Small models call work done after a syntax check, and telling them to verify isn't enough. So after a request
4
4
  that changed files, lcode runs the project's check command itself (its tests, or a linter) before the answer
5
5
  counts as final. When it fails, the output goes back to the model, which keeps working, at most `MAX_ROUNDS`
6
- times; then the answer says plainly that the checks still fail.
6
+ times; then the answer says plainly that the checks still fail. A run in which no test ran says nothing about the
7
+ change, so it only goes back to the model when its error names a file the request changed.
7
8
 
8
9
  The command is, in order: the repository's `.lcode/settings.toml` (`[checks] command = "…"`, used once the
9
10
  repository is trusted, like its hooks), the user's `checks` setting, or what the project looks like: pytest,
@@ -15,13 +16,17 @@ from __future__ import annotations
15
16
  import json
16
17
  import re
17
18
  import shutil
19
+ from collections.abc import Iterable
18
20
  from dataclasses import dataclass
19
21
  from pathlib import Path
20
22
 
23
+ from lcode.permissions import is_read_only
24
+
21
25
  MAX_ROUNDS = 2 # times the model gets failing checks back before lcode stops asking
22
26
  TIMEOUT = 600 # seconds a check may run
23
27
  OUTPUT_TAIL = 6000 # characters of a failing check's output the model gets back
24
28
  EXIT = re.compile(r"\[exit code: (-?\d+)\]\s*$")
29
+ YOUR_SETTING = "your configuration (checks)" # the source of a command from the user's own `checks` setting
25
30
 
26
31
 
27
32
  @dataclass
@@ -46,7 +51,7 @@ def find(root: Path, setting: str, trusted: bool) -> Check | None:
46
51
  if command:
47
52
  return Check(command, ".lcode/settings.toml")
48
53
  if setting != "auto":
49
- return Check(setting, "your configuration (checks)")
54
+ return Check(setting, YOUR_SETTING)
50
55
  return detect(root)
51
56
 
52
57
 
@@ -121,7 +126,9 @@ def detect(root: Path) -> Check | None:
121
126
  if list(root.glob("test_*.py")) or list(root.glob("*_test.py")):
122
127
  return Check(f"{py} -m unittest", "test files")
123
128
  if (root / "tests").is_dir():
124
- return Check(f"{py} -m unittest discover -s tests -t .", "tests/")
129
+ # `-t .` lets a package of tests use relative imports. Without __init__.py, it doesn't start at all.
130
+ top = " -t ." if (root / "tests" / "__init__.py").is_file() else ""
131
+ return Check(f"{py} -m unittest discover -s tests{top}", "tests/")
125
132
  package = text(root / "package.json")
126
133
  if package:
127
134
  try:
@@ -149,6 +156,51 @@ def no_tests(check: Check, result: str) -> bool:
149
156
  return exit_code(result) == NO_TESTS and bool(re.search(r"pytest|unittest", check.command))
150
157
 
151
158
 
159
+ PYTEST_STOPPED = (2, 3, 4) # pytest's exit codes for: interrupted (errors while collecting), internal error, bad usage
160
+ PYTEST_COUNTS = re.compile(r"\b\d+ (?:passed|failed)\b")
161
+ UNITTEST_COUNT = re.compile(r"^Ran \d+ tests? in ", re.M)
162
+ NOT_IMPORTED = re.compile(r"No module named '([\w.]+)'")
163
+
164
+
165
+ def no_test_ran(check: Check, result: str) -> bool:
166
+ """Whether the test runner stopped before its first test, so the run says nothing about the code.
167
+
168
+ pytest stops at an error while collecting. unittest ends in a traceback instead of `Ran N tests` when its discovery
169
+ fails; a test module that doesn't import is a failed test there (`Ran 1 test`), so that's not this.
170
+ """
171
+ code = exit_code(result)
172
+ if re.search(r"\bpytest\b", check.command):
173
+ return code in PYTEST_STOPPED and not PYTEST_COUNTS.search(result)
174
+ if re.search(r"\bunittest\b", check.command):
175
+ return code == 1 and "Traceback (most recent call last)" in result and not UNITTEST_COUNT.search(result)
176
+ return False
177
+
178
+
179
+ def names_any(result: str, files: Iterable[str]) -> bool:
180
+ """Whether a check's output points at one of these files: by its path, or as a module it can't find."""
181
+
182
+ def mentions(text: str, name: str) -> bool:
183
+ return re.search(rf"(?<![\w-]){re.escape(name)}(?![\w-])", text) is not None
184
+
185
+ modules = [module.replace(".", "/") for module in NOT_IMPORTED.findall(result)]
186
+ return any(mentions(result, rel) or any(mentions(rel, module) for module in modules) for rel in files)
187
+
188
+
189
+ REASON_LIMIT = 240 # Django's ImproperlyConfigured says what to set, in 224
190
+
191
+
192
+ def stop_reason(result: str) -> str:
193
+ """A sentence on why a test run stopped before its first test: pytest's first error, or a traceback's end."""
194
+ lines = [line.strip() for line in result.splitlines() if line.strip() and not line.startswith("[")]
195
+ reason = next((line[1:].strip() for line in lines if line.startswith("E ")), lines[-1] if lines else "no output")
196
+ return reason.rstrip(".") + "." if len(reason) <= REASON_LIMIT else reason[: REASON_LIMIT - 1] + "…"
197
+
198
+
199
+ def timed_out(result: str) -> bool:
200
+ """Whether lcode stopped the check at its time limit: it didn't fail, it didn't finish."""
201
+ return exit_code(result) == -9 and "\n[Command timed out after " in result
202
+
203
+
152
204
  def exit_code(result: str) -> int | None:
153
205
  """The exit code at the end of a bash tool result (None: it didn't run, e.g. not allowed)."""
154
206
  found = EXIT.search(result)
@@ -160,7 +212,31 @@ def covers(check: Check, command: str) -> bool:
160
212
  return " ".join(check.command.split()) in " ".join(command.split())
161
213
 
162
214
 
215
+ KEEPS_EXIT_CODE = re.compile(r"\d*>&\d+|&>>?|&&") # redirections and `&&`, after the check
216
+ HIDES_EXIT_CODE = re.compile(r"[|;&\n]") # a pipe, `||`, `;`, `&` or another line: the exit code isn't the check's
217
+ RUN_FAILED = re.compile(r"\b[1-9]\d* (?:failed|errors?)\b|^(?:FAILED|ERROR)\b", re.M)
218
+ RUN_PASSED = re.compile(r"\b[1-9]\d* passed\b|^OK\b", re.M)
219
+
220
+
221
+ def run_passed(check: Check, command: str, result: str) -> bool:
222
+ """Whether the model's own run of the check passed. `pytest -q | tail` exits with tail's 0 when tests fail, so when
223
+ the exit code isn't the check's, only the output can say: a test runner's summary, with nothing failing."""
224
+ if exit_code(result) != 0:
225
+ return False
226
+ found = re.search(r"\s+".join(map(re.escape, check.command.split())), command)
227
+ after = KEEPS_EXIT_CODE.sub(" ", command[found.end() :]).rstrip() if found else ""
228
+ if not HIDES_EXIT_CODE.search(after):
229
+ return True
230
+ return RUN_PASSED.search(result) is not None and RUN_FAILED.search(result) is None
231
+
232
+
163
233
  def failure_note(check: Check, result: str, round_: int) -> str:
234
+ if timed_out(result):
235
+ return (
236
+ f"[lcode] The project's checks (`{check.command}`) didn't finish in {TIMEOUT} seconds and were stopped, so "
237
+ "they don't say whether your changes work. If your change could make something hang, look at that. "
238
+ "Otherwise run the tests that cover your change, and say in your answer that the full checks didn't finish."
239
+ )
164
240
  output = result if len(result) <= OUTPUT_TAIL else "…" + result[-OUTPUT_TAIL:]
165
241
  last = round_ >= MAX_ROUNDS
166
242
  return (
@@ -260,6 +336,78 @@ def unrun_note(scripts: list[str]) -> str:
260
336
  )
261
337
 
262
338
 
339
+ # ----------------------------------------------------------------------------- code written, never run
340
+
341
+ # Not .sql: one can be a migration, and asking the model to run that could change a real database.
342
+ CODE_SUFFIXES = frozenset(
343
+ {".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".rs", ".go", ".c", ".cc", ".cpp", ".java", ".kt", ".rb",
344
+ ".php", ".pl", ".lua", ".jl", ".r", ".scala", ".swift", ".cs", ".sparql", ".rq"}
345
+ ) # fmt: skip
346
+ SPARQL_SUFFIXES = (".sparql", ".rq")
347
+ # Checks that read the code without running it (syntax, lint, types): they don't show that it works.
348
+ STATIC_ONLY = re.compile(
349
+ r"\bast\.parse\b|\bpy_compile\b|\bcompileall\b|(?:^|\s)-fsyntax-only\b|\b(?:node|deno)\s+(?:-c|--check)\b"
350
+ r"|\bphp\s+-l\b|\b(?:ruby|perl)\s+-c\b"
351
+ r"|\b(?:pyflakes|flake8|pylint|mypy|pyright|basedpyright|ruff|eslint|tsc)\b|\bcargo\s+check\b|\bgo\s+vet\b"
352
+ )
353
+ # A test runner runs the code it tests, whether or not the command names a file.
354
+ TEST_RUNNER = re.compile(
355
+ r"\b(?:pytest|py\.test|unittest|tox|nox|jest|vitest|mocha|ctest|phpunit|rspec)\b"
356
+ r"|\b(?:cargo|go|npm|pnpm|yarn|bun|deno|mvn|gradle|dotnet|swift|mix|make)\s+(?:run\s+)?test\b"
357
+ )
358
+ # The program, or a module the code needs, isn't installed: the code didn't run.
359
+ NOT_INSTALLED = re.compile(r"command not found|^\S+: not found$|No module named|Cannot find module", re.I | re.M)
360
+ NOT_FOUND = re.compile(r"(?:^|:\s)([\w.+-]+): (?:command )?not found\s*$", re.M)
361
+
362
+
363
+ def is_code(rel: str) -> bool:
364
+ """Whether a file is a program, module or query in a language that runs (shell scripts have their own check)."""
365
+ return Path(rel).suffix.lower() in CODE_SUFFIXES
366
+
367
+
368
+ def exercised(command: str, result: str, files: Iterable[str]) -> list[str]:
369
+ """The files among `files` that a shell command ran: it names them, or their module, or runs tests, and its
370
+ program was there. Syntax, lint and type checks, and commands that only look, don't count."""
371
+ if is_read_only(command) or STATIC_ONLY.search(command):
372
+ return []
373
+ if exit_code(result) == 127 or any(NOT_INSTALLED.search(line) for line in result.splitlines()[:20]):
374
+ return []
375
+ if TEST_RUNNER.search(command):
376
+ return list(files)
377
+ return [rel for rel in files if re.search(rf"(?<![\w-]){re.escape(Path(rel).stem)}(?![\w-])", command)]
378
+
379
+
380
+ def not_found(result: str) -> list[str]:
381
+ """The programs a shell command's output says aren't installed (`bash: line 1: python3: command not found`)."""
382
+ return list(dict.fromkeys(NOT_FOUND.findall(result)))
383
+
384
+
385
+ def uv_available() -> bool:
386
+ return shutil.which("uv") is not None
387
+
388
+
389
+ def untested_note(files: list[str], missing: list[str], uv: bool) -> str:
390
+ names = ", ".join(files)
391
+ it = "it" if len(files) == 1 else "them"
392
+ note = (
393
+ f"[lcode] You wrote {names} in this request but haven't run {it} since your last change. Run {it} now and fix "
394
+ f"what fails, so you know {it} works before you say so: for a module, import it and call what you wrote; "
395
+ "for a query, run it on its data; for a server or anything else that keeps running, start it in the "
396
+ "background and try it. A syntax check doesn't show that it works."
397
+ )
398
+ if missing:
399
+ note += f" {', '.join(f'`{m}`' for m in missing)} isn't installed here."
400
+ sparql = any(f.lower().endswith(SPARQL_SUFFIXES) for f in files)
401
+ if uv and (sparql or any(f.endswith(".py") for f in files)):
402
+ note += (
403
+ " To run Python code without changing this machine's Python, `uv run --with PACKAGE python FILE` fetches "
404
+ "Python and the packages it needs into a throwaway environment."
405
+ )
406
+ if sparql:
407
+ note += " For a SPARQL query, the package is `rdflib`."
408
+ return note + f" If you can't run {it}, say plainly in your answer that {it} is untested, and why."
409
+
410
+
263
411
  # ----------------------------------------------------------------------------- windows it never looked at
264
412
 
265
413
  GUI_IMPORT = re.compile(r"^\s*(?:from|import)\s+(PyQt[56]|PySide[26]|tkinter|kivy|wx|gi\.repository)\b", re.M)
lcode/cli.py CHANGED
@@ -26,7 +26,7 @@ from rich.progress import (
26
26
  from rich.prompt import Confirm
27
27
  from rich.table import Table
28
28
 
29
- from lcode import backends, catalog, config, limits
29
+ from lcode import backends, catalog, config, limits, residency
30
30
  from lcode.agent import Settings
31
31
  from lcode.catalog import ModelSpec
32
32
  from lcode.cli_args import build_parser, build_subparsers
@@ -313,6 +313,9 @@ def cmd_setup(args) -> None:
313
313
  )
314
314
  if spec.memory_gib(ctx) > hw.budget_gib:
315
315
  console.print("[yellow]warning:[/] this probably doesn't fit in memory; pick a smaller --context or model.")
316
+ elif (fit := residency.ram_fit(ollama, spec, ctx, hw)) and fit.short:
317
+ commands = (f"lcode setup {spec.key} --context {{}}", "lcode setup {}", "lcode models")
318
+ console.print(f"[yellow]warning:[/] RAM is short: {fit.describe()}. {fit.why()} {fit.advice(commands)}")
316
319
  if not spec.tested:
317
320
  console.print(
318
321
  "[yellow]note:[/] this model hasn't been verified with lcode yet — please report how it goes."
lcode/docs/automation.md CHANGED
@@ -56,7 +56,7 @@ went: `0` success, `1` an error, `3` stopped at `--max-steps`, `4` stopped becau
56
56
  | `files_changed` | Files the request added (`A`), modified (`M`) or deleted (`D`), shell commands included |
57
57
  | `usage` | Model requests and tokens; `prompt_tokens` includes tokens served from the prompt cache |
58
58
  | `review` | What the [review](usage.md#a-review-before-the-answer) sent back to the model (`[]` when it found nothing; `null` when no review ran) |
59
- | `checks` | The [checks](usage.md#checks-before-done) that ran after the change: `command`, `exit_code` (`null` when they weren't allowed to run) and `by` (`lcode`, or `model` when the model ran them itself) |
59
+ | `checks` | The [checks](usage.md#checks-before-done) that ran after the change: `command`, `exit_code` (`null` when they say nothing about the change: they weren't allowed to run, no test ran, or they didn't finish) and `by` (`lcode`, or `model` when the model ran them itself) |
60
60
  | `error` | What went wrong, when `status` is `error` |
61
61
  | `session_id` | Continue the conversation later with `lcode --resume <id>` |
62
62