loopmath 0.3.4__py3-none-any.whl → 0.3.5__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.
loopmath/__init__.py CHANGED
@@ -5,4 +5,4 @@ The command line (`loopmath`, or its alias `loop`) is the interface; see the
5
5
  README and `loopmath --help`.
6
6
  """
7
7
 
8
- __version__ = "0.3.4"
8
+ __version__ = "0.3.5"
loopmath/cli.py CHANGED
@@ -14,9 +14,11 @@ Verbs:
14
14
  plan: task-types workflows recommend builder plan
15
15
  record: run start|record|import|attempt|artifact|finish|sessions outcome budget config
16
16
  learn: fit onboard share
17
- view: runs posterior status report doctor guide skill ocp
17
+ view: runs posterior status report doctor guide skill update ocp
18
18
 
19
- No verb in this CLI connects to another machine; builder serves on 127.0.0.1 only.
19
+ No verb in this CLI connects to another machine, except the daily update check (update.py): once a
20
+ day, after any command, loopmath asks pypi.org for its latest version, sending only its own
21
+ (LOOPMATH_NO_UPDATE_CHECK=1 or CI turns it off). builder serves on 127.0.0.1 only.
20
22
  Verbs write only to the store ($LOOPMATH_HOME, default ~/.loopmath, which also
21
23
  holds the parse cache and the fit --full compile folder), to the skill folders
22
24
  skill install names, and to paths the user names.
@@ -550,9 +552,23 @@ def _add_verify_receipts(sub) -> None:
550
552
 
551
553
 
552
554
  def main(argv: list[str] | None = None) -> int:
553
- from .cli_errors import JsonErrorParser, run_guarded, wants_json
555
+ """Run one command, then the daily update check (update.py), which never changes the exit code or stdout.
556
+ A command that ends in an exception other than SystemExit, or in Ctrl-C, skips the check."""
557
+ from .update import after_command
554
558
 
555
559
  raw_args = sys.argv[1:] if argv is None else argv
560
+ try:
561
+ code = _main(raw_args)
562
+ except SystemExit: # --help, --version and usage errors too
563
+ after_command(raw_args)
564
+ raise
565
+ after_command(raw_args)
566
+ return code
567
+
568
+
569
+ def _main(raw_args: list[str]) -> int:
570
+ from .cli_errors import JsonErrorParser, run_guarded, wants_json
571
+
556
572
  JsonErrorParser.json_mode = wants_json(raw_args) # under --json a usage error is a JSON object on stdout too
557
573
  JsonErrorParser.argv = list(raw_args)
558
574
  parser = JsonErrorParser(
loopmath/cli_registry.py CHANGED
@@ -639,6 +639,13 @@ def _add_viewing(sub) -> None:
639
639
  help="onboard, import, plan, record, fit or reference (default: list them, with when to use each)")
640
640
  p.set_defaults(func=_lazy("loopmath.skill.guide:command"))
641
641
 
642
+ p = sub.add_parser("update", help="is a newer loopmath out? the installed and latest versions and the upgrade "
643
+ "command; never upgrades")
644
+ p.add_argument("--refresh", action="store_true", help="ask pypi.org now, instead of reusing the last answer "
645
+ "(kept for 24 h, a failed check for 6 h)")
646
+ _common(p)
647
+ p.set_defaults(func=_lazy("loopmath.update:command"))
648
+
642
649
  p = sub.add_parser("skill", help="install, remove or print the loopmath skill")
643
650
  ss = p.add_subparsers(dest="skill_command", required=True)
644
651
  for verb, helptext in (("install", "write the loopmath skill for Claude Code, Codex or both, and remove the job "
loopmath/prices.toml CHANGED
@@ -143,15 +143,20 @@ source = "OpenCode 1.17.11 model catalog, opencode free route"
143
143
 
144
144
  # ---------------------------------------------------------------------------
145
145
  # Rows checked on the provider pages on 2026-09-23; gpt-6.1-sol added and
146
- # gpt-6-luna checked again on 2026-10-12 (no newer luna is listed). as_of
147
- # stays the copied table's date: a row with no "checked" date takes it as
148
- # the date of its tariff, and those rows were not read again.
146
+ # gpt-6-luna checked again on 2026-10-12 (no newer luna is listed);
147
+ # claude-sonnet-5-5 and claude-haiku-5-5 confirmed and gpt-6.1-terra added
148
+ # on 2026-11-03. as_of stays the copied table's date: a row with no
149
+ # "checked" date takes it as the date of its tariff, and those rows were
150
+ # not read again.
149
151
  # Each source names its page and the date it was read; the tariff record
150
152
  # written with every priced attempt takes its date from "checked YYYY-MM-DD".
151
153
  #
152
154
  # Anthropic (https://platform.claude.com/docs/en/about-claude/pricing): cache_write is the 1-hour write rate (2x input), as
153
155
  # for the rows above. Claude Code writes the 1-hour cache: 64.2M of 64.2M
154
156
  # cache-write tokens in 200 recent sessions on the build machine were 1h.
157
+ # Claude Haiku 5.5 is priced by prompt length: its row is the tier for
158
+ # prompts up to 100,000 input tokens, a longer prompt bills 5x those rates
159
+ # and is priced at the same rate here, so a Haiku 5.5 figure is a floor.
155
160
  # OpenAI (https://developers.openai.com/api/docs/pricing and each model's
156
161
  # page): GPT-6 bills cache writes (1.25x input), but Codex reported 0
157
162
  # cache-write tokens in all 91 recent GPT-6 sessions on the build machine,
@@ -168,6 +173,20 @@ cache_write = 8.00
168
173
  output = 20.00
169
174
  source = "official list, https://platform.claude.com/docs/en/about-claude/pricing, checked 2026-09-23: Claude Opus 5.5 at $4 input, $8 1h cache write, $0.20 cache read (0.05x input), $20 output; cache_write is the 1h rate"
170
175
 
176
+ ["claude-sonnet-5-5"]
177
+ input = 2.00
178
+ cache_read = 0.10
179
+ cache_write = 4.00
180
+ output = 10.00
181
+ source = "official list, https://platform.claude.com/docs/en/about-claude/pricing, checked 2026-11-03: Claude Sonnet 5.5 at $2 input, $4 1h cache write, $0.10 cache read (0.05x input), $10 output; cache_write is the 1h rate"
182
+
183
+ ["claude-haiku-5-5"]
184
+ input = 0.10
185
+ cache_read = 0.01
186
+ cache_write = 0.20
187
+ output = 0.50
188
+ source = "official list, https://platform.claude.com/docs/en/about-claude/pricing, checked 2026-11-03: Claude Haiku 5.5 at $0.10 input, $0.20 1h cache write, $0.01 cache read, $0.50 output for prompts up to 100,000 tokens; prompts over 100,000 tokens bill $0.50 input, $1 1h cache write, $0.05 cache read, $2.50 output and are priced at this rate (a floor); cache_write is the 1h rate"
189
+
171
190
  ["gpt-6-astra"]
172
191
  input = 10.00
173
192
  cache_read = 1.00
@@ -189,6 +208,13 @@ cache_write = 2.50
189
208
  output = 10.00
190
209
  source = "official list, https://developers.openai.com/api/docs/models/gpt-6.1-sol, checked 2026-10-12: standard tier, $2 input, $0.10 cached input, $2.50 cache write, $10 output; prompts over 272K input tokens bill more and are priced at this rate (a floor)"
191
210
 
211
+ ["gpt-6.1-terra"]
212
+ input = 1.00
213
+ cache_read = 0.05
214
+ cache_write = 1.25
215
+ output = 5.00
216
+ source = "official list, https://developers.openai.com/api/docs/models/gpt-6.1-terra, checked 2026-11-03: standard tier, $1 input, $0.05 cached input, $1.25 cache write (30-minute retention; 12-hour retention is $2.50), $5 output; prompts over 272K input tokens bill more and are priced at this rate (a floor)"
217
+
192
218
  ["gpt-6-luna"]
193
219
  input = 0.10
194
220
  cache_read = 0.01
loopmath/skill/doctor.py CHANGED
@@ -6,10 +6,11 @@ Six checks, each `ok`, `warn` or `fail`:
6
6
  store the store root exists and is writable
7
7
  fit `fits/latest` present, and its age
8
8
  prices every model seen in the scan window has a price
9
- skill where the loopmath skill is installed (and which Codex form), whether it is current, and the
10
- job skills 0.3.3 and older installed that are still on disk
9
+ skill where the loopmath skill is installed (and which Codex form), whether it is the one this
10
+ loopmath writes, and the job skills 0.3.3 and older installed that are still on disk
11
11
 
12
- Nothing here opens a network connection. Log files are read through the
12
+ Nothing here opens a network connection (the daily update check runs after the command, from
13
+ cli.main). Log files are read through the
13
14
  parse cache, which doctor keeps up to date in the store's cache folder (the
14
15
  report's `cache` says where and how large); it writes nothing else there, and
15
16
  creates the store folder only when it is missing. Codex auth files are never
@@ -29,6 +30,7 @@ from collections import Counter
29
30
  from pathlib import Path
30
31
  from typing import Callable, Mapping
31
32
 
33
+ from .. import __version__
32
34
  from ..belief.design import other_design
33
35
  from . import install as _install
34
36
 
@@ -218,7 +220,8 @@ def check_skill(cwd: Path | None, env: Mapping[str, str] | None) -> dict:
218
220
  elif p["missing"]:
219
221
  problems.append(f"{where} lacks the loopmath skill: run `{_install_cmd(p)}`")
220
222
  elif not p["current"]:
221
- problems.append(f"{where} is older than this loopmath: run `{_install_cmd(p)}`")
223
+ problems.append(f"{where} has a loopmath skill that differs from the one loopmath {__version__} writes: "
224
+ f"run `{_install_cmd(p)}`")
222
225
  if retired["owned"]:
223
226
  problems.append(f"{where} still has the job skills 0.3.3 and older installed "
224
227
  f"({_folders(retired['owned'])}): run `{_install_cmd(p)}` to remove them")
@@ -35,7 +35,7 @@ Workflow shapes (`--workflow`): `solo`, `best_of_n`, `plan_implement`, `implemen
35
35
  ## Commands
36
36
 
37
37
  ### Status
38
- `loopmath status --json`. Read `exists` (the store exists), `fit.latest` (fit id or null), `fit.usable` (false with no fit, or with a fit an older loopmath made: refit), `fit.problem` (why not, or null), `fit.running`, `counts.runs`, `open_runs[]` (`run`, `type`, `repo`, `started_at`, `slate`), `budget.cap_usd`, `budget.spent.usd`.
38
+ `loopmath status --json`. Read `exists` (the store exists), `fit.latest` (fit id or null), `fit.usable` (false with no fit, or with a fit an older loopmath made: refit), `fit.problem` (why not, or null), `fit.running`, `counts.runs`, `open_runs[]` (`run`, `type`, `repo`, `started_at`, `slate`), `budget.cap_usd`, `budget.spent.usd`, `update` (null when the update check is off or pypi.org has not answered yet; else `latest`, `installed`, `available` (true when a newer loopmath is out), `command` (the upgrade command: offer it when a newer loopmath is out, and run it only if the user agrees), `checked_at` (when loopmath last asked pypi.org)).
39
39
 
40
40
  ### Onboard
41
41
  - `loopmath onboard --dry-run --json`: reads the history, writes nothing. Read `prior.line` (the starting prior, in one line: show it once), `groups.total`, `groups.to_label`, `window.from`, `window.to`, `sessions`, `cost_in_logs.usd`, `labeler.chosen`, `labeler.spec`, `labeler.expected.usd`, `labeler.options[]` (`spec`, `title`, `expected.usd`): one entry per labeller this machine can run, plus `none`.
@@ -30,7 +30,7 @@ Do not run loopmath commands with `--help`: the help text is written for people
30
30
 
31
31
  ## What to do first
32
32
 
33
- 1. Run `loopmath status --json`. If `loopmath` is not found, tell the user to install it with `uv tool install --python 3.12 loopmath`, and stop.
33
+ 1. Run `loopmath status --json`. If `loopmath` is not found, tell the user to install it with `uv tool install --python 3.12 loopmath`, and stop. If status shows update.available, tell the user in one line and offer the update.command; run it only if they agree.
34
34
  2. Pick the guide from what the user asked for:
35
35
 
36
36
  | When | Run and follow |
@@ -1576,6 +1576,7 @@ def config_unset(args: argparse.Namespace) -> int:
1576
1576
  # ================================================================ status, report
1577
1577
  @handler("status")
1578
1578
  def status(args: argparse.Namespace) -> int:
1579
+ from ..update import status_object
1579
1580
  from .status import status_payload, status_lines
1580
1581
 
1581
1582
  store = _store(args)
@@ -1583,6 +1584,7 @@ def status(args: argparse.Namespace) -> int:
1583
1584
  payload = status_payload(store)
1584
1585
  if reindexed is not None:
1585
1586
  payload["reindex"] = reindexed
1587
+ payload["update"] = status_object() # the daily check, here so the first status of the day has it
1586
1588
  return _out(args, "status", payload, status_lines(payload))
1587
1589
 
1588
1590
 
loopmath/update.py ADDED
@@ -0,0 +1,299 @@
1
+ """The daily update check (0.3.5): is a newer loopmath on PyPI?
2
+
3
+ `cli.main` calls `after_command` once a command has finished. At most once a day it asks
4
+ pypi.org for loopmath's latest version: one GET of `URL` with `loopmath/<version>` as the
5
+ User-Agent, nothing else sent, `TIMEOUT_S` to answer. What it heard goes to `update.json` in the
6
+ store's cache folder (`ingest.cache_dir()`, so LOOPMATH_CACHE_DIR wins): `checked_at`, `latest`
7
+ (the last version pypi.org gave) and `error` (why the last ask failed, or null). An answer is
8
+ reused for 24 h and a failure for 6 h, so an offline machine waits out the timeout at most four
9
+ times a day. When a newer version is known and stderr is a terminal, one line on stderr says so,
10
+ with the upgrade command. Nothing here writes to stdout, and no error here changes a command's
11
+ output or exit code.
12
+
13
+ loopmath never upgrades itself: `loopmath update` and `status --json` (`update`) give the command,
14
+ and the user, or their agent once the user agrees, runs it. The check is off when
15
+ LOOPMATH_NO_UPDATE_CHECK is set to anything but empty, or when CI is set; `loopmath update`, which
16
+ the user asks for by name, still asks.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ import re
25
+ import shlex
26
+ import sys
27
+ import tempfile
28
+ import threading
29
+ import time
30
+ from datetime import datetime, timezone
31
+ from pathlib import Path
32
+ from typing import Any, Mapping
33
+
34
+ from . import __version__
35
+
36
+ URL = "https://pypi.org/pypi/loopmath/json"
37
+ TIMEOUT_S = 2.0
38
+ OK_TTL_S = 24 * 3600
39
+ FAIL_TTL_S = 6 * 3600
40
+ CACHE_NAME = "update.json"
41
+ MAX_BYTES = 8 << 20 # the JSON lists every release's files; far below this
42
+ CHANGES_URL = "https://github.com/loopmath/loopmath/blob/v{version}/CHANGELOG.md"
43
+ THEN = "loopmath skill install"
44
+ SCHEMA = "loopmath.update/1"
45
+
46
+ # PEP 440, as the `packaging` library spells it (loopmath does not depend on packaging).
47
+ _PEP440 = re.compile(r"""
48
+ v?
49
+ (?:(?P<epoch>[0-9]+)!)?
50
+ (?P<release>[0-9]+(?:\.[0-9]+)*)
51
+ (?P<pre>[-_.]?(?P<pre_l>alpha|a|beta|b|preview|pre|c|rc)[-_.]?(?P<pre_n>[0-9]+)?)?
52
+ (?P<post>(?:-(?P<post_n1>[0-9]+))|(?:[-_.]?(?P<post_l>post|rev|r)[-_.]?(?P<post_n2>[0-9]+)?))?
53
+ (?P<dev>[-_.]?(?P<dev_l>dev)[-_.]?(?P<dev_n>[0-9]+)?)?
54
+ (?:\+(?P<local>[a-z0-9]+(?:[-_.][a-z0-9]+)*))?
55
+ """, re.VERBOSE | re.IGNORECASE)
56
+ _PRE_RANK = {"a": 0, "alpha": 0, "b": 1, "beta": 1, "c": 2, "rc": 2, "pre": 2, "preview": 2}
57
+
58
+
59
+ def version_key(text: Any) -> tuple | None:
60
+ """A sort key in PEP 440 order (a local label is ignored), or None for a string that is not a version."""
61
+ m = _PEP440.fullmatch(text.strip()) if isinstance(text, str) else None
62
+ if m is None:
63
+ return None
64
+ release = tuple(int(part) for part in m["release"].split("."))
65
+ while len(release) > 1 and release[-1] == 0:
66
+ release = release[:-1]
67
+ if m["pre_l"]:
68
+ pre: tuple = (1, _PRE_RANK[m["pre_l"].lower()], int(m["pre_n"] or 0))
69
+ else:
70
+ pre = (0,) if m["dev"] and not m["post"] else (2,) # 1.0.dev1 sorts before 1.0a1
71
+ post = (1, int(m["post_n1"] or m["post_n2"] or 0)) if m["post"] else (0,)
72
+ dev = (0, int(m["dev_n"] or 0)) if m["dev"] else (1,)
73
+ return int(m["epoch"] or 0), release, pre, post, dev
74
+
75
+
76
+ def is_prerelease(text: str) -> bool:
77
+ m = _PEP440.fullmatch(text.strip())
78
+ return bool(m and (m["pre_l"] or m["dev"]))
79
+
80
+
81
+ def newer(latest: Any, installed: str = __version__) -> bool:
82
+ """True when `latest` is a later version than `installed`. A pre-release counts only when
83
+ `installed` is one too."""
84
+ a, b = version_key(latest), version_key(installed)
85
+ if a is None or b is None:
86
+ return False
87
+ if is_prerelease(latest) and not is_prerelease(installed):
88
+ return False
89
+ return a > b
90
+
91
+
92
+ def enabled(env: Mapping[str, str] | None = None) -> bool:
93
+ env = os.environ if env is None else env
94
+ return not env.get("LOOPMATH_NO_UPDATE_CHECK") and "CI" not in env
95
+
96
+
97
+ def cache_path() -> Path:
98
+ from .ingest.base import cache_dir
99
+
100
+ return cache_dir() / CACHE_NAME
101
+
102
+
103
+ def fetch(timeout: float = TIMEOUT_S) -> str:
104
+ """The latest version on pypi.org (`info.version`). Raises on any failure."""
105
+ import urllib.request
106
+
107
+ request = urllib.request.Request(URL, headers={"User-Agent": f"loopmath/{__version__}"})
108
+ with urllib.request.urlopen(request, timeout=timeout) as response:
109
+ data = json.loads(response.read(MAX_BYTES))
110
+ version = data.get("info", {}).get("version") if isinstance(data, dict) else None
111
+ if version_key(version) is None:
112
+ raise ValueError(f"pypi.org gave no version loopmath can read: {version!r}")
113
+ return version
114
+
115
+
116
+ def _ask(timeout: float) -> tuple[str | None, str | None]:
117
+ """(latest, None) or (None, why), within `timeout` in all: urlopen's own timeout does not
118
+ cover the name lookup, so the request runs in a thread that is left behind if it is late."""
119
+ box: dict[str, str] = {}
120
+
121
+ def run() -> None:
122
+ try:
123
+ box["latest"] = fetch(timeout)
124
+ except BaseException as exc: # noqa: BLE001 - every failure is a failed check
125
+ box["error"] = (f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__)[:300]
126
+
127
+ worker = threading.Thread(target=run, name="loopmath-update-check", daemon=True)
128
+ worker.start()
129
+ worker.join(timeout)
130
+ if worker.is_alive():
131
+ return None, f"no answer from pypi.org within {timeout:g} s"
132
+ return box.get("latest"), box.get("error")
133
+
134
+
135
+ def _iso(at: float) -> str:
136
+ return datetime.fromtimestamp(int(at), timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
137
+
138
+
139
+ def _instant(value: Any) -> float | None:
140
+ try:
141
+ return datetime.fromisoformat(value).timestamp() if isinstance(value, str) else None
142
+ except ValueError:
143
+ return None
144
+
145
+
146
+ def read_cache(path: Path) -> dict | None:
147
+ try:
148
+ data = json.loads(path.read_text(encoding="utf-8"))
149
+ except (OSError, ValueError):
150
+ return None
151
+ if not isinstance(data, dict) or _instant(data.get("checked_at")) is None:
152
+ return None
153
+ latest = data.get("latest")
154
+ return {"checked_at": data["checked_at"], "latest": latest if version_key(latest) else None,
155
+ "error": data.get("error") if isinstance(data.get("error"), str) else None}
156
+
157
+
158
+ def fresh(state: dict, now: float) -> bool:
159
+ """An answer is good for 24 h and a failure for 6 h; a time ahead of the clock is not trusted."""
160
+ age = now - (_instant(state.get("checked_at")) or float("-inf"))
161
+ return 0 <= age < (FAIL_TTL_S if state.get("error") else OK_TTL_S)
162
+
163
+
164
+ def _write(path: Path, state: dict) -> None:
165
+ """Temp file beside `path`, then rename over it."""
166
+ fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent))
167
+ try:
168
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
169
+ json.dump(state, fh, indent=1)
170
+ fh.write("\n")
171
+ os.replace(tmp, path)
172
+ except BaseException:
173
+ Path(tmp).unlink(missing_ok=True)
174
+ raise
175
+
176
+
177
+ def check(*, refresh: bool = False, now: float | None = None, path: Path | None = None) -> dict:
178
+ """What loopmath knows of the latest version: `checked_at`, `latest`, `error`, and `cached` (true
179
+ when read from `update.json` without asking). Asks pypi.org only when the cache is stale or
180
+ `refresh` is set, and never when the cache folder cannot be written: an unwritable folder would
181
+ otherwise mean a request on every command."""
182
+ now = time.time() if now is None else now
183
+ path = cache_path() if path is None else path
184
+ old = read_cache(path)
185
+ if old is not None and not refresh and fresh(old, now):
186
+ return {**old, "cached": True}
187
+ try:
188
+ path.parent.mkdir(parents=True, exist_ok=True)
189
+ writable = os.access(path.parent, os.W_OK)
190
+ except OSError:
191
+ writable = False
192
+ if not writable:
193
+ return {**(old or {"checked_at": None, "latest": None}), "error": f"cannot write {path}", "cached": False}
194
+ latest, error = _ask(TIMEOUT_S)
195
+ state = {"checked_at": _iso(now), "latest": latest or (old or {}).get("latest"), "error": error}
196
+ try:
197
+ _write(path, state)
198
+ except OSError:
199
+ pass # the answer stands; the next command asks again
200
+ return {**state, "cached": False}
201
+
202
+
203
+ def installer(prefix: str | None = None) -> str:
204
+ """How this loopmath was installed: `uv` (uv tool), `pipx`, or `pip` (anything else)."""
205
+ root = Path(sys.prefix if prefix is None else prefix)
206
+ if (root / "uv-receipt.toml").is_file():
207
+ return "uv"
208
+ if (root / "pipx_metadata.json").is_file():
209
+ return "pipx"
210
+ return "pip"
211
+
212
+
213
+ def upgrade_command(kind: str | None = None) -> str:
214
+ kind = installer() if kind is None else kind
215
+ if kind == "uv":
216
+ return "uv tool upgrade loopmath"
217
+ if kind == "pipx":
218
+ return "pipx upgrade loopmath"
219
+ return f"{shlex.quote(sys.executable)} -m pip install -U loopmath"
220
+
221
+
222
+ def details(state: dict, kind: str | None = None) -> dict:
223
+ """`state` for people and agents: the versions, whether an upgrade is available, and its commands."""
224
+ kind = installer() if kind is None else kind
225
+ upgrade = upgrade_command(kind)
226
+ latest = state.get("latest")
227
+ return {"latest": latest, "installed": __version__, "available": newer(latest),
228
+ "command": f"{upgrade} && {THEN}", "checked_at": state.get("checked_at"),
229
+ "installer": kind, "upgrade": upgrade, "then": THEN,
230
+ "changes": CHANGES_URL.format(version=latest) if latest else None}
231
+
232
+
233
+ def status_object() -> dict | None:
234
+ """`status --json`'s `update`: null when the check is off or pypi.org has never answered."""
235
+ if not enabled():
236
+ return None
237
+ try:
238
+ info = details(check())
239
+ except Exception: # noqa: BLE001 - the check never fails a command
240
+ return None
241
+ if info["latest"] is None:
242
+ return None
243
+ return {k: info[k] for k in ("latest", "installed", "available", "command", "checked_at")}
244
+
245
+
246
+ def notice(info: dict) -> str | None:
247
+ if not info.get("available"):
248
+ return None
249
+ return f"loopmath {info['latest']} is out (you have {info['installed']}): {info['upgrade']}, then {THEN}"
250
+
251
+
252
+ def _command_word(argv: list[str]) -> str | None:
253
+ return next((a for a in argv if not a.startswith("-")), None)
254
+
255
+
256
+ def after_command(argv: list[str], stream=None) -> None:
257
+ """After a command (`cli.main`): the daily check, then one line on stderr when a newer
258
+ loopmath is out and stderr is a terminal. Silent on any error, Ctrl-C included."""
259
+ try:
260
+ if not enabled() or _command_word(argv) == "update": # `update` has just said it all
261
+ return
262
+ line = notice(details(check()))
263
+ stream = sys.stderr if stream is None else stream
264
+ if line and stream.isatty():
265
+ print(line, file=stream)
266
+ except (Exception, KeyboardInterrupt): # noqa: BLE001
267
+ pass
268
+
269
+
270
+ def command(args: argparse.Namespace) -> int:
271
+ """`loopmath update [--refresh] [--json]`: the installed and latest versions and the upgrade
272
+ commands. It never upgrades. Exit 0 when the check worked (up to date, or a newer one shown),
273
+ 1 when it failed."""
274
+ from .output import emit_json, fmt_time
275
+
276
+ state = check(refresh=args.refresh)
277
+ info = details(state)
278
+ error = state.get("error") or (None if info["latest"] else "pypi.org gave no version")
279
+ if args.json:
280
+ emit_json(SCHEMA, {"ok": error is None, **info, "cached": state["cached"], "error": error,
281
+ **({"exit": 1} if error else {})})
282
+ return 1 if error else 0
283
+ if error:
284
+ when = f" (at {fmt_time(state['checked_at'])}; `loopmath update --refresh` asks again)" if state["cached"] else ""
285
+ print(f"error: could not get the latest version from pypi.org: {error}{when}", file=sys.stderr)
286
+ return 1
287
+ checked = f"pypi.org, checked {fmt_time(state['checked_at'])}"
288
+ if not info["available"]:
289
+ if version_key(__version__) > version_key(info["latest"]): # a build from source, or a pre-release
290
+ print(f"loopmath {__version__} is newer than the latest on pypi.org, {info['latest']} ({checked})")
291
+ else:
292
+ print(f"loopmath {__version__} is the latest ({checked})")
293
+ return 0
294
+ print(f"loopmath {info['latest']} is out (you have {__version__}; {checked})")
295
+ print(f"what changed: {info['changes']}")
296
+ print(f"upgrade: {info['upgrade']}")
297
+ print(f"then: {THEN}")
298
+ print("loopmath never upgrades itself; run these yourself, or have your agent run them")
299
+ return 0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: loopmath
3
- Version: 0.3.4
3
+ Version: 0.3.5
4
4
  Summary: Plan agent workflows, record how they went, and learn from your own Claude Code and Codex logs
