leanprompt 0.0.1 → 0.1.0-dev.8
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/LICENSE +202 -0
- package/LICENSE-DOCS +396 -0
- package/NOTICE +11 -0
- package/README.md +86 -3
- package/cli/dist/detect.d.ts +23 -0
- package/cli/dist/detect.js +219 -0
- package/cli/dist/evalAudit.d.ts +32 -0
- package/cli/dist/evalAudit.js +161 -0
- package/cli/dist/facts.d.ts +14 -0
- package/cli/dist/facts.js +43 -0
- package/cli/dist/forms.d.ts +23 -0
- package/cli/dist/forms.js +199 -0
- package/cli/dist/frontmatter.d.ts +10 -0
- package/cli/dist/frontmatter.js +32 -0
- package/cli/dist/help.d.ts +27 -0
- package/cli/dist/help.js +118 -0
- package/cli/dist/init.d.ts +78 -0
- package/cli/dist/init.js +358 -0
- package/cli/dist/install.d.ts +20 -0
- package/cli/dist/install.js +225 -0
- package/cli/dist/isMain.d.ts +6 -0
- package/cli/dist/isMain.js +18 -0
- package/cli/dist/lesson.d.ts +16 -0
- package/cli/dist/lesson.js +205 -0
- package/cli/dist/lint/facts.d.ts +7 -0
- package/cli/dist/lint/facts.js +163 -0
- package/cli/dist/lint/numbers.d.ts +26 -0
- package/cli/dist/lint/numbers.js +163 -0
- package/cli/dist/lint/rules.d.ts +20 -0
- package/cli/dist/lint/rules.js +170 -0
- package/cli/dist/log/logger.d.ts +49 -0
- package/cli/dist/log/logger.js +148 -0
- package/cli/dist/log/record.d.ts +56 -0
- package/cli/dist/log/record.js +117 -0
- package/cli/dist/main.d.ts +6 -0
- package/cli/dist/main.js +67 -0
- package/cli/dist/profile.d.ts +93 -0
- package/cli/dist/profile.js +372 -0
- package/cli/dist/report/cost.d.ts +55 -0
- package/cli/dist/report/cost.js +151 -0
- package/cli/dist/report/html.d.ts +81 -0
- package/cli/dist/report/html.js +555 -0
- package/cli/dist/report/template.html +269 -0
- package/cli/dist/score/calibrate.d.ts +65 -0
- package/cli/dist/score/calibrate.js +213 -0
- package/cli/dist/score/measured.d.ts +66 -0
- package/cli/dist/score/measured.js +191 -0
- package/cli/dist/score/static.d.ts +112 -0
- package/cli/dist/score/static.js +172 -0
- package/cli/dist/score/write.d.ts +29 -0
- package/cli/dist/score/write.js +247 -0
- package/forms/AGENTS.block.md +25 -0
- package/forms/opencode/commands/leanprompt-audit.md +10 -0
- package/forms/opencode/commands/leanprompt.md +8 -0
- package/forms/skills/generation-economy/SKILL.md +89 -0
- package/forms/skills/generation-economy/rules/LP-GE-01.md +93 -0
- package/forms/skills/generation-economy/rules/LP-GE-02.md +82 -0
- package/forms/skills/generation-economy/rules/LP-GE-03.md +87 -0
- package/forms/skills/generation-economy/rules/LP-GE-04.md +118 -0
- package/forms/skills/generation-economy/rules/LP-GE-05.md +84 -0
- package/forms/skills/generation-economy/rules/LP-GE-06.md +76 -0
- package/forms/skills/generation-economy/rules/LP-GE-07.md +84 -0
- package/forms/skills/generation-economy/rules/LP-GE-08.md +71 -0
- package/forms/skills/generation-economy/rules/LP-GE-09.md +79 -0
- package/forms/skills/generation-economy/rules/LP-GE-10.md +104 -0
- package/forms/skills/leanprompt/SKILL.md +48 -0
- package/forms/skills/leanprompt/fix.md +15 -0
- package/forms/skills/leanprompt/init.md +30 -0
- package/forms/skills/llm-call-audit/SKILL.md +169 -0
- package/forms/skills/llm-call-audit/call-shapes.md +99 -0
- package/forms/skills/llm-call-audit/presenting.md +72 -0
- package/forms/skills/llm-call-audit/report-template.md +113 -0
- package/forms/skills/lmwarden/SKILL.md +97 -0
- package/forms/skills/lmwarden/rules/LP-LW-01.md +73 -0
- package/forms/skills/lmwarden/rules/LP-LW-02.md +78 -0
- package/forms/skills/lmwarden/rules/LP-LW-03.md +73 -0
- package/forms/skills/measure-loop/SKILL.md +155 -0
- package/forms/skills/measure-loop/templates/stable-head.template.ts +38 -0
- package/forms/skills/measure-loop/templates/stable_head_template.py +40 -0
- package/forms/skills/prefill-cache/SKILL.md +66 -0
- package/forms/skills/prefill-cache/rules/LP-PC-01.md +103 -0
- package/forms/skills/prefill-cache/rules/LP-PC-02.md +80 -0
- package/forms/skills/prefill-cache/rules/LP-PC-03.md +75 -0
- package/forms/skills/prefill-cache/rules/LP-PC-04.md +79 -0
- package/forms/skills/prefill-cache/rules/LP-PC-05.md +68 -0
- package/forms/skills/prefill-cache/rules/LP-PC-06.md +71 -0
- package/forms/skills/prefill-cache/rules/LP-PC-07.md +97 -0
- package/forms/skills/prefill-cache/rules/LP-PC-08.md +67 -0
- package/forms/skills/prefill-cache/rules/LP-PC-09.md +75 -0
- package/forms/skills/prefill-cache/rules/LP-PC-10.md +76 -0
- package/forms/skills/prefill-cache/rules/LP-PC-11.md +72 -0
- package/forms/skills/prefill-cache/rules/LP-PC-12.md +73 -0
- package/forms/skills/prompt-diet/SKILL.md +69 -0
- package/forms/skills/prompt-diet/rules/LP-PD-01.md +79 -0
- package/forms/skills/prompt-diet/rules/LP-PD-02.md +73 -0
- package/forms/skills/prompt-diet/rules/LP-PD-03.md +65 -0
- package/forms/skills/prompt-diet/rules/LP-PD-04.md +77 -0
- package/forms/skills/prompt-diet/rules/LP-PD-05.md +71 -0
- package/forms/skills/prompt-diet/rules/LP-PD-06.md +68 -0
- package/models/anthropic-thinking.md +38 -0
- package/models/openai-reasoning.md +35 -0
- package/models/qwen.md +34 -0
- package/package.json +31 -8
- package/providers/anthropic.md +83 -0
- package/providers/deepinfra.md +46 -0
- package/providers/gemini.md +61 -0
- package/providers/openai.md +73 -0
- package/providers/openrouter.md +66 -0
- package/providers/sglang.md +41 -0
- package/providers/vllm.md +52 -0
- package/runtimes/http-clients.md +20 -0
- package/skills/_template/RULE.md +31 -0
- package/skills/generation-economy/SKILL.md +88 -0
- package/skills/generation-economy/rules/LP-GE-01.md +92 -0
- package/skills/generation-economy/rules/LP-GE-02.md +81 -0
- package/skills/generation-economy/rules/LP-GE-03.md +86 -0
- package/skills/generation-economy/rules/LP-GE-04.md +117 -0
- package/skills/generation-economy/rules/LP-GE-05.md +83 -0
- package/skills/generation-economy/rules/LP-GE-06.md +75 -0
- package/skills/generation-economy/rules/LP-GE-07.md +83 -0
- package/skills/generation-economy/rules/LP-GE-08.md +70 -0
- package/skills/generation-economy/rules/LP-GE-09.md +78 -0
- package/skills/generation-economy/rules/LP-GE-10.md +103 -0
- package/skills/leanprompt/SKILL.md +47 -0
- package/skills/leanprompt/fix.md +14 -0
- package/skills/leanprompt/init.md +29 -0
- package/skills/llm-call-audit/SKILL.md +168 -0
- package/skills/llm-call-audit/call-shapes.md +98 -0
- package/skills/llm-call-audit/presenting.md +71 -0
- package/skills/llm-call-audit/report-template.md +112 -0
- package/skills/lmwarden/SKILL.md +96 -0
- package/skills/lmwarden/rules/LP-LW-01.md +72 -0
- package/skills/lmwarden/rules/LP-LW-02.md +77 -0
- package/skills/lmwarden/rules/LP-LW-03.md +72 -0
- package/skills/measure-loop/SKILL.md +154 -0
- package/skills/measure-loop/templates/stable-head.template.ts +38 -0
- package/skills/measure-loop/templates/stable_head_template.py +40 -0
- package/skills/prefill-cache/SKILL.md +65 -0
- package/skills/prefill-cache/rules/LP-PC-01.md +102 -0
- package/skills/prefill-cache/rules/LP-PC-02.md +79 -0
- package/skills/prefill-cache/rules/LP-PC-03.md +74 -0
- package/skills/prefill-cache/rules/LP-PC-04.md +78 -0
- package/skills/prefill-cache/rules/LP-PC-05.md +67 -0
- package/skills/prefill-cache/rules/LP-PC-06.md +70 -0
- package/skills/prefill-cache/rules/LP-PC-07.md +96 -0
- package/skills/prefill-cache/rules/LP-PC-08.md +66 -0
- package/skills/prefill-cache/rules/LP-PC-09.md +74 -0
- package/skills/prefill-cache/rules/LP-PC-10.md +75 -0
- package/skills/prefill-cache/rules/LP-PC-11.md +71 -0
- package/skills/prefill-cache/rules/LP-PC-12.md +72 -0
- package/skills/prompt-diet/SKILL.md +68 -0
- package/skills/prompt-diet/rules/LP-PD-01.md +78 -0
- package/skills/prompt-diet/rules/LP-PD-02.md +72 -0
- package/skills/prompt-diet/rules/LP-PD-03.md +64 -0
- package/skills/prompt-diet/rules/LP-PD-04.md +76 -0
- package/skills/prompt-diet/rules/LP-PD-05.md +70 -0
- package/skills/prompt-diet/rules/LP-PD-06.md +67 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// Measured score from a usage log (DESIGN §8). Pure: the caller reads the log and the provider facts.
|
|
2
|
+
import { cap } from "../facts.js";
|
|
3
|
+
import { scoreFrom } from "./static.js";
|
|
4
|
+
/** A measured score needs at least this many measured calls (DESIGN §8). */
|
|
5
|
+
export const MIN_CALLS = 50;
|
|
6
|
+
const validNodeChars = (nc, n) => {
|
|
7
|
+
if (!Array.isArray(nc) || nc.length === 0 || nc.length !== n)
|
|
8
|
+
return false;
|
|
9
|
+
let prev = 0;
|
|
10
|
+
for (const c of nc) {
|
|
11
|
+
if (typeof c !== "number" || !Number.isFinite(c) || c < prev)
|
|
12
|
+
return false;
|
|
13
|
+
prev = c;
|
|
14
|
+
}
|
|
15
|
+
return prev > 0;
|
|
16
|
+
};
|
|
17
|
+
/** Record positions in time order: earlier `ts` first, equal (or unreadable) `ts` in file order; unreadable ts last. */
|
|
18
|
+
function timeOrder(records) {
|
|
19
|
+
const t = records.map((r) => {
|
|
20
|
+
const ms = Date.parse(r.ts);
|
|
21
|
+
return Number.isNaN(ms) ? Number.POSITIVE_INFINITY : ms;
|
|
22
|
+
});
|
|
23
|
+
const order = records.map((_, i) => i).sort((a, b) => (t[a] === t[b] ? a - b : t[a] < t[b] ? -1 : 1));
|
|
24
|
+
return { order, t };
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The measured score of a usage log (DESIGN §8).
|
|
28
|
+
*
|
|
29
|
+
* In time order (`ts`; equal ts keep file order), for each measured record r:
|
|
30
|
+
* - shared(r) is the deepest i such that r.ids.nodes[0..i] equals the nodes prefix of an earlier
|
|
31
|
+
* measured record seen within the provider's `ttl_seconds` (0 = no limit), across all `conv`s.
|
|
32
|
+
* - reusable(r) = cap(facts, round(prompt_tokens x node_chars[i] / node_chars[last])), or 0 when
|
|
33
|
+
* nothing is shared. Missing Anthropic breakpoints do not reduce it (owner ruling D1).
|
|
34
|
+
* - stable(r) is the same estimate over the deepest prefix shared with an earlier measured record of
|
|
35
|
+
* any age, then cap: the structure the app kept, whether or not the cache still held it.
|
|
36
|
+
* - E = sum cached / sum reusable, clamped to [0, 1]; 1 when nothing is reusable.
|
|
37
|
+
* - S = sum stable / sum prompt over records that continue an earlier record with the same conv; 1 when
|
|
38
|
+
* none. The cache lifetime does not affect S: a user's pause is not the app rewriting its prefix.
|
|
39
|
+
* G = output tokens of wasted calls / all output tokens, over every record. A call is wasted when
|
|
40
|
+
* (a) an earlier call has the same last node and the same params, (b) flags.retry_of is the
|
|
41
|
+
* position (0-based, in `records`, earlier than the retry) of a call with finish "length" and the
|
|
42
|
+
* same params, or (c) flags.parse_failed.
|
|
43
|
+
*
|
|
44
|
+
* A record is unmeasured (out of E and S, never zero reuse) when its finish is "error" (call_failed),
|
|
45
|
+
* its prompt_tokens is 0 or less (no_usage: the logger got no usage counts, so a broken integration
|
|
46
|
+
* refuses instead of scoring a perfect E), it has no ids, its node_chars is missing, empty, misaligned with ids.nodes, not non-decreasing
|
|
47
|
+
* or ends at 0, its ts is unreadable,
|
|
48
|
+
* or `factsFor` has no facts for its provider (throws or returns nothing: unknown_provider; throws an
|
|
49
|
+
* error with `code: "ambiguous_target"`: ambiguous_target, the profile lists several targets and the
|
|
50
|
+
* record's provider matches none of them).
|
|
51
|
+
*/
|
|
52
|
+
export function measuredScore(records, factsFor) {
|
|
53
|
+
const { order, t } = timeOrder(records);
|
|
54
|
+
const by_reason = {
|
|
55
|
+
no_usage: 0, no_ids: 0, bad_node_chars: 0, bad_ts: 0, unknown_provider: 0, ambiguous_target: 0, call_failed: 0,
|
|
56
|
+
};
|
|
57
|
+
// A facts lookup either gives facts or the reason it gave none.
|
|
58
|
+
const factsCache = new Map();
|
|
59
|
+
const lookup = (provider) => {
|
|
60
|
+
if (!factsCache.has(provider)) {
|
|
61
|
+
let f;
|
|
62
|
+
try {
|
|
63
|
+
f = factsFor(provider) ?? "unknown_provider";
|
|
64
|
+
}
|
|
65
|
+
catch (e) {
|
|
66
|
+
f = e?.code === "ambiguous_target" ? "ambiguous_target" : "unknown_provider";
|
|
67
|
+
}
|
|
68
|
+
factsCache.set(provider, f);
|
|
69
|
+
}
|
|
70
|
+
return factsCache.get(provider);
|
|
71
|
+
};
|
|
72
|
+
const measured = [];
|
|
73
|
+
for (const i of order) {
|
|
74
|
+
const r = records[i];
|
|
75
|
+
let why = null;
|
|
76
|
+
let facts = null;
|
|
77
|
+
// A failed call (finish "error") never reached the cache, or its state is unknown: not evidence either way.
|
|
78
|
+
if (r.finish === "error")
|
|
79
|
+
why = "call_failed";
|
|
80
|
+
// No prompt tokens: the usage object was missing or unreadable. Never evidence of reuse.
|
|
81
|
+
else if (!(r.prompt_tokens > 0))
|
|
82
|
+
why = "no_usage";
|
|
83
|
+
else if (!r.ids || !Array.isArray(r.ids.nodes) || r.ids.nodes.length === 0)
|
|
84
|
+
why = "no_ids";
|
|
85
|
+
else if (!validNodeChars(r.node_chars, r.ids.nodes.length))
|
|
86
|
+
why = "bad_node_chars";
|
|
87
|
+
else if (t[i] === Number.POSITIVE_INFINITY)
|
|
88
|
+
why = "bad_ts";
|
|
89
|
+
else if (typeof (facts = lookup(r.provider)) === "string")
|
|
90
|
+
why = facts;
|
|
91
|
+
if (why)
|
|
92
|
+
by_reason[why]++;
|
|
93
|
+
else
|
|
94
|
+
measured.push({ r, t: t[i], facts: facts });
|
|
95
|
+
}
|
|
96
|
+
const unmeasured = records.length - measured.length;
|
|
97
|
+
if (measured.length < MIN_CALLS)
|
|
98
|
+
return { ok: false, reason: "too_few_calls", calls: records.length, unmeasured, unmeasured_by_reason: by_reason };
|
|
99
|
+
// E and S.
|
|
100
|
+
const root = { seen: Number.NEGATIVE_INFINITY, next: new Map() };
|
|
101
|
+
const convs = new Set();
|
|
102
|
+
let cachedSum = 0;
|
|
103
|
+
let reusableSum = 0;
|
|
104
|
+
let contStable = 0;
|
|
105
|
+
let contPrompt = 0;
|
|
106
|
+
for (const { r, t: now, facts } of measured) {
|
|
107
|
+
const nodes = r.ids.nodes;
|
|
108
|
+
const chars = r.node_chars;
|
|
109
|
+
const ttlMs = facts.ttl_seconds > 0 ? facts.ttl_seconds * 1000 : Number.POSITIVE_INFINITY;
|
|
110
|
+
// Walk the shared prefix. `deepest` is the structural match (any age). A shallower entry was
|
|
111
|
+
// seen no earlier than a deeper one, so once an entry is outside the lifetime, `shared` stops.
|
|
112
|
+
let deepest = -1;
|
|
113
|
+
let shared = -1;
|
|
114
|
+
let node = root;
|
|
115
|
+
for (let k = 0; k < nodes.length; k++) {
|
|
116
|
+
const child = node.next.get(nodes[k]);
|
|
117
|
+
if (!child)
|
|
118
|
+
break;
|
|
119
|
+
deepest = k;
|
|
120
|
+
if (shared === k - 1 && now - child.seen <= ttlMs)
|
|
121
|
+
shared = k;
|
|
122
|
+
node = child;
|
|
123
|
+
}
|
|
124
|
+
const estimate = (i) => i < 0 ? 0 : cap(facts, Math.round((r.prompt_tokens * chars[i]) / chars[chars.length - 1]));
|
|
125
|
+
const reusable = estimate(shared);
|
|
126
|
+
cachedSum += r.cached_tokens;
|
|
127
|
+
reusableSum += reusable;
|
|
128
|
+
const conv = r.ids.conv;
|
|
129
|
+
if (conv !== null && conv !== undefined) {
|
|
130
|
+
if (convs.has(conv)) {
|
|
131
|
+
contStable += estimate(deepest);
|
|
132
|
+
contPrompt += r.prompt_tokens;
|
|
133
|
+
}
|
|
134
|
+
else
|
|
135
|
+
convs.add(conv);
|
|
136
|
+
}
|
|
137
|
+
// Record this request's prefixes as seen now.
|
|
138
|
+
node = root;
|
|
139
|
+
for (const id of nodes) {
|
|
140
|
+
let child = node.next.get(id);
|
|
141
|
+
if (!child)
|
|
142
|
+
node.next.set(id, (child = { seen: now, next: new Map() }));
|
|
143
|
+
else
|
|
144
|
+
child.seen = Math.max(child.seen, now);
|
|
145
|
+
node = child;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const E = reusableSum > 0 ? Math.min(1, Math.max(0, cachedSum / reusableSum)) : 1;
|
|
149
|
+
const S = contPrompt > 0 ? contStable / contPrompt : 1;
|
|
150
|
+
// G, over every record in time order.
|
|
151
|
+
const lastSeen = new Set();
|
|
152
|
+
let wasted = 0;
|
|
153
|
+
let output = 0;
|
|
154
|
+
for (const i of order) {
|
|
155
|
+
const r = records[i];
|
|
156
|
+
output += r.output_tokens;
|
|
157
|
+
const nodes = r.ids && Array.isArray(r.ids.nodes) ? r.ids.nodes : [];
|
|
158
|
+
// A failed call neither repeats nor seeds the repeat rule: retrying it is correct (LP-GE-05).
|
|
159
|
+
const key = nodes.length && r.finish !== "error" ? JSON.stringify([nodes[nodes.length - 1], r.params]) : null;
|
|
160
|
+
const repeat = key !== null && lastSeen.has(key);
|
|
161
|
+
if (key !== null)
|
|
162
|
+
lastSeen.add(key);
|
|
163
|
+
const j = r.flags?.retry_of;
|
|
164
|
+
const target = typeof j === "number" && Number.isInteger(j) && j >= 0 && j < i ? records[j] : undefined;
|
|
165
|
+
const retryOfTruncation = target !== undefined && target.finish === "length" && target.params === r.params;
|
|
166
|
+
if (repeat || retryOfTruncation || r.flags?.parse_failed === true)
|
|
167
|
+
wasted += r.output_tokens;
|
|
168
|
+
}
|
|
169
|
+
const G = output > 0 ? wasted / output : 0;
|
|
170
|
+
// Head churn (information only).
|
|
171
|
+
const heads = new Set();
|
|
172
|
+
const conversations = new Set();
|
|
173
|
+
for (const r of records) {
|
|
174
|
+
if (!r.ids)
|
|
175
|
+
continue;
|
|
176
|
+
heads.add(r.ids.head);
|
|
177
|
+
if (r.ids.conv !== null && r.ids.conv !== undefined)
|
|
178
|
+
conversations.add(r.ids.conv);
|
|
179
|
+
}
|
|
180
|
+
const inputs = { E, S, G };
|
|
181
|
+
return {
|
|
182
|
+
ok: true,
|
|
183
|
+
score: scoreFrom(inputs),
|
|
184
|
+
inputs,
|
|
185
|
+
calls: records.length,
|
|
186
|
+
unmeasured,
|
|
187
|
+
unmeasured_by_reason: by_reason,
|
|
188
|
+
estimate: "char-share",
|
|
189
|
+
heads: { distinct_head: heads.size, conversations: conversations.size },
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
export type Saves = "prefill" | "generation" | "both";
|
|
2
|
+
export type Severity = "high" | "medium" | "low";
|
|
3
|
+
/** `file` of a finding that lives outside the repository (an engine's launch flags, a gateway's config). */
|
|
4
|
+
export declare const EXTERNAL = "<external>";
|
|
5
|
+
export interface Finding {
|
|
6
|
+
rule: string;
|
|
7
|
+
/** A path relative to the project root, or `<external>`. */
|
|
8
|
+
file: string;
|
|
9
|
+
/** The line the fix changes; 0 for an `<external>` finding with no line. */
|
|
10
|
+
line: number;
|
|
11
|
+
saves: Saves;
|
|
12
|
+
severity: Severity;
|
|
13
|
+
share?: number;
|
|
14
|
+
fixed?: boolean;
|
|
15
|
+
/** `needs-facts`: whether the finding holds depends on a fact not known yet (`confirm` names it). */
|
|
16
|
+
status?: "needs-facts";
|
|
17
|
+
/** Free text: where an `<external>` finding lives, for example "engine launch flags". Required for `<external>`. */
|
|
18
|
+
where?: string;
|
|
19
|
+
/** The fact that would confirm or dismiss the finding. Required with `status: "needs-facts"`. */
|
|
20
|
+
confirm?: string;
|
|
21
|
+
/** Plain-English explanation for the report and the page (each at most 600 characters). */
|
|
22
|
+
problem?: string;
|
|
23
|
+
change?: string;
|
|
24
|
+
why?: string;
|
|
25
|
+
/** The estimate as words, for example "about 138k tokens per 1,000 calls". */
|
|
26
|
+
estimate?: string;
|
|
27
|
+
assumptions?: string;
|
|
28
|
+
verify?: string;
|
|
29
|
+
/** The model this finding's calls use: the key into `prices:` in leanprompt.yaml. */
|
|
30
|
+
model?: string;
|
|
31
|
+
/** Tokens this finding loses per 1,000 calls of the whole app, by how they are billed (see TokensLost). */
|
|
32
|
+
tokens_per_1k?: TokensLost;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Tokens lost per 1,000 calls of the whole app. `prompt`: prompt tokens sent that need not be sent at all
|
|
36
|
+
* (a retry, a repeated context), billed at the full input price. `uncached`: prompt tokens the cache could
|
|
37
|
+
* have served and did not, billed at the input price less the cached-input price. `output`: output tokens
|
|
38
|
+
* thrown away. `measured_calls`: set when the numbers come from a usage log of that many calls.
|
|
39
|
+
*/
|
|
40
|
+
export interface TokensLost {
|
|
41
|
+
prompt?: number;
|
|
42
|
+
uncached?: number;
|
|
43
|
+
output?: number;
|
|
44
|
+
measured_calls?: number;
|
|
45
|
+
}
|
|
46
|
+
/** The audit's assumed average call, for the share of the bill a fix saves. */
|
|
47
|
+
export interface AverageCall {
|
|
48
|
+
prompt_tokens: number;
|
|
49
|
+
output_tokens: number;
|
|
50
|
+
}
|
|
51
|
+
/** The plain-English text fields of a finding, and their length limit. */
|
|
52
|
+
export declare const TEXT_FIELDS: readonly ["problem", "change", "why", "estimate", "assumptions", "verify"];
|
|
53
|
+
export declare const TEXT_MAX = 600;
|
|
54
|
+
/** A finding the report lists under "Open questions": outside the repository, or waiting on a fact. */
|
|
55
|
+
export declare const isOpenQuestion: (f: Finding) => boolean;
|
|
56
|
+
/** `.leanprompt/weights.json`, written by `calibrate`. */
|
|
57
|
+
export interface Weights {
|
|
58
|
+
v: 1;
|
|
59
|
+
shares: {
|
|
60
|
+
high: number;
|
|
61
|
+
medium: number;
|
|
62
|
+
low: number;
|
|
63
|
+
};
|
|
64
|
+
k_prefill: number;
|
|
65
|
+
k_gen: number;
|
|
66
|
+
source: "real" | "synthetic";
|
|
67
|
+
calls: number;
|
|
68
|
+
date: string;
|
|
69
|
+
}
|
|
70
|
+
export interface StaticScore {
|
|
71
|
+
score: number;
|
|
72
|
+
inputs: {
|
|
73
|
+
E: number;
|
|
74
|
+
S: number;
|
|
75
|
+
G: number;
|
|
76
|
+
};
|
|
77
|
+
weights: "default" | "calibrated";
|
|
78
|
+
/** Of the `of` findings scored (not fixed), how many had no `share` and used the severity default. */
|
|
79
|
+
default_shares: {
|
|
80
|
+
used: number;
|
|
81
|
+
of: number;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/** The score formula shared by the static and measured scores: floor(100 x (0.6 x E x S + 0.4 x (1 - G))). */
|
|
85
|
+
export declare function scoreFrom({ E, S, G }: {
|
|
86
|
+
E: number;
|
|
87
|
+
S: number;
|
|
88
|
+
G: number;
|
|
89
|
+
}): number;
|
|
90
|
+
/**
|
|
91
|
+
* Parse `.leanprompt/findings.json`. Invalid entries are dropped and reported in `errors`;
|
|
92
|
+
* `ruleIds` is the set of known rule ids (see `loadRuleIds`).
|
|
93
|
+
*/
|
|
94
|
+
export declare function parseFindings(text: string, ruleIds: ReadonlySet<string>): {
|
|
95
|
+
findings: Finding[];
|
|
96
|
+
errors: string[];
|
|
97
|
+
average_call?: AverageCall;
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Static score: floor(100 x (0.6 x E x S + 0.4 x (1 - G))).
|
|
101
|
+
* E x S = product of (1 - share) over prefill findings (reported as E, with S = 1);
|
|
102
|
+
* G = 1 - product of (1 - share) over generation findings. `both` counts on both sides;
|
|
103
|
+
* `fixed` findings are skipped. `<external>` and `needs-facts` findings count like any other.
|
|
104
|
+
* Pure: filtering by the profile's `ignore:` is the caller's job.
|
|
105
|
+
*
|
|
106
|
+
* Share per finding: an explicit `share` (set by the auditor) is used as is. Otherwise the
|
|
107
|
+
* severity default (high 0.5, medium 0.2, low 0.05); with `weights`, that default becomes
|
|
108
|
+
* min(0.95, default x k_prefill) on the prefill side or min(0.95, default x k_gen) on the
|
|
109
|
+
* generation side. k does NOT scale an explicit share: calibration corrects the guessed
|
|
110
|
+
* defaults, not a share the auditor stated.
|
|
111
|
+
*/
|
|
112
|
+
export declare function staticScore(findings: readonly Finding[], weights?: Weights): StaticScore;
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/** `file` of a finding that lives outside the repository (an engine's launch flags, a gateway's config). */
|
|
2
|
+
export const EXTERNAL = "<external>";
|
|
3
|
+
/** The plain-English text fields of a finding, and their length limit. */
|
|
4
|
+
export const TEXT_FIELDS = ["problem", "change", "why", "estimate", "assumptions", "verify"];
|
|
5
|
+
export const TEXT_MAX = 600;
|
|
6
|
+
/** A finding the report lists under "Open questions": outside the repository, or waiting on a fact. */
|
|
7
|
+
export const isOpenQuestion = (f) => f.file === EXTERNAL || f.status === "needs-facts";
|
|
8
|
+
const DEFAULT_SHARE = { high: 0.5, medium: 0.2, low: 0.05 };
|
|
9
|
+
const SHARE_CAP = 0.95;
|
|
10
|
+
const SAVES = ["prefill", "generation", "both"];
|
|
11
|
+
const SEVERITY = ["high", "medium", "low"];
|
|
12
|
+
/** The score formula shared by the static and measured scores: floor(100 x (0.6 x E x S + 0.4 x (1 - G))). */
|
|
13
|
+
export function scoreFrom({ E, S, G }) {
|
|
14
|
+
// The epsilon guards against 91.99999... from float error before floor.
|
|
15
|
+
return Math.floor(100 * (0.6 * E * S + 0.4 * (1 - G)) + 1e-9);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Parse `.leanprompt/findings.json`. Invalid entries are dropped and reported in `errors`;
|
|
19
|
+
* `ruleIds` is the set of known rule ids (see `loadRuleIds`).
|
|
20
|
+
*/
|
|
21
|
+
export function parseFindings(text, ruleIds) {
|
|
22
|
+
const findings = [];
|
|
23
|
+
const errors = [];
|
|
24
|
+
let doc;
|
|
25
|
+
try {
|
|
26
|
+
doc = JSON.parse(text);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return { findings, errors: ["findings file is not valid JSON"] };
|
|
30
|
+
}
|
|
31
|
+
if (!doc || typeof doc !== "object" || Array.isArray(doc))
|
|
32
|
+
return { findings, errors: ["findings file must be an object"] };
|
|
33
|
+
const d = doc;
|
|
34
|
+
if (d.v !== 1)
|
|
35
|
+
errors.push("v must be 1");
|
|
36
|
+
let average_call;
|
|
37
|
+
if (d.average_call !== undefined) {
|
|
38
|
+
const a = d.average_call;
|
|
39
|
+
const okNum = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
40
|
+
if (a && typeof a === "object" && !Array.isArray(a) && okNum(a.prompt_tokens) && okNum(a.output_tokens) && Object.keys(a).length === 2) {
|
|
41
|
+
average_call = { prompt_tokens: a.prompt_tokens, output_tokens: a.output_tokens };
|
|
42
|
+
}
|
|
43
|
+
else
|
|
44
|
+
errors.push("average_call must be {prompt_tokens, output_tokens}, both positive numbers");
|
|
45
|
+
}
|
|
46
|
+
if (!Array.isArray(d.findings)) {
|
|
47
|
+
errors.push("findings must be an array");
|
|
48
|
+
return { findings, errors, ...(average_call ? { average_call } : {}) };
|
|
49
|
+
}
|
|
50
|
+
d.findings.forEach((raw, i) => {
|
|
51
|
+
const at = `findings[${i}]`;
|
|
52
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
53
|
+
return void errors.push(`${at}: must be an object`);
|
|
54
|
+
const r = raw;
|
|
55
|
+
const bad = (msg) => void errors.push(`${at}: ${msg}`);
|
|
56
|
+
if (typeof r.rule !== "string" || !ruleIds.has(r.rule))
|
|
57
|
+
return bad(`unknown rule ${String(r.rule)}`);
|
|
58
|
+
if (typeof r.file !== "string" || !r.file)
|
|
59
|
+
return bad("file must be a non-empty string");
|
|
60
|
+
const external = r.file === EXTERNAL;
|
|
61
|
+
if (external) {
|
|
62
|
+
if (r.line !== undefined && (typeof r.line !== "number" || !Number.isInteger(r.line) || r.line < 0))
|
|
63
|
+
return bad("line must be 0 or a positive integer");
|
|
64
|
+
}
|
|
65
|
+
else if (typeof r.line !== "number" || !Number.isInteger(r.line) || r.line < 1)
|
|
66
|
+
return bad("line must be a positive integer");
|
|
67
|
+
if (typeof r.saves !== "string" || !SAVES.includes(r.saves))
|
|
68
|
+
return bad(`bad saves ${String(r.saves)}`);
|
|
69
|
+
if (typeof r.severity !== "string" || !SEVERITY.includes(r.severity))
|
|
70
|
+
return bad(`bad severity ${String(r.severity)}`);
|
|
71
|
+
if (r.share !== undefined && (typeof r.share !== "number" || !(r.share >= 0 && r.share <= 1)))
|
|
72
|
+
return bad("share must be a number in [0, 1]");
|
|
73
|
+
if (r.fixed !== undefined && typeof r.fixed !== "boolean")
|
|
74
|
+
return bad("fixed must be a boolean");
|
|
75
|
+
const text = (v) => typeof v === "string" && v.trim() !== "";
|
|
76
|
+
if (external && !text(r.where))
|
|
77
|
+
return bad("a finding in <external> needs `where` (for example \"engine launch flags\")");
|
|
78
|
+
for (const k of ["where", "confirm"])
|
|
79
|
+
if (r[k] !== undefined && !text(r[k]))
|
|
80
|
+
return bad(`${k} must be a non-empty string`);
|
|
81
|
+
if (r.status !== undefined && r.status !== "needs-facts")
|
|
82
|
+
return bad(`status must be needs-facts, not ${String(r.status)}`);
|
|
83
|
+
if (r.status === "needs-facts" && r.confirm === undefined)
|
|
84
|
+
return bad("a needs-facts finding needs `confirm`: the fact that would confirm or dismiss it");
|
|
85
|
+
for (const k of TEXT_FIELDS) {
|
|
86
|
+
const v = r[k];
|
|
87
|
+
if (v !== undefined && (!text(v) || v.length > TEXT_MAX))
|
|
88
|
+
return bad(`${k} must be a non-empty string of at most ${TEXT_MAX} characters`);
|
|
89
|
+
}
|
|
90
|
+
if (r.model !== undefined && !text(r.model))
|
|
91
|
+
return bad("model must be a non-empty string");
|
|
92
|
+
let tokens;
|
|
93
|
+
if (r.tokens_per_1k !== undefined) {
|
|
94
|
+
const t = r.tokens_per_1k;
|
|
95
|
+
if (!t || typeof t !== "object" || Array.isArray(t))
|
|
96
|
+
return bad("tokens_per_1k must be an object");
|
|
97
|
+
const keys = Object.keys(t);
|
|
98
|
+
if (keys.length === 0)
|
|
99
|
+
return bad("tokens_per_1k needs prompt, uncached or output");
|
|
100
|
+
tokens = {};
|
|
101
|
+
for (const k of keys) {
|
|
102
|
+
const v = t[k];
|
|
103
|
+
if (k === "measured_calls") {
|
|
104
|
+
if (typeof v !== "number" || !Number.isInteger(v) || v < 1)
|
|
105
|
+
return bad("tokens_per_1k.measured_calls must be a positive integer");
|
|
106
|
+
tokens.measured_calls = v;
|
|
107
|
+
}
|
|
108
|
+
else if (k === "prompt" || k === "uncached" || k === "output") {
|
|
109
|
+
if (typeof v !== "number" || !Number.isFinite(v) || v < 0)
|
|
110
|
+
return bad(`tokens_per_1k.${k} must be a number >= 0`);
|
|
111
|
+
tokens[k] = v;
|
|
112
|
+
}
|
|
113
|
+
else
|
|
114
|
+
return bad(`tokens_per_1k: unknown key ${k}`);
|
|
115
|
+
}
|
|
116
|
+
if (tokens.prompt === undefined && tokens.uncached === undefined && tokens.output === undefined)
|
|
117
|
+
return bad("tokens_per_1k needs prompt, uncached or output");
|
|
118
|
+
}
|
|
119
|
+
const out = { rule: r.rule, file: r.file, line: r.line ?? 0, saves: r.saves, severity: r.severity };
|
|
120
|
+
if (r.share !== undefined)
|
|
121
|
+
out.share = r.share;
|
|
122
|
+
if (r.fixed !== undefined)
|
|
123
|
+
out.fixed = r.fixed;
|
|
124
|
+
if (r.status !== undefined)
|
|
125
|
+
out.status = "needs-facts";
|
|
126
|
+
if (r.where !== undefined)
|
|
127
|
+
out.where = r.where;
|
|
128
|
+
if (r.confirm !== undefined)
|
|
129
|
+
out.confirm = r.confirm;
|
|
130
|
+
for (const k of TEXT_FIELDS)
|
|
131
|
+
if (r[k] !== undefined)
|
|
132
|
+
out[k] = r[k];
|
|
133
|
+
if (r.model !== undefined)
|
|
134
|
+
out.model = r.model;
|
|
135
|
+
if (tokens)
|
|
136
|
+
out.tokens_per_1k = tokens;
|
|
137
|
+
findings.push(out);
|
|
138
|
+
});
|
|
139
|
+
return { findings, errors, ...(average_call ? { average_call } : {}) };
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Static score: floor(100 x (0.6 x E x S + 0.4 x (1 - G))).
|
|
143
|
+
* E x S = product of (1 - share) over prefill findings (reported as E, with S = 1);
|
|
144
|
+
* G = 1 - product of (1 - share) over generation findings. `both` counts on both sides;
|
|
145
|
+
* `fixed` findings are skipped. `<external>` and `needs-facts` findings count like any other.
|
|
146
|
+
* Pure: filtering by the profile's `ignore:` is the caller's job.
|
|
147
|
+
*
|
|
148
|
+
* Share per finding: an explicit `share` (set by the auditor) is used as is. Otherwise the
|
|
149
|
+
* severity default (high 0.5, medium 0.2, low 0.05); with `weights`, that default becomes
|
|
150
|
+
* min(0.95, default x k_prefill) on the prefill side or min(0.95, default x k_gen) on the
|
|
151
|
+
* generation side. k does NOT scale an explicit share: calibration corrects the guessed
|
|
152
|
+
* defaults, not a share the auditor stated.
|
|
153
|
+
*/
|
|
154
|
+
export function staticScore(findings, weights) {
|
|
155
|
+
let es = 1;
|
|
156
|
+
let keepG = 1;
|
|
157
|
+
const default_shares = { used: 0, of: 0 };
|
|
158
|
+
for (const f of findings) {
|
|
159
|
+
if (f.fixed)
|
|
160
|
+
continue;
|
|
161
|
+
default_shares.of++;
|
|
162
|
+
if (f.share === undefined)
|
|
163
|
+
default_shares.used++;
|
|
164
|
+
const share = (k) => f.share ?? (weights ? Math.min(SHARE_CAP, DEFAULT_SHARE[f.severity] * k) : DEFAULT_SHARE[f.severity]);
|
|
165
|
+
if (f.saves !== "generation")
|
|
166
|
+
es *= 1 - share(weights?.k_prefill ?? 1);
|
|
167
|
+
if (f.saves !== "prefill")
|
|
168
|
+
keepG *= 1 - share(weights?.k_gen ?? 1);
|
|
169
|
+
}
|
|
170
|
+
const inputs = { E: es, S: 1, G: 1 - keepG };
|
|
171
|
+
return { score: scoreFrom(inputs), inputs, weights: weights ? "calibrated" : "default", default_shares };
|
|
172
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type RuleInfo } from "../lint/rules.js";
|
|
2
|
+
import { type Profile } from "../profile.js";
|
|
3
|
+
import { type UnmeasuredReason } from "./measured.js";
|
|
4
|
+
import { type Finding, type Weights } from "./static.js";
|
|
5
|
+
export type Kind = "measured" | "static";
|
|
6
|
+
export declare const PACKAGE_ROOT: string;
|
|
7
|
+
export declare const USAGE_FILE = ".leanprompt/usage.jsonl";
|
|
8
|
+
export declare const FINDINGS_FILE = ".leanprompt/findings.json";
|
|
9
|
+
export declare const WEIGHTS_FILE = ".leanprompt/weights.json";
|
|
10
|
+
/** shields.io colour for a score. Static scores are estimates from an audit, so they are always grey. */
|
|
11
|
+
export declare function badgeColor(score: number, kind: Kind): string;
|
|
12
|
+
/** Read and validate `.leanprompt/weights.json`. Null when absent; throws naming the file when invalid. */
|
|
13
|
+
export declare function loadWeights(file: string): Weights | null;
|
|
14
|
+
/** `no_usage 60, no_ids 3`, nonzero reasons only. */
|
|
15
|
+
export declare function formatReasons(byReason: Record<UnmeasuredReason, number>): string;
|
|
16
|
+
/** Drop findings the profile's `ignore:` list names (same rule and file). */
|
|
17
|
+
export declare function filterIgnored(findings: Finding[], profile: Profile | null | undefined): Finding[];
|
|
18
|
+
/** Escape for a GitHub Actions workflow command: the message, and (with `property`) a key=value property. */
|
|
19
|
+
export declare function ghEscape(s: string, property?: boolean): string;
|
|
20
|
+
/**
|
|
21
|
+
* One `::warning` line per open finding (not fixed, not on the ignore list), for GitHub Actions to show
|
|
22
|
+
* on the file and line. An `<external>` finding, or one with no line, is annotated without them.
|
|
23
|
+
*/
|
|
24
|
+
export declare function githubAnnotations(findings: Finding[], rules: Map<string, RuleInfo>): string[];
|
|
25
|
+
/**
|
|
26
|
+
* `leanprompt score [--measured [<usage.jsonl>]] [--static [<findings.json>]] [--dir <project>]`.
|
|
27
|
+
* A bare `--measured` or `--static` means the project's own `.leanprompt/usage.jsonl` or `.leanprompt/findings.json`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function scoreCommand(args: string[]): Promise<number>;
|