leanprompt 0.0.0-stage → 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.
Files changed (157) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-DOCS +396 -0
  3. package/NOTICE +11 -0
  4. package/README.md +89 -2
  5. package/cli/dist/detect.d.ts +23 -0
  6. package/cli/dist/detect.js +219 -0
  7. package/cli/dist/evalAudit.d.ts +32 -0
  8. package/cli/dist/evalAudit.js +161 -0
  9. package/cli/dist/facts.d.ts +14 -0
  10. package/cli/dist/facts.js +43 -0
  11. package/cli/dist/forms.d.ts +23 -0
  12. package/cli/dist/forms.js +199 -0
  13. package/cli/dist/frontmatter.d.ts +10 -0
  14. package/cli/dist/frontmatter.js +32 -0
  15. package/cli/dist/help.d.ts +27 -0
  16. package/cli/dist/help.js +118 -0
  17. package/cli/dist/init.d.ts +78 -0
  18. package/cli/dist/init.js +358 -0
  19. package/cli/dist/install.d.ts +20 -0
  20. package/cli/dist/install.js +225 -0
  21. package/cli/dist/isMain.d.ts +6 -0
  22. package/cli/dist/isMain.js +18 -0
  23. package/cli/dist/lesson.d.ts +16 -0
  24. package/cli/dist/lesson.js +205 -0
  25. package/cli/dist/lint/facts.d.ts +7 -0
  26. package/cli/dist/lint/facts.js +163 -0
  27. package/cli/dist/lint/numbers.d.ts +26 -0
  28. package/cli/dist/lint/numbers.js +163 -0
  29. package/cli/dist/lint/rules.d.ts +20 -0
  30. package/cli/dist/lint/rules.js +170 -0
  31. package/cli/dist/log/logger.d.ts +49 -0
  32. package/cli/dist/log/logger.js +148 -0
  33. package/cli/dist/log/record.d.ts +56 -0
  34. package/cli/dist/log/record.js +117 -0
  35. package/cli/dist/main.d.ts +6 -0
  36. package/cli/dist/main.js +67 -0
  37. package/cli/dist/profile.d.ts +93 -0
  38. package/cli/dist/profile.js +372 -0
  39. package/cli/dist/report/cost.d.ts +55 -0
  40. package/cli/dist/report/cost.js +151 -0
  41. package/cli/dist/report/html.d.ts +81 -0
  42. package/cli/dist/report/html.js +555 -0
  43. package/cli/dist/report/template.html +269 -0
  44. package/cli/dist/score/calibrate.d.ts +65 -0
  45. package/cli/dist/score/calibrate.js +213 -0
  46. package/cli/dist/score/measured.d.ts +66 -0
  47. package/cli/dist/score/measured.js +191 -0
  48. package/cli/dist/score/static.d.ts +112 -0
  49. package/cli/dist/score/static.js +172 -0
  50. package/cli/dist/score/write.d.ts +29 -0
  51. package/cli/dist/score/write.js +247 -0
  52. package/forms/AGENTS.block.md +25 -0
  53. package/forms/opencode/commands/leanprompt-audit.md +10 -0
  54. package/forms/opencode/commands/leanprompt.md +8 -0
  55. package/forms/skills/generation-economy/SKILL.md +89 -0
  56. package/forms/skills/generation-economy/rules/LP-GE-01.md +93 -0
  57. package/forms/skills/generation-economy/rules/LP-GE-02.md +82 -0
  58. package/forms/skills/generation-economy/rules/LP-GE-03.md +87 -0
  59. package/forms/skills/generation-economy/rules/LP-GE-04.md +118 -0
  60. package/forms/skills/generation-economy/rules/LP-GE-05.md +84 -0
  61. package/forms/skills/generation-economy/rules/LP-GE-06.md +76 -0
  62. package/forms/skills/generation-economy/rules/LP-GE-07.md +84 -0
  63. package/forms/skills/generation-economy/rules/LP-GE-08.md +71 -0
  64. package/forms/skills/generation-economy/rules/LP-GE-09.md +79 -0
  65. package/forms/skills/generation-economy/rules/LP-GE-10.md +104 -0
  66. package/forms/skills/leanprompt/SKILL.md +48 -0
  67. package/forms/skills/leanprompt/fix.md +15 -0
  68. package/forms/skills/leanprompt/init.md +30 -0
  69. package/forms/skills/llm-call-audit/SKILL.md +169 -0
  70. package/forms/skills/llm-call-audit/call-shapes.md +99 -0
  71. package/forms/skills/llm-call-audit/presenting.md +72 -0
  72. package/forms/skills/llm-call-audit/report-template.md +113 -0
  73. package/forms/skills/lmwarden/SKILL.md +97 -0
  74. package/forms/skills/lmwarden/rules/LP-LW-01.md +73 -0
  75. package/forms/skills/lmwarden/rules/LP-LW-02.md +78 -0
  76. package/forms/skills/lmwarden/rules/LP-LW-03.md +73 -0
  77. package/forms/skills/measure-loop/SKILL.md +155 -0
  78. package/forms/skills/measure-loop/templates/stable-head.template.ts +38 -0
  79. package/forms/skills/measure-loop/templates/stable_head_template.py +40 -0
  80. package/forms/skills/prefill-cache/SKILL.md +66 -0
  81. package/forms/skills/prefill-cache/rules/LP-PC-01.md +103 -0
  82. package/forms/skills/prefill-cache/rules/LP-PC-02.md +80 -0
  83. package/forms/skills/prefill-cache/rules/LP-PC-03.md +75 -0
  84. package/forms/skills/prefill-cache/rules/LP-PC-04.md +79 -0
  85. package/forms/skills/prefill-cache/rules/LP-PC-05.md +68 -0
  86. package/forms/skills/prefill-cache/rules/LP-PC-06.md +71 -0
  87. package/forms/skills/prefill-cache/rules/LP-PC-07.md +97 -0
  88. package/forms/skills/prefill-cache/rules/LP-PC-08.md +67 -0
  89. package/forms/skills/prefill-cache/rules/LP-PC-09.md +75 -0
  90. package/forms/skills/prefill-cache/rules/LP-PC-10.md +76 -0
  91. package/forms/skills/prefill-cache/rules/LP-PC-11.md +72 -0
  92. package/forms/skills/prefill-cache/rules/LP-PC-12.md +73 -0
  93. package/forms/skills/prompt-diet/SKILL.md +69 -0
  94. package/forms/skills/prompt-diet/rules/LP-PD-01.md +79 -0
  95. package/forms/skills/prompt-diet/rules/LP-PD-02.md +73 -0
  96. package/forms/skills/prompt-diet/rules/LP-PD-03.md +65 -0
  97. package/forms/skills/prompt-diet/rules/LP-PD-04.md +77 -0
  98. package/forms/skills/prompt-diet/rules/LP-PD-05.md +71 -0
  99. package/forms/skills/prompt-diet/rules/LP-PD-06.md +68 -0
  100. package/models/anthropic-thinking.md +38 -0
  101. package/models/openai-reasoning.md +35 -0
  102. package/models/qwen.md +34 -0
  103. package/package.json +32 -4
  104. package/providers/anthropic.md +83 -0
  105. package/providers/deepinfra.md +46 -0
  106. package/providers/gemini.md +61 -0
  107. package/providers/openai.md +73 -0
  108. package/providers/openrouter.md +66 -0
  109. package/providers/sglang.md +41 -0
  110. package/providers/vllm.md +52 -0
  111. package/runtimes/http-clients.md +20 -0
  112. package/skills/_template/RULE.md +31 -0
  113. package/skills/generation-economy/SKILL.md +88 -0
  114. package/skills/generation-economy/rules/LP-GE-01.md +92 -0
  115. package/skills/generation-economy/rules/LP-GE-02.md +81 -0
  116. package/skills/generation-economy/rules/LP-GE-03.md +86 -0
  117. package/skills/generation-economy/rules/LP-GE-04.md +117 -0
  118. package/skills/generation-economy/rules/LP-GE-05.md +83 -0
  119. package/skills/generation-economy/rules/LP-GE-06.md +75 -0
  120. package/skills/generation-economy/rules/LP-GE-07.md +83 -0
  121. package/skills/generation-economy/rules/LP-GE-08.md +70 -0
  122. package/skills/generation-economy/rules/LP-GE-09.md +78 -0
  123. package/skills/generation-economy/rules/LP-GE-10.md +103 -0
  124. package/skills/leanprompt/SKILL.md +47 -0
  125. package/skills/leanprompt/fix.md +14 -0
  126. package/skills/leanprompt/init.md +29 -0
  127. package/skills/llm-call-audit/SKILL.md +168 -0
  128. package/skills/llm-call-audit/call-shapes.md +98 -0
  129. package/skills/llm-call-audit/presenting.md +71 -0
  130. package/skills/llm-call-audit/report-template.md +112 -0
  131. package/skills/lmwarden/SKILL.md +96 -0
  132. package/skills/lmwarden/rules/LP-LW-01.md +72 -0
  133. package/skills/lmwarden/rules/LP-LW-02.md +77 -0
  134. package/skills/lmwarden/rules/LP-LW-03.md +72 -0
  135. package/skills/measure-loop/SKILL.md +154 -0
  136. package/skills/measure-loop/templates/stable-head.template.ts +38 -0
  137. package/skills/measure-loop/templates/stable_head_template.py +40 -0
  138. package/skills/prefill-cache/SKILL.md +65 -0
  139. package/skills/prefill-cache/rules/LP-PC-01.md +102 -0
  140. package/skills/prefill-cache/rules/LP-PC-02.md +79 -0
  141. package/skills/prefill-cache/rules/LP-PC-03.md +74 -0
  142. package/skills/prefill-cache/rules/LP-PC-04.md +78 -0
  143. package/skills/prefill-cache/rules/LP-PC-05.md +67 -0
  144. package/skills/prefill-cache/rules/LP-PC-06.md +70 -0
  145. package/skills/prefill-cache/rules/LP-PC-07.md +96 -0
  146. package/skills/prefill-cache/rules/LP-PC-08.md +66 -0
  147. package/skills/prefill-cache/rules/LP-PC-09.md +74 -0
  148. package/skills/prefill-cache/rules/LP-PC-10.md +75 -0
  149. package/skills/prefill-cache/rules/LP-PC-11.md +71 -0
  150. package/skills/prefill-cache/rules/LP-PC-12.md +72 -0
  151. package/skills/prompt-diet/SKILL.md +68 -0
  152. package/skills/prompt-diet/rules/LP-PD-01.md +78 -0
  153. package/skills/prompt-diet/rules/LP-PD-02.md +72 -0
  154. package/skills/prompt-diet/rules/LP-PD-03.md +64 -0
  155. package/skills/prompt-diet/rules/LP-PD-04.md +76 -0
  156. package/skills/prompt-diet/rules/LP-PD-05.md +70 -0
  157. package/skills/prompt-diet/rules/LP-PD-06.md +67 -0