5
5
  Author: loopmath
6
6
  License-Expression: MIT
@@ -42,7 +42,7 @@ loopmath helps an orchestrator agent choose how to run a coding task, and learns
42
42
 
43
43
  Before a task, it predicts how the user's usual agent workflow will do: the chance of an accepted result, and the cost in tokens and dollars. It shows the other workflows on a success-cost curve and offers two exploration picks. Each pick comes with its gain on every future similar run, its one-time price, and the number of runs it takes to pay back. After the task, the orchestrator records what ran and what came of it. loopmath fills in the token costs from the Claude Code and Codex logs, writes a receipt of predicted against actual, and refits.
44
44
 
45
- loopmath never starts or coordinates agents. Claude Code, Codex, herdr or your own tool does that; loopmath is a CLI they call. Everything runs locally. loopmath connects to no other machine: `loopmath builder` serves its page on 127.0.0.1 only, and no other command opens a network connection. The logs are opened read only, and loopmath writes only to its store (`~/.loopmath`, which holds its caches too), to the skill folders `skill install` names, and to paths you name.
45
+ loopmath never starts or coordinates agents. Claude Code, Codex, herdr or your own tool does that; loopmath is a CLI they call. Everything runs locally. loopmath connects to no other machine but pypi.org: `loopmath builder` serves its page on 127.0.0.1 only, and no other command opens a network connection, except the daily update check. Once a day loopmath asks pypi.org whether a newer loopmath exists; it sends only its version and uploads nothing. `LOOPMATH_NO_UPDATE_CHECK=1` turns the check off, and it is off when `CI` is set. The logs are opened read only, and loopmath writes only to its store (`~/.loopmath`, which holds its caches too), to the skill folders `skill install` names, and to paths you name.
46
46
 
