loki-mode 8.70.0 → 8.72.0

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.
package/mcp/__init__.py CHANGED
@@ -75,4 +75,4 @@ try:
75
75
  except ImportError:
76
76
  __all__ = ['mcp']
77
77
 
78
- __version__ = '8.70.0'
78
+ __version__ = '8.72.0'
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "loki-mode",
3
3
  "mcpName": "io.github.asklokesh/loki-mode",
4
- "version": "8.70.0",
4
+ "version": "8.72.0",
5
5
  "description": "Loki Mode by Autonomi. Autonomous spec-to-product system: takes a PRD, GitHub issue, OpenAPI/JSON/YAML, or one-line brief to a deployed app via the RARV-C closure loop with 8 quality gates. Provider-agnostic (Claude Code, OpenAI Codex, Cline, Aider).",
6
6
  "keywords": [
7
7
  "agent",
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
3
3
  "name": "loki-mode",
4
4
  "displayName": "Loki Mode",
5
- "version": "8.70.0",
5
+ "version": "8.72.0",
6
6
  "description": "Autonomous spec-to-product build system with a built-in trust layer (RARV-C closure loop, 8 quality gates, completion council). Ships Loki's spec-hardening, drift-detection, and deterministic PR verification commands plus the Loki MCP server.",
7
7
  "author": {
8
8
  "name": "Autonomi",
@@ -0,0 +1,346 @@
1
+ #!/usr/bin/env python3
2
+ """Pre-run cost estimate: what is this run likely to cost, and on what basis.
3
+
4
+ WHY THIS EXISTS. cost-summary.py answers "what did that run cost" AFTER the
5
+ fact. The PRD-shaped estimator behind `loki plan` answers "what will a build of
6
+ this PRD cost" from PRD heuristics, before any run exists. Neither answers the
7
+ question an operator asks when they already have history in this workspace:
8
+ given what iterations here have ACTUALLY cost, what is N more likely to cost.
9
+
10
+ THE HONESTY RULE THIS INHERITS. Unmeasured is not free. That confusion shipped
11
+ to a user on four separate surfaces (v8.51.0 through v8.54.0). This is another
12
+ surface reading the same records, so it obeys the same rule by importing the
13
+ same predicate rather than restating it:
14
+
15
+ - Zero measured records means NO BASIS. The projection is None and the render
16
+ says so. It never prints $0.00, because a fabricated zero is exactly the
17
+ defect this lineage keeps paying down, and a forward-looking $0.00 is worse
18
+ than a backward-looking one: it invites someone to start a run believing it
19
+ is free.
20
+ - Unmeasured records are EXCLUDED from the basis, never averaged in as zero.
21
+ The count that informed the estimate is always stated, so a 2-of-9 basis
22
+ can never be mistaken for a 9-of-9 one.
23
+ - A single data point is labelled as a single data point. A median of one is
24
+ arithmetically fine and epistemically nearly worthless; saying "median"
25
+ without saying "of 1" is how a guess acquires unearned authority.
26
+ - The output is labelled an ESTIMATE with its basis. Never a guarantee.
27
+
28
+ MEASURED IS NOT THE SAME AS PRICED. record_is_measured() is field-agnostic on
29
+ purpose: a record carrying real tokens but cost_usd 0 is "measured" on the
30
+ strength of its tokens. For a COST basis that record is useless, and averaging
31
+ its 0 in would drag the projection toward a fabricated low -- the headline rule
32
+ inverted. Real costs are stored raw (0.018719), so a sub-cent charge is 0.0001
33
+ and never exactly 0; an exact zero is therefore a reliable unpriced signal.
34
+ cost-summary.py draws the same line for the same reason. So three counts are
35
+ reported, not two:
36
+
37
+ found iteration-*.json records the shared reader accepted
38
+ measured record_is_measured() -- carried an observed value
39
+ priced measured AND cost_usd is non-zero -- the actual basis
40
+
41
+ WHAT THIS DELIBERATELY DOES NOT DO. It does not derive a median ITERATION COUNT.
42
+ One workspace's .loki/metrics/efficiency/ holds one run's iterations, so a
43
+ "median iteration count" over it would be a median of one sample dressed up as a
44
+ distribution. There is no multi-run archive to draw a real one from, so
45
+ --iterations is REQUIRED. Inventing the horizon and then multiplying a real
46
+ per-iteration cost by it would launder a guess through an honest number.
47
+
48
+ Usage:
49
+ python3 tools/estimate-run.py --iterations 12 [WORKSPACE] [--json]
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import argparse
55
+ import importlib.util
56
+ import json
57
+ import os
58
+ import statistics
59
+ import sys
60
+
61
+ _HERE = os.path.dirname(os.path.abspath(__file__))
62
+ _REPO_ROOT = os.path.dirname(_HERE)
63
+ _LIB = os.path.join(_REPO_ROOT, "autonomy", "lib")
64
+ if _LIB not in sys.path:
65
+ sys.path.insert(0, _LIB)
66
+
67
+ # THE single definition of "measured". Restating it here is how the honesty
68
+ # rule drifts; the four surfaces that once rendered an unmeasured run as
69
+ # "$0.00" each had their own idea of what counted.
70
+ from efficiency_cost import record_is_measured # noqa: E402
71
+
72
+ # iteration_attribution.py already reads, filters and sorts the efficiency dir
73
+ # (skipping malformed records rather than defaulting them to zero).
74
+ # cost-summary.py imports it for exactly this reason: one reader of that
75
+ # directory. A third copy would drift the same way a second predicate would.
76
+ _ia_spec = importlib.util.spec_from_file_location(
77
+ "iteration_attribution", os.path.join(_LIB, "iteration_attribution.py"))
78
+ _ia = importlib.util.module_from_spec(_ia_spec)
79
+ _ia_spec.loader.exec_module(_ia)
80
+
81
+ # Alias-keyed table: {"pricing": {"sonnet": {"input": 3.0, "output": 15.0, ...}}}
82
+ # USD per 1M tokens. NOT the same schema as benchmarks/bench/prices.json (which
83
+ # efficiency_cost.price_from_tokens reads, keyed models.<x>.input_per_mtok), so
84
+ # this reads model-pricing.json directly rather than routing through it.
85
+ PRICING_PATH = os.path.join(
86
+ _REPO_ROOT, "loki-ts", "data", "model-pricing.json")
87
+
88
+
89
+ def _num(v):
90
+ """Non-bool int/float, else None. Never coerces junk to 0."""
91
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
92
+ return None
93
+ return v
94
+
95
+
96
+ def load_pricing(path=None):
97
+ """Return the alias -> rates map, or {} when unreadable.
98
+
99
+ A missing price table means we cannot quote a price, which is an honest
100
+ null. It never blocks the projection: observed cost comes from the recorded
101
+ cost_usd, not from this table.
102
+ """
103
+ try:
104
+ with open(path or PRICING_PATH, encoding="utf-8") as handle:
105
+ data = json.load(handle)
106
+ except Exception:
107
+ return {}
108
+ pricing = data.get("pricing") if isinstance(data, dict) else None
109
+ return pricing if isinstance(pricing, dict) else {}
110
+
111
+
112
+ def resolve_model_now(workspace="."):
113
+ """The model a run started NOW would use, and the lever that chose it.
114
+
115
+ Mirrors the runner's precedence -- a pending mid-flight override file is the
116
+ most specific, just-requested intent and wins over the session pin. Returns
117
+ (model, source); (None, None) when neither lever is set, which is an honest
118
+ "unresolved" rather than a guessed default. Guessing here would let the
119
+ report assert the projection transfers when it may not.
120
+ """
121
+ override = os.path.join(workspace, ".loki", "state", "model-override")
122
+ try:
123
+ with open(override, encoding="utf-8") as handle:
124
+ val = handle.read().strip().lower()
125
+ if val:
126
+ return val, "model-override file"
127
+ except OSError:
128
+ pass
129
+ val = (os.environ.get("LOKI_SESSION_MODEL") or "").strip().lower()
130
+ if val:
131
+ return val, "LOKI_SESSION_MODEL"
132
+ return None, None
133
+
134
+
135
+ def estimate(workspace=".", iterations=None, pricing_path=None):
136
+ """Build the estimate dict. Pure derivation, no guessing."""
137
+ loki_dir = os.path.join(workspace, ".loki")
138
+ recs = _ia._iteration_records(loki_dir)
139
+
140
+ found = len(recs)
141
+ measured = 0
142
+ cost_points = [] # priced costs only -- THE basis
143
+ basis_models = [] # models of the priced records, in order
144
+
145
+ for rec in recs:
146
+ if not record_is_measured(rec):
147
+ # EXCLUDED, not added as zero. Averaging an unmeasured iteration in
148
+ # as 0 is indistinguishable from a real measurement of 0.
149
+ continue
150
+ measured += 1
151
+ usd = _num(rec.get("cost_usd"))
152
+ # Measured on tokens but unpriced: real for token accounting, useless
153
+ # for a cost basis, and a fabricated low if averaged in. See module
154
+ # docstring.
155
+ if usd is None or usd == 0:
156
+ continue
157
+ cost_points.append(float(usd))
158
+ model = rec.get("model")
159
+ basis_models.append(str(model) if model else "")
160
+
161
+ # THE HONESTY GUARD. No priced history means no basis, so every downstream
162
+ # number is None and the render says why. Turning this into 0.0 is the
163
+ # "unmeasured becomes free" defect, pointed at the future.
164
+ median_usd = None if not cost_points else statistics.median(cost_points)
165
+
166
+ known_models = sorted({m for m in basis_models if m})
167
+ model_now, model_source = resolve_model_now(workspace)
168
+ rates = load_pricing(pricing_path).get(model_now) if model_now else None
169
+
170
+ out = {
171
+ "workspace": os.path.abspath(workspace),
172
+ "label": "ESTIMATE",
173
+ "iterations_found": found,
174
+ "iterations_measured": measured,
175
+ "iterations_priced": len(cost_points),
176
+ "basis_count": len(cost_points),
177
+ "has_basis": bool(cost_points),
178
+ "single_point_basis": len(cost_points) == 1,
179
+ "median_cost_per_iteration_usd": (
180
+ None if median_usd is None else round(median_usd, 4)),
181
+ "min_cost_per_iteration_usd": (
182
+ round(min(cost_points), 4) if cost_points else None),
183
+ "max_cost_per_iteration_usd": (
184
+ round(max(cost_points), 4) if cost_points else None),
185
+ "iterations_projected": iterations,
186
+ "projected_cost_usd": (
187
+ round(median_usd * iterations, 4)
188
+ if median_usd is not None and iterations else None),
189
+ "basis_models": known_models,
190
+ "model_now": model_now,
191
+ "model_now_source": model_source,
192
+ "model_now_price_per_mtok": (
193
+ {"input": rates.get("input"), "output": rates.get("output"),
194
+ "cache_read": rates.get("cache_read")}
195
+ if isinstance(rates, dict) else None),
196
+ "projection_transfers": None,
197
+ "notes": [],
198
+ }
199
+
200
+ n = out["notes"]
201
+
202
+ if found == 0:
203
+ n.append(
204
+ "no iteration records found in this workspace: there is NO history "
205
+ "to project from, so no cost is estimated (not $0.00)")
206
+ elif not cost_points:
207
+ n.append(
208
+ "no measured, priced iteration in %d record(s): there is NO basis "
209
+ "to project from, so no cost is estimated (not $0.00)" % found)
210
+ if measured:
211
+ n.append(
212
+ "%d of %d records carried tokens but no cost (unpriced model): "
213
+ "spend is unknown rather than zero, so they cannot form a basis"
214
+ % (measured - len(cost_points), measured))
215
+ else:
216
+ n.append(
217
+ "ESTIMATE based on %d measured, priced iteration(s) of %d found -- "
218
+ "not a guarantee" % (len(cost_points), found))
219
+ if len(cost_points) == 1:
220
+ n.append(
221
+ "the basis is a SINGLE data point: this is one observation "
222
+ "extrapolated, not a distribution, and the range is that one "
223
+ "point")
224
+ if len(cost_points) < found:
225
+ n.append(
226
+ "PARTIAL: %d of %d records did not inform the estimate "
227
+ "(unmeasured or unpriced), and were excluded rather than "
228
+ "counted as zero" % (found - len(cost_points), found))
229
+ if iterations is None:
230
+ n.append(
231
+ "no --iterations given and no multi-run history exists to "
232
+ "derive a median iteration count from: pass --iterations N for "
233
+ "a projection")
234
+
235
+ # MODEL TRANSFER. Naming the model is not enough -- if history was priced on
236
+ # a different model than the one that would run now, the per-iteration
237
+ # median does not carry over, and saying so is the difference between an
238
+ # estimate and a misleading one.
239
+ if cost_points:
240
+ if len(known_models) > 1:
241
+ out["projection_transfers"] = False
242
+ n.append(
243
+ "the basis MIXES models (%s): a single median across different "
244
+ "price points may not transfer to either" % ", ".join(known_models))
245
+ elif not known_models:
246
+ out["projection_transfers"] = None
247
+ n.append(
248
+ "the basis records name no model: whether this projection "
249
+ "transfers to the model that would run now is unknown")
250
+ elif model_now is None:
251
+ out["projection_transfers"] = None
252
+ n.append(
253
+ "basis model is %s; no model is pinned for a run now "
254
+ "(LOKI_SESSION_MODEL unset, no override file), so whether the "
255
+ "projection transfers is unknown" % known_models[0])
256
+ elif model_now != known_models[0]:
257
+ out["projection_transfers"] = False
258
+ n.append(
259
+ "basis model is %s but a run now would use %s (%s): this "
260
+ "projection MAY NOT TRANSFER" % (
261
+ known_models[0], model_now, model_source))
262
+ else:
263
+ out["projection_transfers"] = True
264
+
265
+ if model_now and rates is None:
266
+ n.append(
267
+ "no price listed for %s in the pricing table: its rate is not "
268
+ "quoted (the projection still comes from observed cost, not price)"
269
+ % model_now)
270
+
271
+ return out
272
+
273
+
274
+ def _fmt_usd(v):
275
+ """UNKNOWN, never $0.00, when there is nothing to report."""
276
+ return "UNKNOWN" if v is None else "$%.4f" % v
277
+
278
+
279
+ def render(est):
280
+ """Human-readable report. The honesty lives here too, not only in the dict."""
281
+ lines = []
282
+ lines.append("Run cost ESTIMATE -- %s" % est["workspace"])
283
+ lines.append("")
284
+
285
+ if not est["has_basis"]:
286
+ lines.append(" NO BASIS: no measured, priced iteration to project from.")
287
+ lines.append(" Cost per iteration: UNKNOWN")
288
+ lines.append(" Projected cost: UNKNOWN")
289
+ lines.append(" Records found: %d measured: %d priced: %d"
290
+ % (est["iterations_found"], est["iterations_measured"],
291
+ est["iterations_priced"]))
292
+ else:
293
+ lines.append(" Basis: %d measured, priced iteration(s) "
294
+ "of %d found" % (est["basis_count"], est["iterations_found"]))
295
+ lines.append(" Cost per iteration: median %s (range %s - %s)" % (
296
+ _fmt_usd(est["median_cost_per_iteration_usd"]),
297
+ _fmt_usd(est["min_cost_per_iteration_usd"]),
298
+ _fmt_usd(est["max_cost_per_iteration_usd"])))
299
+ if est["iterations_projected"]:
300
+ label = "Projected for %d:" % est["iterations_projected"]
301
+ lines.append(" %-20s %s"
302
+ % (label, _fmt_usd(est["projected_cost_usd"])))
303
+ else:
304
+ lines.append(" Projected cost: UNKNOWN (pass --iterations N)")
305
+
306
+ basis_models = est["basis_models"]
307
+ lines.append(" Basis model(s): %s"
308
+ % (", ".join(basis_models) if basis_models else "not recorded"))
309
+ if est["model_now"]:
310
+ rate = est["model_now_price_per_mtok"]
311
+ price = ("not in pricing table" if not rate else
312
+ "$%s in / $%s out per Mtok" % (rate["input"], rate["output"]))
313
+ lines.append(" Model now: %s (via %s) -- %s"
314
+ % (est["model_now"], est["model_now_source"], price))
315
+ else:
316
+ lines.append(" Model now: not pinned")
317
+
318
+ lines.append("")
319
+ for note in est["notes"]:
320
+ lines.append(" - %s" % note)
321
+ return "\n".join(lines)
322
+
323
+
324
+ def main(argv=None):
325
+ ap = argparse.ArgumentParser(
326
+ description="Estimate what a run is likely to cost, from measured history.")
327
+ ap.add_argument("workspace", nargs="?", default=".")
328
+ ap.add_argument("--iterations", type=int, default=None,
329
+ help="how many iterations to project (no multi-run history "
330
+ "exists to derive this, so it is required for a "
331
+ "projected total)")
332
+ ap.add_argument("--json", action="store_true")
333
+ args = ap.parse_args(argv)
334
+
335
+ est = estimate(args.workspace, args.iterations)
336
+ if args.json:
337
+ print(json.dumps(est, indent=2))
338
+ else:
339
+ print(render(est))
340
+ # Exit 0 either way: "no basis" is a successful, honest answer, not a tool
341
+ # failure. Callers read has_basis.
342
+ return 0
343
+
344
+
345
+ if __name__ == "__main__":
346
+ sys.exit(main())