@@ -0,0 +1,81 @@
1
+ import { type Profile } from "../profile.js";
2
+ import { type AverageCall, type Finding } from "../score/static.js";
3
+ export type { RuleInfo } from "../lint/rules.js";
4
+ export { loadRules } from "../lint/rules.js";
5
+ import type { RuleInfo } from "../lint/rules.js";
6
+ /** The fields of `.leanprompt/score.json` the page uses. Everything is optional: the file is read defensively. */
7
+ export interface ScoreFile {
8
+ score?: number;
9
+ kind?: string;
10
+ weights?: string;
11
+ inputs?: {
12
+ E?: number;
13
+ S?: number;
14
+ G?: number;
15
+ };
16
+ calls?: number;
17
+ unmeasured?: number;
18
+ diagnostics?: {
19
+ estimate?: string;
20
+ default_shares?: number;
21
+ findings?: number;
22
+ };
23
+ message?: string;
24
+ color?: string;
25
+ date?: string;
26
+ leanprompt?: string;
27
+ }
28
+ export interface ReportInput {
29
+ findings: Finding[];
30
+ score: ScoreFile | null;
31
+ rules: Map<string, RuleInfo>;
32
+ project: string;
33
+ /** Findings dropped by the profile's `ignore:` list. */
34
+ ignored?: number;
35
+ /** leanprompt version used in pinned rule links. Defaults to this package's version. */
36
+ version?: string;
37
+ /** leanprompt.yaml, for the volume and prices behind the money estimate. */
38
+ profile?: Profile | null;
39
+ /** The audit's average call, from findings.json, for the share of the bill. */
40
+ average_call?: AverageCall;
41
+ /** Local git facts for the badge snippet. */
42
+ git?: GitInfo;
43
+ }
44
+ export declare const DEFAULT_OUT: string;
45
+ /**
46
+ * Rank: open before fixed; findings with token numbers before those without, largest first; then severity
47
+ * high to low, estimated share (when given) high to low, then file:line.
48
+ */
49
+ export declare function rankFindings(findings: Finding[]): Finding[];
50
+ /**
51
+ * Text joined after a colon reads as one sentence: lower-case its first word when that is an ordinary capitalised
52
+ * word ("When", "A"), and leave acronyms, code, names and "I" as they are ("LLM", "vLLM", "OpenAI", "Anthropic").
53
+ */
54
+ export declare function afterColon(text: string): string;
55
+ /** The finding's short title for the meter: the first sentence of its problem, or the rule's title, cut at a word. */
56
+ export declare function shortTitle(f: Finding, rules: Map<string, RuleInfo>, max?: number): string;
57
+ /** Split text after its first sentence (a full stop, question mark or colon followed by a space and a capital). */
58
+ export declare function splitLead(text: string): [string, string];
59
+ /** The block a user pastes into their coding agent: self-contained instructions plus the open findings. */
60
+ export declare function handoffText(findings: Finding[], rules: Map<string, RuleInfo>): string;
61
+ /** A short, plain message a user can send a colleague. */
62
+ export declare function shareText(findings: Finding[], score: ScoreFile | null, profile?: Profile | null): string;
63
+ /** Git facts for the badge, read locally by the command (no network). */
64
+ export interface GitInfo {
65
+ remote?: string;
66
+ branch?: string;
67
+ /** Whether `.leanprompt/score.json` is tracked by git. */
68
+ scoreTracked?: boolean;
69
+ }
70
+ /**
71
+ * The raw URL of `.leanprompt/score.json` on a public git host (GitHub, GitLab.com, Bitbucket), from
72
+ * `git remote get-url origin` and the current branch. Null for any other host, or no branch.
73
+ * Credentials in the remote URL are dropped.
74
+ */
75
+ export declare function rawScoreUrl(remote: string, branch: string): string | null;
76
+ /** One self-contained HTML document: inline CSS, one inline copy script, no network. */
77
+ export declare function renderReport(o: ReportInput): string;
78
+ /** Local git facts for the badge: the origin remote, the current branch, and whether score.json is tracked. No network. */
79
+ export declare function readGit(dir: string): GitInfo | undefined;
80
+ /** `leanprompt report --html [--out <file>] [--dir <project>]` */
81
+ export declare function reportCommand(args: string[]): Promise<number>;
@@ -0,0 +1,555 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { optionsFor } from "../help.js";
6
+ import { REPO } from "../forms.js";
7
+ import { loadRuleIds } from "../lint/rules.js";
8
+ import { loadProfile } from "../profile.js";
9
+ import { EXTERNAL, isOpenQuestion, parseFindings } from "../score/static.js";
10
+ import { costSummary, formatDollars, formatTokens } from "./cost.js";
11
+ import { filterIgnored, FINDINGS_FILE, PACKAGE_ROOT } from "../score/write.js";
12
+ export { loadRules } from "../lint/rules.js";
13
+ import { loadRules } from "../lint/rules.js";
14
+ export const DEFAULT_OUT = join(".leanprompt", "report.html");
15
+ const SCORE_FILE = join(".leanprompt", "score.json");
16
+ const TEMPLATE = new URL("./template.html", import.meta.url);
17
+ const SEV_ORDER = { high: 0, medium: 1, low: 2 };
18
+ const escapeHtml = (v) => String(v).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
19
+ const e = escapeHtml;
20
+ function packageVersion() {
21
+ return JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8")).version;
22
+ }
23
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
24
+ const fmt2 = (v) => num(v)?.toFixed(2) ?? "n/a";
25
+ function kindLabel(s) {
26
+ if (s.kind === "measured")
27
+ return "measured";
28
+ return s.weights === "calibrated" ? "static, calibrated" : "static";
29
+ }
30
+ function scoreSection(score) {
31
+ if (!score || num(score.score) === undefined) {
32
+ return `<section class="score-sec" id="s-score"><h2>Score</h2><p class="card">No score yet: run <code>npx leanprompt score</code></p></section>`;
33
+ }
34
+ const measured = score.kind === "measured";
35
+ const i = score.inputs ?? {};
36
+ let html = `<section class="score-sec" id="s-score"><h2>Score</h2><p class="prose">One number from 0 to 100 for how well this app avoids paying for the same tokens twice; higher is better. It is computed from the findings above (static) or from your usage log (measured).</p><div class="card"><div class="score"><span class="n">${e(score.score)}</span><span class="kind">${e(kindLabel(score))}</span></div>`;
37
+ html += `<dl class="inputs">`;
38
+ html += `<div><dt>E, prefill reuse</dt><dd>${e(fmt2(i.E))}</dd></div>`;
39
+ html += `<div><dt>S, prefix stability</dt><dd>${e(fmt2(i.S))}</dd></div>`;
40
+ html += `<div><dt>G, generation waste</dt><dd>${e(fmt2(i.G))}</dd></div>`;
41
+ if (measured) {
42
+ const calls = num(score.calls);
43
+ const unmeasured = num(score.unmeasured);
44
+ const measuredCalls = calls !== undefined && unmeasured !== undefined ? calls - unmeasured : undefined;
45
+ html += `<div><dt>Calls measured</dt><dd>${e(measuredCalls ?? "n/a")}</dd></div>`;
46
+ html += `<div><dt>Calls logged</dt><dd>${e(calls ?? "n/a")}</dd></div>`;
47
+ html += `<div><dt>Calls unmeasured</dt><dd>${e(num(score.unmeasured) ?? "n/a")}</dd></div>`;
48
+ }
49
+ const d = score.diagnostics ?? {};
50
+ const defaults = !measured && num(d.default_shares) !== undefined && num(d.findings) !== undefined;
51
+ if (defaults)
52
+ html += `<div><dt>Default shares</dt><dd>${e(d.default_shares)} of ${e(d.findings)}</dd></div>`;
53
+ html += `</dl>`;
54
+ if (defaults)
55
+ html += `<p class="muted">Findings scored with severity defaults, not estimates. The fewer, the more the static score says about this app.</p>`;
56
+ if (measured) {
57
+ html += `<p class="muted">Reusable tokens are estimated from the character share of each prompt part, not counted by the provider.</p>`;
58
+ }
59
+ else {
60
+ html += `<p class="muted">A static score is an estimate from the audit's findings, not a measurement.</p>`;
61
+ }
62
+ if (typeof score.date === "string")
63
+ html += `<p class="muted">Scored ${e(score.date)}.</p>`;
64
+ html += `</div></section>`;
65
+ return html;
66
+ }
67
+ /** Where a finding is, as plain text: `file:line`, or for an `<external>` one its `where` text. */
68
+ function whereText(f) {
69
+ if (f.file === EXTERNAL)
70
+ return `${f.where ?? EXTERNAL}${f.line > 0 ? ` (line ${f.line})` : ""}`;
71
+ return `${f.file}:${f.line}`;
72
+ }
73
+ /** Where a finding is, as HTML. */
74
+ function location(f) {
75
+ if (f.file === EXTERNAL)
76
+ return e(whereText(f));
77
+ return `<code>${e(whereText(f))}</code>`;
78
+ }
79
+ const tokensOf = (f) => f.tokens_per_1k ? (f.tokens_per_1k.prompt ?? 0) + (f.tokens_per_1k.uncached ?? 0) + (f.tokens_per_1k.output ?? 0) : undefined;
80
+ /**
81
+ * Rank: open before fixed; findings with token numbers before those without, largest first; then severity
82
+ * high to low, estimated share (when given) high to low, then file:line.
83
+ */
84
+ export function rankFindings(findings) {
85
+ return [...findings].sort((a, b) => Number(!!a.fixed) - Number(!!b.fixed) ||
86
+ (tokensOf(b) ?? -1) - (tokensOf(a) ?? -1) ||
87
+ SEV_ORDER[a.severity] - SEV_ORDER[b.severity] ||
88
+ (b.share ?? 0) - (a.share ?? 0) ||
89
+ (a.file < b.file ? -1 : a.file > b.file ? 1 : 0) ||
90
+ a.line - b.line);
91
+ }
92
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
93
+ const ruleTitle = (f, rules) => rules.get(f.rule)?.title ?? f.rule;
94
+ const ruleLink = (f, rules, version) => {
95
+ const r = rules.get(f.rule);
96
+ return r ? `${REPO}/blob/v${version}/skills/${r.skill}/rules/${f.rule}.md` : undefined;
97
+ };
98
+ function groups(findings) {
99
+ const ranked = rankFindings(findings);
100
+ return {
101
+ open: ranked.filter((f) => !f.fixed && !isOpenQuestion(f)),
102
+ questions: ranked.filter((f) => !f.fixed && isOpenQuestion(f)),
103
+ fixed: ranked.filter((f) => f.fixed),
104
+ };
105
+ }
106
+ /** "an estimate from the code, not a measurement" or "measured over N calls". */
107
+ const tokenKind = (c) => c.measured ? `measured over ${(c.measured_calls ?? 0).toLocaleString("en-US")} calls` : "an estimate from the code, not a measurement";
108
+ function headline(o, g, cost) {
109
+ const n = g.open.length;
110
+ let h = `<header class="lede" id="s-top"><p class="project">leanprompt audit of <strong>${e(o.project)}</strong></p>`;
111
+ if (n === 0 && g.questions.length === 0) {
112
+ if (g.fixed.length > 0) {
113
+ h += `<h1>No open findings</h1><p class="sub">${e(plural(g.fixed.length, "finding"))}, fixed. Nothing open remains.</p>`;
114
+ }
115
+ else
116
+ h += `<h1>${e("The audit found no place where this app pays for tokens it doesn't need")}</h1>`;
117
+ return `${h}</header>`;
118
+ }
119
+ if (n === 0) {
120
+ h += `<h1>${e(`Nothing confirmed yet, and ${plural(g.questions.length, "open question")} to settle`)}</h1>`;
121
+ }
122
+ else {
123
+ h += `<h1>${e(`${plural(n, "place")} where this app pays for tokens it doesn't need`)}</h1>`;
124
+ const top = g.open[0];
125
+ const t = tokensOf(top);
126
+ const size = t !== undefined ? `, about ${e(formatTokens(t))} tokens per 1,000 calls` : top.estimate ? `, ${e(top.estimate)}` : "";
127
+ const what = top.problem ? splitLead(top.problem)[0] : `${ruleTitle(top, o.rules).replace(/\.$/, "")}.`;
128
+ h += `<p class="sub">The biggest, at ${location(top)}${size}: ${e(afterColon(what))}</p>`;
129
+ if (cost.with_tokens > 0) {
130
+ const kind = tokenKind(cost);
131
+ h += `<p class="total"><span class="lbl">Together</span> <strong>about ${e(formatTokens(cost.tokens_per_1k))} tokens per 1,000 calls</strong> `;
132
+ h += `${cost.with_tokens < n ? `For the ${e(cost.with_tokens)} with a number, ${e(kind)}.` : `${e(kind.charAt(0).toUpperCase() + kind.slice(1))}.`}`;
133
+ if (cost.question_tokens_per_1k > 0)
134
+ h += ` <span class="oq">If the open questions hold, add about ${e(formatTokens(cost.question_tokens_per_1k))}.</span>`;
135
+ h += `</p>`;
136
+ h += tokenBar(g.open, o.rules);
137
+ }
138
+ if (g.questions.length > 0)
139
+ h += `<p class="muted">Plus ${e(plural(g.questions.length, "open question"))} to confirm, listed after the findings.</p>`;
140
+ }
141
+ return `${h}</header>`;
142
+ }
143
+ // Capitalised words that stay capitalised after a colon: names of providers, tools and languages.
144
+ const PROPER = new Set("Anthropic Claude OpenAI Gemini Google OpenRouter DeepInfra DeepSeek Qwen Llama Mistral Groq Together Azure Bedrock Vertex LangChain LlamaIndex LiteLLM Vercel Python Go Node TypeScript JavaScript Rust Java Ruby Windows Linux Codex Cursor OpenCode SGLang Ollama GitHub GitLab Bitbucket Monday Tuesday Wednesday Thursday Friday Saturday Sunday January February March April May June July August September October November December".split(" "));
145
+ /**
146
+ * Text joined after a colon reads as one sentence: lower-case its first word when that is an ordinary capitalised
147
+ * word ("When", "A"), and leave acronyms, code, names and "I" as they are ("LLM", "vLLM", "OpenAI", "Anthropic").
148
+ */
149
+ export function afterColon(text) {
150
+ const word = /^[^\s,.;:!?()"]*/.exec(text)[0];
151
+ if (!/^[A-Z][a-z'-]*$/.test(word) || word.replace(/['-].*$/, "") === "I" || PROPER.has(word.replace(/['-].*$/, "")))
152
+ return text;
153
+ return text.charAt(0).toLowerCase() + text.slice(1);
154
+ }
155
+ /** The finding's short title for the meter: the first sentence of its problem, or the rule's title, cut at a word. */
156
+ export function shortTitle(f, rules, max = 80) {
157
+ const lead = (f.problem ? splitLead(f.problem)[0] : ruleTitle(f, rules)).trim().replace(/[.:;,]$/, "");
158
+ if (lead.length <= max)
159
+ return lead;
160
+ const cut = lead.slice(0, max - 1);
161
+ const sp = cut.lastIndexOf(" ");
162
+ return `${(sp > max / 2 ? cut.slice(0, sp) : cut).replace(/[\s,;:.(]+$/, "")}\u2026`;
163
+ }
164
+ /** `client.ts:42`: the file's name and line, for the legend. */
165
+ const shortWhere = (f) => (f.file === EXTERNAL ? whereText(f) : `${f.file.split("/").pop()}:${f.line}`);
166
+ /**
167
+ * The meter: one row per finding with a number, largest first. Each row carries the card's number, where it is,
168
+ * a bar scaled to its share of the total, and the figures as text, so neither colour nor length carries meaning alone.
169
+ */
170
+ function tokenBar(open, rules) {
171
+ const withT = open.filter((f) => (tokensOf(f) ?? 0) > 0);
172
+ const total = withT.reduce((a, f) => a + tokensOf(f), 0);
173
+ if (total <= 0 || withT.length < 1)
174
+ return "";
175
+ const max = Math.max(...withT.map((f) => tokensOf(f)));
176
+ let html = `<figure class="meter"><figcaption>Tokens per 1,000 calls, by finding, and each one's share of the total</figcaption><ol>`;
177
+ withT.forEach((f) => {
178
+ const t = tokensOf(f);
179
+ const share = (100 * t) / total;
180
+ const n = open.indexOf(f) + 1;
181
+ const pct = share >= 1 ? `${Math.round(share)}%` : "under 1%";
182
+ const title = shortTitle(f, rules);
183
+ html += `<li><a href="#f${n}" aria-label="${e(`Finding ${n}, ${title}, ${shortWhere(f)}: ${formatTokens(t)} tokens per 1,000 calls, ${pct} of the total`)}">`;
184
+ html += `<span class="mn" aria-hidden="true">${n}</span><span class="ml" aria-hidden="true"><span class="mtt">${e(title)}</span><code class="mw">${e(shortWhere(f))}</code></span>`;
185
+ html += `<span class="mt" aria-hidden="true">${e(formatTokens(t))}</span><span class="mp" aria-hidden="true">${e(pct)}</span>`;
186
+ html += `<span class="track" aria-hidden="true"><span class="fill" style="width:${((100 * t) / max).toFixed(2)}%"></span></span></a></li>`;
187
+ });
188
+ return `${html}</ol></figure>`;
189
+ }
190
+ function costSection(cost) {
191
+ if (cost.rows.filter((r) => !r.finding.fixed).length === 0)
192
+ return "";
193
+ let html = `<section class="cost" id="s-cost"><h2>What this costs you</h2>`;
194
+ const m = cost.money;
195
+ if (m) {
196
+ html += `<p class="big"><strong>About ${e(formatDollars(m.lost_per_month))} a month at ${e(m.calls_per_month.toLocaleString("en-US"))} calls a month.</strong></p>`;
197
+ html += `<p>Fixing these saves about ${e(formatDollars(m.saved_if_fixed))} a month`;
198
+ if (m.percent !== undefined && m.bill_per_month !== undefined)
199
+ html += ` (about ${e(m.percent.toFixed(1))}% of an estimated ${e(formatDollars(m.bill_per_month))} monthly bill)`;
200
+ html += `.`;
201
+ if (m.questions_per_month !== undefined)
202
+ html += ` If the open questions hold, add about ${e(formatDollars(m.questions_per_month))} a month.`;
203
+ if (m.saved_by_fixes !== undefined)
204
+ html += ` The fixes already made save about ${e(formatDollars(m.saved_by_fixes))} a month.`;
205
+ html += `</p>`;
206
+ }
207
+ if (cost.gpu) {
208
+ const h = cost.gpu.hours_per_month;
209
+ html += `<p class="big"><strong>About ${e(h.toFixed(1))} ${h === 1 ? "hour" : "hours"} of GPU prefill time a month</strong> at ${e(cost.gpu.calls_per_month.toLocaleString("en-US"))} calls a month and ${e(cost.gpu.prefill_tokens_per_second.toLocaleString("en-US"))} prefill tokens a second.</p>`;
210
+ }
211
+ html += `<p class="muted">Every figure here is ${e(tokenKind(cost))}. Findings can overlap (one failed call can show up in two), so the sum may count some tokens twice. Money is not part of the score.</p>`;
212
+ // The inputs, so every figure can be checked by hand.
213
+ html += `<div class="tablewrap"><table><thead><tr><th>Finding</th><th>Where</th><th class="fig">Tokens per 1,000 calls</th>${m ? `<th class="fig">A month</th>` : ""}${cost.rows.some((r) => r.ttft_seconds !== undefined) ? `<th class="fig">First-token time</th>` : ""}</tr></thead><tbody>`;
214
+ for (const r of cost.rows.filter((x) => !x.finding.fixed)) {
215
+ const t = r.finding.tokens_per_1k;
216
+ const parts = [t.prompt ? `${formatTokens(t.prompt)} prompt` : "", t.uncached ? `${formatTokens(t.uncached)} not cached` : "", t.output ? `${formatTokens(t.output)} output` : ""].filter(Boolean).join(", ");
217
+ html += `<tr><td class="rule">${e(r.finding.rule)}</td><td class="loc">${location(r.finding)}</td><td class="fig tok">${e(parts || "0")}</td>`;
218
+ if (m)
219
+ html += `<td class="fig mon">${r.dollars_per_month !== undefined ? e(formatDollars(r.dollars_per_month)) : ""}</td>`;
220
+ if (cost.rows.some((x) => x.ttft_seconds !== undefined))
221
+ html += `<td class="fig ttft">${r.ttft_seconds !== undefined ? `+${e(r.ttft_seconds.toFixed(2))} s` : ""}</td>`;
222
+ html += `</tr>`;
223
+ }
224
+ html += `</tbody></table></div>`;
225
+ const inputs = [];
226
+ if (m) {
227
+ inputs.push(`Volume: ${e(m.calls_per_month.toLocaleString("en-US"))} calls a month${m.volume_source ? `, from ${e(m.volume_source)}` : ""}.`);
228
+ for (const { model, price } of m.prices) {
229
+ const usd = (v) => `$${v.toFixed(Math.max(2, (String(v).split(".")[1] ?? "").length))}`;
230
+ const bits = [`input ${usd(price.input)}`, price.cached_input !== undefined ? `cached input ${usd(price.cached_input)}` : "", price.cache_write !== undefined ? `cache write ${usd(price.cache_write)}` : "", `output ${usd(price.output)}`].filter(Boolean).join(", ");
231
+ inputs.push(`Price of <code>${e(model)}</code>: ${e(bits)} per 1M tokens, from ${e(price.source)}, checked ${e(price.checked)}.`);
232
+ }
233
+ if (cost.average_call && m.bill_per_month !== undefined) {
234
+ inputs.push(`Average call, as the audit assumed: ${e(cost.average_call.prompt_tokens.toLocaleString("en-US"))} prompt and ${e(cost.average_call.output_tokens.toLocaleString("en-US"))} output tokens; the bill leaves cache discounts out.`);
235
+ }
236
+ }
237
+ else if (cost.gpu) {
238
+ inputs.push(`Volume: ${e(cost.gpu.calls_per_month.toLocaleString("en-US"))} calls a month; prefill throughput ${e(cost.gpu.prefill_tokens_per_second.toLocaleString("en-US"))} tokens a second, from <code>leanprompt.yaml</code>.`);
239
+ }
240
+ if (inputs.length)
241
+ html += `<ul class="inputs">${inputs.map((i) => `<li>${i}</li>`).join("")}</ul>`;
242
+ if (cost.missing.length > 0) {
243
+ html += `<p>To see this in money, add to <code>leanprompt.yaml</code>:</p><ul class="missing">${cost.missing.map((x) => `<li><code>${e(x.split("\t")[0])}</code>: ${e(x.split("\t")[1] ?? "")}</li>`).join("")}</ul>`;
244
+ html += `<p class="muted">leanprompt never guesses a volume or a price. Your coding agent can look up the provider's current price page and add it with the date; <a href="${REPO}/blob/main/docs/profile.md">how</a>.</p>`;
245
+ }
246
+ return `${html}</section>`;
247
+ }
248
+ /** Split text after its first sentence (a full stop, question mark or colon followed by a space and a capital). */
249
+ export function splitLead(text) {
250
+ const m = /^(.+?[.?])\s+(?=[A-Z"(])/.exec(text);
251
+ return m ? [m[1], text.slice(m[0].length)] : [text, ""];
252
+ }
253
+ function card(f, i, o, version, kind) {
254
+ const link = ruleLink(f, o.rules, version);
255
+ const title = ruleTitle(f, o.rules);
256
+ let html = `<article class="finding sev-${f.severity}${f.fixed ? " fixed" : ""}" data-where="${e(whereText(f))}" id="f${i + 1}">`;
257
+ html += `<div class="num" aria-hidden="true">${i + 1}</div><div class="body">`;
258
+ // The first sentence of the problem is the card's heading; the rest follows it as text.
259
+ const [lead, rest] = f.problem ? splitLead(f.problem) : [title, ""];
260
+ html += `<h3>${e(lead)}</h3>`;
261
+ html += `<p class="meta"><span class="visually-hidden">Finding ${i + 1}. </span>${location(f)} <span class="sev">${e(f.severity)}</span> <span class="rid">${e(f.rule)}</span>${f.fixed ? ` <span class="tag">fixed</span>` : ""}</p>`;
262
+ if (rest)
263
+ html += `<p class="rest">${e(rest)}</p>`;
264
+ const estimate = f.estimate ?? (tokensOf(f) !== undefined ? `about ${formatTokens(tokensOf(f))} tokens per 1,000 calls` : undefined);
265
+ const dl = [
266
+ ["act", kind === "question" ? "Change, if confirmed" : "What to change", f.change],
267
+ ["why", "Why it matters", f.why],
268
+ ];
269
+ if (kind === "question")
270
+ dl.unshift(["act confirm", "To confirm", f.confirm]);
271
+ const rows = dl.filter(([, , v]) => v).map(([c, k, v]) => `<div class="${c}"><dt>${e(k)}</dt><dd>${e(v)}</dd></div>`);
272
+ if (estimate || f.assumptions) {
273
+ let dd = estimate ? `<span class="est">${e(estimate)}</span>` : "";
274
+ if (f.assumptions)
275
+ dd += `<details class="assume"><summary>What the estimate assumes</summary><p>${e(f.assumptions)}</p></details>`;
276
+ rows.push(`<div class="estimate"><dt>Estimate</dt><dd>${dd}</dd></div>`);
277
+ }
278
+ if (rows.length)
279
+ html += `<dl class="why">${rows.join("")}</dl>`;
280
+ else
281
+ html += `<p class="muted">The audit wrote no explanation for this one; the rule page explains it.</p>`;
282
+ if (f.verify || f.problem || link) {
283
+ html += `<footer class="check">`;
284
+ if (f.verify)
285
+ html += `<p><span class="k">How to check the fix</span> ${e(f.verify)}</p>`;
286
+ if (f.problem || link) {
287
+ html += `<p class="rulelink">${f.problem ? `Rule: ${e(title)}.` : ""}${link ? ` <a href="${e(link)}">How this rule works</a>` : ""}</p>`;
288
+ }
289
+ html += `</footer>`;
290
+ }
291
+ return `${html}</div></article>`;
292
+ }
293
+ function findingsSection(o, g, version) {
294
+ const all = g.open.length + g.questions.length;
295
+ let html = `<section class="findings" id="s-findings"><h2>${e("What's wrong and what to change")}</h2><p class="muted">${all} open, ${g.fixed.length} fixed`;
296
+ if (o.ignored)
297
+ html += `, ${o.ignored} ignored by the profile`;
298
+ html += `. Largest first, by the audit's estimate of tokens lost per 1,000 calls.</p>`;
299
+ html += g.open.map((f, i) => card(f, i, o, version, "open")).join("");
300
+ if (g.open.length === 0)
301
+ html += `<p>No confirmed findings.</p>`;
302
+ html += `</section>`;
303
+ if (g.questions.length > 0) {
304
+ html += `<section class="findings" id="s-questions"><h2>Open questions</h2><p class="muted">Findings outside this repository, or waiting on a fact the code cannot show. They still count in the score. Each says what to confirm.</p>`;
305
+ html += g.questions.map((f, i) => card(f, g.open.length + i, o, version, "question")).join("");
306
+ html += `</section>`;
307
+ }
308
+ if (g.fixed.length > 0) {
309
+ html += `<section class="findings" id="s-fixed"><details class="fixed-list"><summary><h2>${e(plural(g.fixed.length, "fixed finding"))}</h2></summary>`;
310
+ html += g.fixed.map((f, i) => card(f, all + i, o, version, "fixed")).join("");
311
+ html += `</details></section>`;
312
+ }
313
+ return html;
314
+ }
315
+ const NPX = "npx github:Podwarden/leanprompt";
316
+ /** The block a user pastes into their coding agent: self-contained instructions plus the open findings. */
317
+ export function handoffText(findings, rules) {
318
+ const g = groups(findings);
319
+ const lines = [
320
+ "Please check and fix the LLM-call findings from a leanprompt audit of this repository.",
321
+ "",
322
+ `1. If the leanprompt skills are not installed for you here, install them: ${NPX} install`,
323
+ "2. Read .leanprompt/findings.json and leanprompt-report.md. If they are missing, use the list below.",
324
+ "3. Check each finding against the code before you change anything. The audit can be wrong: if a finding does not hold, tell me why and leave that code alone.",
325
+ "4. Fix one finding at a time. Show me the change as a small diff and apply it only after I say yes.",
326
+ "5. Prove each fix with the measure-loop skill: a before and after on the same scenario. Ask me before running anything that sends real, billed requests.",
327
+ `6. When a fix is proved, set "fixed": true on its finding in .leanprompt/findings.json and run ${NPX} score.`,
328
+ ];
329
+ if (g.open.length > 0) {
330
+ lines.push("", "Findings, largest first:");
331
+ g.open.forEach((f, i) => lines.push(`${i + 1}. ${f.rule} at ${whereText(f)}: ${f.problem ?? ruleTitle(f, rules)}`));
332
+ }
333
+ if (g.questions.length > 0) {
334
+ lines.push("", "Open questions (confirm before fixing):");
335
+ for (const f of g.questions)
336
+ lines.push(`- ${f.rule} (${whereText(f)}): ${f.problem ?? ruleTitle(f, rules)}${f.confirm ? ` To confirm: ${f.confirm}` : ""}`);
337
+ }
338
+ return lines.join("\n");
339
+ }
340
+ function copyButton(id, label = "Copy") {
341
+ return `<button type="button" class="copy" data-copy="${id}" data-label="${e(label)}" hidden>${e(label)}</button>`;
342
+ }
343
+ function handoffSection(o) {
344
+ let html = `<section class="handoff" id="s-fix"><h2>Fix it with your coding agent</h2>`;
345
+ html += `<p>Paste this into Claude Code, Codex, Cursor or any coding assistant. It will check each finding against your code and propose fixes one at a time, asking before it changes anything.</p>`;
346
+ html += `<div class="copybox">${copyButton("handoff", "Copy for your agent")}<pre id="handoff" tabindex="0">${e(handoffText(o.findings, o.rules))}</pre></div>`;
347
+ return `${html}</section>`;
348
+ }
349
+ /** Whether the page has shown something worth passing on: an estimate, or a measured score. */
350
+ function worthSharing(o) {
351
+ return o.findings.some((f) => f.estimate || f.tokens_per_1k) || (o.score?.kind === "measured" && num(o.score.score) !== undefined);
352
+ }
353
+ /** A short, plain message a user can send a colleague. */
354
+ export function shareText(findings, score, profile = null) {
355
+ const g = groups(findings);
356
+ const cost = costSummary(findings, profile);
357
+ let what;
358
+ if (g.open.length > 0) {
359
+ what = `leanprompt checked how our app calls LLMs and found ${plural(g.open.length, "place")} where it pays for tokens it doesn't need`;
360
+ if (cost.with_tokens > 0)
361
+ what += `, about ${formatTokens(cost.tokens_per_1k)} tokens per 1,000 calls, ${cost.measured ? `measured over ${cost.measured_calls} calls` : "an estimate from the code"}`;
362
+ else if (g.open[0].estimate)
363
+ what += `; the largest is ${g.open[0].estimate}, an estimate from the code`;
364
+ what += ".";
365
+ }
366
+ else if (g.fixed.length > 0) {
367
+ what = `leanprompt checked how our app calls LLMs; we fixed the ${plural(g.fixed.length, "place")} where it paid for tokens it didn't need.`;
368
+ }
369
+ else if (score?.kind === "measured" && num(score.score) !== undefined) {
370
+ what = `leanprompt measured how our app's LLM calls reuse the provider's cache: score ${score.score} over ${num(score.calls) ?? "its logged"} calls.`;
371
+ }
372
+ else
373
+ what = "leanprompt checked how our app calls LLMs.";
374
+ return `${what} It explains each finding in plain English and hands the fixes to your coding agent. It is free, open source, and runs locally: ${REPO}`;
375
+ }
376
+ /**
377
+ * The raw URL of `.leanprompt/score.json` on a public git host (GitHub, GitLab.com, Bitbucket), from
378
+ * `git remote get-url origin` and the current branch. Null for any other host, or no branch.
379
+ * Credentials in the remote URL are dropped.
380
+ */
381
+ export function rawScoreUrl(remote, branch) {
382
+ if (!branch || branch === "HEAD")
383
+ return null;
384
+ const m = /^(?:[\w.-]+@)?(github\.com|gitlab\.com|bitbucket\.org):(.+?)(?:\.git)?\/?$/.exec(remote) ??
385
+ /^(?:https?|ssh|git):\/\/(?:[^@/]+@)?(github\.com|gitlab\.com|bitbucket\.org)(?::\d+)?\/(.+?)(?:\.git)?\/?$/.exec(remote);
386
+ if (!m)
387
+ return null;
388
+ const [, host, path] = m;
389
+ if (!/^[\w.-]+(\/[\w.-]+)+$/.test(path))
390
+ return null;
391
+ const br = branch.split("/").map(encodeURIComponent).join("/");
392
+ const file = ".leanprompt/score.json";
393
+ if (host === "github.com")
394
+ return /^[\w.-]+\/[\w.-]+$/.test(path) ? `https://raw.githubusercontent.com/${path}/${br}/${file}` : null;
395
+ if (host === "gitlab.com")
396
+ return `https://gitlab.com/${path}/-/raw/${br}/${file}`;
397
+ return /^[\w.-]+\/[\w.-]+$/.test(path) ? `https://bitbucket.org/${path}/raw/${br}/${file}` : null;
398
+ }
399
+ function badgeBlock(o) {
400
+ let html = `<h3>The README badge</h3>`;
401
+ if (!o.score || num(o.score.score) === undefined) {
402
+ return `${html}<p class="muted">The badge shows your score. Run <code>npx leanprompt score</code> first; it writes <code>.leanprompt/score.json</code>, which the badge reads.</p>`;
403
+ }
404
+ const raw = o.git?.remote && o.git.branch ? rawScoreUrl(o.git.remote, o.git.branch) : null;
405
+ if (!raw) {
406
+ return `${html}<p class="muted">The badge needs a public repository on GitHub, GitLab.com or Bitbucket with <code>.leanprompt/score.json</code> committed: shields.io reads the file from there. This repository's remote is not one of those, so there is no snippet to paste.</p>`;
407
+ }
408
+ const md = `![leanprompt](https://img.shields.io/endpoint?url=${encodeURIComponent(raw)})`;
409
+ html += `<p>It shows your ${o.score.kind === "measured" ? "measured" : "static (estimated, grey)"} score, read from your own committed <code>.leanprompt/score.json</code>. Anyone can rerun it: there is no hosted service.`;
410
+ if (!o.git?.scoreTracked)
411
+ html += ` Commit <code>.leanprompt/score.json</code> first, or the badge has nothing to read.`;
412
+ html += ` It works once the repository is public.</p>`;
413
+ html += `<div class="copybox">${copyButton("badge")}<pre id="badge" tabindex="0">${e(md)}</pre></div>`;
414
+ return html;
415
+ }
416
+ function shareSection(o) {
417
+ if (!worthSharing(o))
418
+ return "";
419
+ let html = `<section class="share" id="s-share"><h2>If this helped</h2>`;
420
+ html += `<p>If this page saved you some digging, a star or a word to a colleague helps other builders find it.</p>`;
421
+ html += `<p><a class="star" href="${REPO}">Star leanprompt on GitHub</a></p>`;
422
+ html += `<h3>A message for a colleague</h3><div class="copybox">${copyButton("share")}<pre id="share" tabindex="0">${e(shareText(o.findings, o.score, o.profile ?? null))}</pre></div>`;
423
+ html += badgeBlock(o);
424
+ return `${html}</section>`;
425
+ }
426
+ const COPY_SCRIPT = `<script>
427
+ document.querySelectorAll("button[data-copy]").forEach(function (b) {
428
+ if (!navigator.clipboard) return;
429
+ var live = document.getElementById("copy-status");
430
+ var label = b.getAttribute("data-label") || "Copy";
431
+ b.hidden = false;
432
+ b.addEventListener("click", function () {
433
+ var text = document.getElementById(b.getAttribute("data-copy")).textContent;
434
+ navigator.clipboard.writeText(text).then(function () {
435
+ b.textContent = "Copied";
436
+ if (live) live.textContent = "Copied to the clipboard.";
437
+ setTimeout(function () { b.textContent = label; if (live) live.textContent = ""; }, 2000);
438
+ }, function () {
439
+ b.textContent = "Select the text to copy it";
440
+ if (live) live.textContent = "Copying failed. Select the text to copy it.";
441
+ });
442
+ });
443
+ });
444
+ </script>`;
445
+ /** The section index for wide screens: short labels, with counts, linking to the sections in order. */
446
+ function navRail(o, g, cost) {
447
+ const items = [["s-top", "Summary", ""]];
448
+ if (cost.rows.some((r) => !r.finding.fixed))
449
+ items.push(["s-cost", "Cost", ""]);
450
+ items.push(["s-findings", "Findings", String(g.open.length)]);
451
+ if (g.questions.length > 0)
452
+ items.push(["s-questions", "Questions", String(g.questions.length)]);
453
+ if (g.fixed.length > 0)
454
+ items.push(["s-fixed", "Fixed", String(g.fixed.length)]);
455
+ items.push(["s-fix", "Hand-off to your agent", ""], ["s-score", "Score", o.score && num(o.score.score) !== undefined ? String(o.score.score) : ""]);
456
+ if (worthSharing(o))
457
+ items.push(["s-share", "Share", ""]);
458
+ const li = items.map(([id, label, n]) => `<li><a href="#${id}"><span>${e(label)}</span>${n ? `<span class="c">${e(n)}</span>` : ""}</a></li>`).join("");
459
+ return `<nav class="rail" aria-label="Sections"><p class="mark">leanprompt</p><p class="proj">${e(o.project)}</p><ul>${li}</ul></nav>`;
460
+ }
461
+ /** One self-contained HTML document: inline CSS, one inline copy script, no network. */
462
+ export function renderReport(o) {
463
+ const version = o.version ?? packageVersion();
464
+ const g = groups(o.findings);
465
+ const cost = costSummary(o.findings, o.profile ?? null, o.average_call);
466
+ const body = headline(o, g, cost) +
467
+ costSection(cost) +
468
+ findingsSection(o, g, version) +
469
+ handoffSection(o) +
470
+ scoreSection(o.score) +
471
+ shareSection(o);
472
+ const footer = `<footer class="page-foot muted">Made by leanprompt ${e(version)}, by the LM Warden Team, on your machine; this page loads nothing from the network. <a href="${REPO}">${REPO}</a></footer>`;
473
+ return readFileSync(TEMPLATE, "utf8")
474
+ .replace("{{TITLE}}", () => `leanprompt report: ${e(o.project)}`)
475
+ .replace("{{NAV}}", () => navRail(o, g, cost))
476
+ .replace("{{BODY}}", () => body)
477
+ .replace("{{FOOTER}}", () => footer)
478
+ .replace("{{SCRIPT}}", () => COPY_SCRIPT);
479
+ }
480
+ /** Local git facts for the badge: the origin remote, the current branch, and whether score.json is tracked. No network. */
481
+ export function readGit(dir) {
482
+ const git = (...a) => {
483
+ try {
484
+ return execFileSync("git", ["-C", dir, ...a], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
485
+ }
486
+ catch {
487
+ return undefined;
488
+ }
489
+ };
490
+ if (git("rev-parse", "--is-inside-work-tree") !== "true")
491
+ return undefined;
492
+ const info = { scoreTracked: git("ls-files", "--error-unmatch", "--", ".leanprompt/score.json") !== undefined };
493
+ const remote = git("remote", "get-url", "origin");
494
+ const branch = git("symbolic-ref", "--short", "-q", "HEAD");
495
+ if (remote)
496
+ info.remote = remote;
497
+ if (branch)
498
+ info.branch = branch;
499
+ return info;
500
+ }
501
+ function readScore(file) {
502
+ if (!existsSync(file))
503
+ return null;
504
+ try {
505
+ const d = JSON.parse(readFileSync(file, "utf8"));
506
+ return d && typeof d === "object" && !Array.isArray(d) ? d : null;
507
+ }
508
+ catch {
509
+ return null;
510
+ }
511
+ }
512
+ /** `leanprompt report --html [--out <file>] [--dir <project>]` */
513
+ export async function reportCommand(args) {
514
+ let values;
515
+ try {
516
+ values = parseArgs({ args, options: optionsFor("report"), strict: true }).values;
517
+ }
518
+ catch (err) {
519
+ process.stderr.write(`leanprompt: ${err.message}\n`);
520
+ return 2;
521
+ }
522
+ if (!values.html) {
523
+ process.stderr.write("leanprompt: use --html (the Markdown report is leanprompt-report.md, written by the audit)\n");
524
+ return 2;
525
+ }
526
+ const dir = resolve(values.dir ?? ".");
527
+ let findings = [];
528
+ let ignored = 0;
529
+ let average_call;
530
+ const profile = loadProfile(dir);
531
+ const fpath = join(dir, FINDINGS_FILE);
532
+ if (existsSync(fpath)) {
533
+ const parsed = parseFindings(readFileSync(fpath, "utf8"), loadRuleIds(PACKAGE_ROOT));
534
+ if (parsed.errors.length > 0)
535
+ throw new Error(`${fpath}: ${parsed.errors.join("; ")}`);
536
+ findings = filterIgnored(parsed.findings, profile);
537
+ ignored = parsed.findings.length - findings.length;
538
+ average_call = parsed.average_call;
539
+ }
540
+ const html = renderReport({
541
+ findings,
542
+ ignored,
543
+ score: readScore(join(dir, SCORE_FILE)),
544
+ rules: loadRules(PACKAGE_ROOT),
545
+ project: basename(dir),
546
+ profile,
547
+ ...(average_call ? { average_call } : {}),
548
+ git: readGit(dir),
549
+ });
550
+ const target = resolve(dir, values.out ?? DEFAULT_OUT);
551
+ mkdirSync(dirname(target), { recursive: true });
552
+ writeFileSync(target, html);
553
+ process.stdout.write(`${target}\n`);
554
+ return 0;
555
+ }