47
47
  The package installs two commands: `loopmath` and its short alias `loop`. If another `loop` is already on your PATH, use `loopmath`.
48
48
 
@@ -64,6 +64,8 @@ python3 -m venv .venv
64
64
 
65
65
  Installing needs the network: pip, pipx and uv download the build backend (setuptools 77 or newer) and the dependencies (jsonschema, numpy, pandas, scipy), from a clone too, so `pip install --no-index -e .` fails offline.
66
66
 
67
+ To upgrade, `loopmath update` says whether a newer loopmath is out and prints the command for how you installed it (`uv tool upgrade loopmath`, `pipx upgrade loopmath`, or pip); run it, then `loopmath skill install`. loopmath never upgrades itself.
68
+
67
69
  ## First run
68
70
 
69
71
  ```sh
@@ -177,7 +179,7 @@ The workflow builder is the one page that is served: `loopmath builder --type bu
177
179
  | Plan | `task-types`, `workflows` (list, show, validate, diff), `recommend`, `builder` |
178
180
  | Record | `run` (start, record, import, attempt, artifact, finish, sessions), `outcome`, `budget`, `config` (get, set, unset) |
179
181
  | Learn | `fit`, `onboard`, `share`, `prior` |
180
- | View | `runs`, `posterior`, `status`, `report`, `doctor`, `verify-receipts` |
182
+ | View | `runs`, `posterior`, `status`, `report`, `doctor`, `verify-receipts`, `update` |
181
183
  | Harness testing | `check-change`, `gate` (experimental), `screen` (experimental) |
182
184
  | Task subsets | `tasks pick` (experimental) |
183
185
  | Evolution loops | `adapt openevolve` (experimental), `adapt shinkaevolve` (experimental), `recommend --role` (experimental) |
@@ -308,7 +310,7 @@ The store is `~/.loopmath`. Set `LOOPMATH_HOME` or pass `--home` to put it elsew
308
310
  - signals, receipts and fits;
309
311
  - your config and your workflows;
310
312
  - the views you write;
311
- - the caches: the log parse cache, and the folder where `fit --full` compiles its model (when that compile fails, it also leaves the C code it tried in a `pytensor_compilation_error_*` file in the system temp folder and prints where).
313
+ - the caches: the log parse cache, the daily update check's last answer (`update.json`), and the folder where `fit --full` compiles its model (when that compile fails, it also leaves the C code it tried in a `pytensor_compilation_error_*` file in the system temp folder and prints where).
312
314
 
313
315
  Do not edit the store by hand; use the commands. `loopmath verify-receipts` checks the receipts in your store; give a file to verify a research receipt ledger instead.
314
316
 
@@ -1,10 +1,10 @@
1
- loopmath/__init__.py,sha256=FwSfUFdPCwuJZg0s1wSveMcOr9gr_X7IUxADSVkttRQ,244
1
+ loopmath/__init__.py,sha256=aGozqgIo2AYBW46OAW4DqzzcVxam2u5tyfcMeUs0DUE,244
2
2
  loopmath/__main__.py,sha256=X6nV3FjHmxDbIjccOYrBts_0KyJwOmDEPI5URzMO_-8,126
3
3
  loopmath/adapter_host.py,sha256=KBLHsP-LzrRDzOaDQMJRDq-NfCJeT5nY_CQAPLqyKQ4,10284
4
- loopmath/cli.py,sha256=16RLm--_f0u9Eh9VX5-xG4l4hzgSKuwn0zDdbBTMe2I,30372
4
+ loopmath/cli.py,sha256=_na7CGsmdnm1WdKgZt4ScTdFtT8G4Ygc4jx-VBSchCk,31053
5
5
  loopmath/cli_errors.py,sha256=pf7kuCoA--zV0L4wwj8v3JA3KrJFaDIcdLUUuSF2sRo,4839
6
6
  loopmath/cli_graph.py,sha256=30VWDHnTEwAB_IX6CL_FluvnfAjydwrjDm0GRlBcLlQ,13492
7
- loopmath/cli_registry.py,sha256=8mrRrjVNTt2BEbGyVgMW5toTi98R-tBYe0byRZf8UlU,67309
7
+ loopmath/cli_registry.py,sha256=OFPNAwHVJm6KQLWYG8Ldi4HuzjdcbnJARvAEjCNPhbg,67725
8
8
  loopmath/cli_support.py,sha256=gD_33ELLH4oUuYtWbxoCSYr2LUpJuh3ay80sn1KpTUA,23199
9
9
  loopmath/explain.py,sha256=fQN2ANW4fniyWdm0k14Cvioicm_Nncx7-lanVPteTUw,3166
10
10
  loopmath/fit.py,sha256=8eelfN7KqrHVQFLvWkq0iCgHLD7Jun8shuslUFuXfmU,14680
@@ -22,7 +22,7 @@ loopmath/output.py,sha256=04_OCSBQxp0X_1um-DNgJUKQB-ihjul6XoCvXj-Nq-o,4806
22
22
  loopmath/pool.py,sha256=s3DfC2G2S6rK47PEyzSpIM1wYNQKnScpCtIallHhego,1953
23
23
  loopmath/price.py,sha256=Mr3yINrwwH9dZ2aKrv7BTsyQcukkU9fU3I4M1l1GR2A,24880
24
24
  loopmath/price_validation.py,sha256=7VY-vli5JFBh1FV2dRC241Akr6gLbJ7qos6fhuBr8_c,13246
25
- loopmath/prices.toml,sha256=5bYkgpWzK0D6numXZM6y-Ok3EuKevDH-iWBnsElIu1c,11376
25
+ loopmath/prices.toml,sha256=VQ_KHWF9i3kihk6O6m5nGG9PoS3yLawBtwSZUIjvdns,12872
26
26
  loopmath/receipts.py,sha256=gW_c1ZSyrL0czo1ilFdpeyonkqFuzKYbeaUknbrFDvE,7034
27
27
  loopmath/recommend_role.py,sha256=sofO0BzpmC52z4AlvXPEQNRX3sEuFdfxH1fmdtrhOrk,18082
28
28
  loopmath/research_defaults.py,sha256=tKbCtQGdj5E37qaIZeQ72MaX0eZOVSX31wNtOTxtr6E,248
@@ -38,6 +38,7 @@ loopmath/surface_presentation.py,sha256=F_gIyjJuhTyRtuQr44IwonpF_dgG-96IMJxjf94E
38
38
  loopmath/surface_support.py,sha256=IzPjIkyaMxKgViogpcbPkvlxOHsGF6B5X4o129ywPfE,6724
39
39
  loopmath/taskmodel.py,sha256=F34WCnByhZ7IbMUtaN-ryth0WD1RFO0ypDKbH2KYByA,30046
40
40
  loopmath/types.py,sha256=BZrdnMCKPWlGbdMBlk6Y5HRx7yeRyrzdMIyp2rHXizg,14223
41
+ loopmath/update.py,sha256=KHuKPkk4-UWPCeBf4c_8DNuy4jJummaPKmziYWB6GIg,12515
41
42
  loopmath/adapters/__init__.py,sha256=ildOOoO51WAX8uzAsPQmMketnP29-1yPnjeTi4kEIGM,1012
42
43
  loopmath/adapters/atrium.py,sha256=UvBfq_MMlqDX5L6LIM0tJf1wXGeCXcCpR4NN9OIr9V4,18495
43
44
  loopmath/adapters/base.py,sha256=Ryuh9P8q1f42JT7oEQL9THMhdaUeCoHY7O6hbQ14Fyw,13786
@@ -270,7 +271,7 @@ loopmath/share/export.py,sha256=5UTjI9e4NCmwzceV00iKXOXS1NzbYBy7WrcVyOq5AZA,2739
270
271
  loopmath/share/import_.py,sha256=Q-Xkr6bQaPXjgRNZi1ldnStTcQfQQDvdDNrnARhdat8,18290
271
272
  loopmath/skill/__init__.py,sha256=-DtMdtjqlKOBIRA-3sdr1oiJHqkL5xLBNuvkteYCRFk,95
272
273
  loopmath/skill/commands.py,sha256=ylzGDiLHAaiewFLJbXa_FvmlHEfGdJQNZUESokDrzLg,4636
273
- loopmath/skill/doctor.py,sha256=DS7rYXdH0E_uq1YMS_LMZXbkl6H465zS4epDBiNTvBk,12220
274
+ loopmath/skill/doctor.py,sha256=I0npD3NNXKq7ZskQVrIZJkEOT_F31vQ8w7S2omJB4AI,12412
274
275
  loopmath/skill/guide.py,sha256=CcSLpTGjGLZKu1N0IiaItZUqRiZXWVUiPQOZEibNpLo,2267
275
276
  loopmath/skill/install.py,sha256=o1iPskwmfNCAXowYyknfLCFyNNEE1OqbyWn1IwnrLuo,29895
276
277
  loopmath/skill/guides/fit.md,sha256=OXW_AxHXGUgR5sJ-JLdlhzAC5fEUc1pLtSaPWpw-kn8,2301
@@ -278,11 +279,11 @@ loopmath/skill/guides/import.md,sha256=iLjA3sABPeZtMwki3lCWPZgaaSFXgnFpp_LWqZRVI
278
279
  loopmath/skill/guides/onboard.md,sha256=CuN4a13hktbJssDnXXk-CQjdUAJ-h6yh87eJ8CZ-m7Q,4409
279
280
  loopmath/skill/guides/plan.md,sha256=CG9V3opdsO1ejBJpwo56lz_01DmRt2rg0TJqs6sF-eQ,10086
280
281
  loopmath/skill/guides/record.md,sha256=DOf0BJ-qo3AOOEtDFGuf1RYwHrq-sEezay3apUEgbKQ,6231
281
- loopmath/skill/guides/reference.md,sha256=Fp7EMaPNjdmFkxW4ImxhkWRlOvxZ5gb4Par0pxXXjEU,16604
282
- loopmath/skill/skills/loopmath/SKILL.md,sha256=fr2rj-2ICFAI6Vw7TtwtnWMcvcYs8QCwc-nrrW261_I,3550
282
+ loopmath/skill/guides/reference.md,sha256=_UdmF_h4t3M9FaGMJ5zALY3Vcyqc_Kh0sVHoWgWCcs8,16918
283
+ loopmath/skill/skills/loopmath/SKILL.md,sha256=nzrwQuzeCaiWZOplE67cnCL9zcQo-F5lxBDFdRPUvow,3667
283
284
  loopmath/store/__init__.py,sha256=vCGuqOSRKmKoT4eLbjEl8kxJRwdHWqxouGTp6gqPLFE,708
284
285
  loopmath/store/budget.py,sha256=5ra1EuTJOQ5K7xCaN2_cdqQWbPvRkyLjcBuD5K32PvY,8526
285
- loopmath/store/commands.py,sha256=28Lnw-YiXZZFy5oYMPfINMXrHAoT_Z2IeCtvFgQlfVs,81726
286
+ loopmath/store/commands.py,sha256=AZ-FcItafEV2wkhaJetmVkGHWzuKW0ilfBS-R-bcIUg,81868
286
287
  loopmath/store/config.py,sha256=SmBD9umWq-7oHmnXR_m8gdUYq1p--dxJZs-EHFw8F28,29384
287
288
  loopmath/store/finish.py,sha256=WSxjWDOG5Z0NCLBnDsRRkTztwrKmHvqIvjrbfzv_a6M,32952
288
289
  loopmath/store/fitjob.py,sha256=GHBF61GyT9V-SGne-drAdaEzp2J5X8lSpgHitjHtwH0,11809
@@ -342,12 +343,12 @@ loopmath/workflows/catalog/plan_implement.toml,sha256=qxAs6G3JGOUuW6TnhiaUXzaFfy
342
343
  loopmath/workflows/catalog/plan_implement_review.toml,sha256=rRtiactglcJAynFWbrjnI-Ftbl3qe971ov9HJ3Vr7uU,862
343
344
  loopmath/workflows/catalog/solo.toml,sha256=aJWBEEfS4DNCLqznDI3yp-7s1ZXx_rdqsEIPX7n0-nM,373
344
345
  loopmath/workflows/catalog/swarm.toml,sha256=1hbQR41nl7VS_XN1z2fmwLCNw6kn2syowpwwauFUL3o,850
345
- loopmath-0.3.4.data/data/spec/ocp-v0.2.schema.json,sha256=T4P5gg6H2dW-28MRbg9fSNct_ejXezI69-SaKR9WogU,31855
346
- loopmath-0.3.4.data/data/spec/ocp-v0.schema.json,sha256=tOGqmvAjh0Ap09zV3QLQp3PovQB8inpVNgxSnrPS354,15279
347
- loopmath-0.3.4.data/data/spec/ocp_conformance.py,sha256=VzRGKvC6f-64U72xrDOSJEeYa92Bpj3tEf5x0uJXqhk,893
348
- loopmath-0.3.4.dist-info/licenses/LICENSE,sha256=Df5w_-_yYMWXFWcPR1Cj0pDXWBCE5_xdFN9WCNGHuGQ,1065
349
- loopmath-0.3.4.dist-info/METADATA,sha256=rDpRaSxt3ZMOJ5UumjfA-XAbwg_3kcmbnfScKIbSbSA,39523
350
- loopmath-0.3.4.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
351
- loopmath-0.3.4.dist-info/entry_points.txt,sha256=WQwYqfGAwvoQ_vu6_lwQpq3V8xbK3i9SyNKPDdQ1VmQ,72
352
- loopmath-0.3.4.dist-info/top_level.txt,sha256=SH9Y0Z7thA0zx1PAgHAwc1vOJaS6o3yS5HazS-LzXOg,9
353
- loopmath-0.3.4.dist-info/RECORD,,
346
+ loopmath-0.3.5.data/data/spec/ocp-v0.2.schema.json,sha256=T4P5gg6H2dW-28MRbg9fSNct_ejXezI69-SaKR9WogU,31855
347
+ loopmath-0.3.5.data/data/spec/ocp-v0.schema.json,sha256=tOGqmvAjh0Ap09zV3QLQp3PovQB8inpVNgxSnrPS354,15279
348
+ loopmath-0.3.5.data/data/spec/ocp_conformance.py,sha256=VzRGKvC6f-64U72xrDOSJEeYa92Bpj3tEf5x0uJXqhk,893
349
+ loopmath-0.3.5.dist-info/licenses/LICENSE,sha256=Df5w_-_yYMWXFWcPR1Cj0pDXWBCE5_xdFN9WCNGHuGQ,1065
350
+ loopmath-0.3.5.dist-info/METADATA,sha256=3BXJFjowPcpIu-gPIHS28ZdIVSGaWdzlyb1fEXX6m20,40077
351
+ loopmath-0.3.5.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
352
+ loopmath-0.3.5.dist-info/entry_points.txt,sha256=WQwYqfGAwvoQ_vu6_lwQpq3V8xbK3i9SyNKPDdQ1VmQ,72
353
+ loopmath-0.3.5.dist-info/top_level.txt,sha256=SH9Y0Z7thA0zx1PAgHAwc1vOJaS6o3yS5HazS-LzXOg,9
354
+ loopmath-0.3.5.dist-info/RECORD,,