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.
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 +86 -3
  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 +31 -8
  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,205 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { optionsFor } from "./help.js";
5
+ import { loadRuleIds } from "./lint/rules.js";
6
+ import { loadProfile, profileTargets } from "./profile.js";
7
+ import { PACKAGE_ROOT } from "./score/write.js";
8
+ const REPO = "https://github.com/Podwarden/leanprompt";
9
+ export const LESSON_FILE = join(".leanprompt", "lesson.md");
10
+ const SCORE_FILE = join(".leanprompt", "score.json");
11
+ const CREDIT_PROJECT = "Credit (optional): project and link";
12
+ // The repo URL itself (and a path or query under it), never a lookalike such as `leanprompt-evil`.
13
+ const REPO_URL = /^https:\/\/github\.com\/Podwarden\/leanprompt(?:[/?#].*)?$/;
14
+ const URL_RE = /https?:\/\/[^\s)>\]"'`]+|\bwww\.[^\s)>\]"'`]+/gi;
15
+ const TLDS = "com|net|org|io|dev|app|ai|cloud|local|internal|lan|corp|home|h|co|me|xyz|info|biz";
16
+ const HOST_RE = new RegExp(`\\b(?:[a-z0-9-]+\\.)+(?:${TLDS})\\b`, "gi");
17
+ const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g;
18
+ const IPV4_RE = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
19
+ const IPV6_RE = /\b[0-9a-f]{1,4}(?::[0-9a-f]{0,4}){5,7}\b/gi;
20
+ const KEY_PREFIX_RE = /\b(?:sk-[A-Za-z0-9_-]{8,}|vw[A-Za-z0-9_-]{16,})/g;
21
+ const LONG_RUN_RE = /[A-Za-z0-9+/=_-]{32,}/g;
22
+ const HEX_RUN_RE = /\b[0-9a-fA-F]{24,}\b/g;
23
+ const UNIX_PATH_RE = /(?:^|[\s("'`=:])(?:~|(?:\/[A-Za-z0-9._@+-]+){2,})(?:\/[A-Za-z0-9._@+-]+)*/g;
24
+ const WIN_PATH_RE = /\b[A-Za-z]:\\[^\s]+/g;
25
+ const SOURCE_PATH_RE = /\b[\w.@-]+(?:\/[\w.@-]+)+\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|rb|php|cs|swift|ya?ml|json|toml|env|sh|md)\b/g;
26
+ const mask = (s) => `${s.trim().slice(0, 4)}...`;
27
+ const matches = (text, re) => text.match(re) ?? [];
28
+ /** Split a draft into the text of its "Credit (optional): project and link" section and the rest. */
29
+ function splitCredit(text) {
30
+ const lines = text.split("\n");
31
+ const rest = [];
32
+ const credit = [];
33
+ let inCredit = false;
34
+ for (const l of lines) {
35
+ if (/^#{1,6}\s/.test(l))
36
+ inCredit = l.replace(/^#+\s*/, "").trim() === CREDIT_PROJECT;
37
+ (inCredit ? credit : rest).push(l);
38
+ }
39
+ return { rest: rest.join("\n"), credit: credit.join("\n") };
40
+ }
41
+ function scanPart(text, allowLinks) {
42
+ const found = [];
43
+ let t = text;
44
+ // URLs first, so a path or host inside a URL is reported once, as a URL.
45
+ t = t.replace(URL_RE, (u) => {
46
+ const bare = u.replace(/[.,;:]+$/, "");
47
+ if (REPO_URL.test(bare) || allowLinks)
48
+ return " ";
49
+ found.push(`a link to somewhere other than this repo: ${bare.slice(0, 30)}${bare.length > 30 ? "..." : ""}`);
50
+ return " ";
51
+ });
52
+ for (const m of matches(t, EMAIL_RE))
53
+ found.push(`an email address: ${mask(m)}`);
54
+ t = t.replace(EMAIL_RE, " ");
55
+ for (const m of matches(t, KEY_PREFIX_RE))
56
+ found.push(`something that looks like an API key: ${mask(m)}`);
57
+ t = t.replace(KEY_PREFIX_RE, " ");
58
+ for (const m of [...matches(t, HEX_RUN_RE), ...matches(t, LONG_RUN_RE)])
59
+ found.push(`a long random-looking string, possibly a key: ${mask(m)}`);
60
+ t = t.replace(HEX_RUN_RE, " ").replace(LONG_RUN_RE, " ");
61
+ for (const m of [...matches(t, IPV4_RE), ...matches(t, IPV6_RE)])
62
+ found.push(`an IP address: ${mask(m)}`);
63
+ t = t.replace(IPV4_RE, " ").replace(IPV6_RE, " ");
64
+ for (const m of [...matches(t, WIN_PATH_RE), ...matches(t, UNIX_PATH_RE)])
65
+ found.push(`a file path: ${mask(m)}`);
66
+ t = t.replace(WIN_PATH_RE, " ").replace(UNIX_PATH_RE, " ");
67
+ for (const m of matches(t, SOURCE_PATH_RE))
68
+ found.push(`a file path: ${mask(m)}`);
69
+ t = t.replace(SOURCE_PATH_RE, " ");
70
+ for (const m of matches(t, HOST_RE))
71
+ found.push(`a host name: ${mask(m)}`);
72
+ return found;
73
+ }
74
+ /**
75
+ * What must be removed before a lesson is shared: keys, emails, IP addresses, host names, links other than this
76
+ * repo's, and file paths. The repo URL, rule ids and E-row citations pass. A link is allowed only in the
77
+ * "Credit (optional): project and link" section, where the contributor puts it on purpose. Matches are masked
78
+ * to their first characters, so a key is never printed in full.
79
+ */
80
+ export function scanLesson(text) {
81
+ const { rest, credit } = splitCredit(text);
82
+ return { blocked: [...scanPart(rest, false), ...scanPart(credit, true)] };
83
+ }
84
+ /** The fields of a score.json this command copies. Null when absent; throws naming the file when unreadable. */
85
+ function readScore(file) {
86
+ if (!existsSync(file))
87
+ return null;
88
+ let d;
89
+ try {
90
+ d = JSON.parse(readFileSync(file, "utf8"));
91
+ }
92
+ catch {
93
+ throw new Error(`${file}: not valid JSON`);
94
+ }
95
+ if (!d || typeof d !== "object" || Array.isArray(d))
96
+ throw new Error(`${file}: must be an object`);
97
+ const inp = (d.inputs ?? {});
98
+ const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : undefined);
99
+ return {
100
+ kind: d.kind === "measured" || d.kind === "static" ? d.kind : undefined,
101
+ score: num(d.score),
102
+ E: num(inp.E),
103
+ S: num(inp.S),
104
+ G: num(inp.G),
105
+ };
106
+ }
107
+ const cell = (v, digits) => v === undefined ? "" : typeof v === "number" ? (digits === undefined ? String(v) : v.toFixed(digits)) : v;
108
+ function buildDraft(rule, target, before, after) {
109
+ const row = (label, pick, digits) => `| ${label} | ${before ? cell(pick(before), digits) : ""} | ${after ? cell(pick(after), digits) : ""} |`;
110
+ return `<!-- Draft written by leanprompt on this machine. Nothing has been sent. Read every line, edit it freely, and delete this note. Describe the case in general terms: no code, keys, hostnames, file paths, customer or company names. A maintainer reads every submission before it informs a rule, and it is shared under CC BY 4.0. -->
111
+
112
+ # Lesson learned
113
+
114
+ Rule id: ${rule}
115
+ Provider or engine: ${target}
116
+
117
+ ## Before and after
118
+
119
+ | | Before | After |
120
+ |---|---|---|
121
+ ${row("Score kind", (s) => s.kind)}
122
+ ${row("Score", (s) => s.score)}
123
+ ${row("E", (s) => s.E, 2)}
124
+ ${row("S", (s) => s.S, 2)}
125
+ ${row("G", (s) => s.G, 2)}
126
+
127
+ ## What changed
128
+
129
+ ## Edge case (in general terms)
130
+
131
+ ## Credit (optional): name
132
+
133
+ ## ${CREDIT_PROJECT}
134
+ `;
135
+ }
136
+ /** The prefilled "new issue" link: template, title and labels only. The body is pasted by the user, never put in a URL. */
137
+ function issueUrl(rule) {
138
+ const q = [
139
+ ["template", "lesson-learned.yml"],
140
+ ["title", rule ? `Lesson learned: ${rule}` : "Lesson learned: "],
141
+ ["labels", "lesson-learned"],
142
+ ]
143
+ .map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
144
+ .join("&");
145
+ return `${REPO}/issues/new?${q}`;
146
+ }
147
+ /** The rule id a written draft names, for the issue title. */
148
+ const ruleOf = (text) => /^Rule id:[ \t]*(LP-[A-Z]{2}-\d{2})\b/m.exec(text)?.[1] ?? "";
149
+ /**
150
+ * `leanprompt lesson [--rule <id>] [--before <older score.json>] [--dir <project>]`.
151
+ * Writes a draft to `.leanprompt/lesson.md` for the user to edit, scans it, and prints a prefilled
152
+ * GitHub issue link once it is clean. An existing draft is checked, not overwritten. Sends nothing.
153
+ */
154
+ export async function lessonCommand(args) {
155
+ let values;
156
+ try {
157
+ values = parseArgs({ args, options: optionsFor("lesson"), strict: true }).values;
158
+ }
159
+ catch (e) {
160
+ process.stderr.write(`leanprompt: ${e.message}\n`);
161
+ return 2;
162
+ }
163
+ const dir = resolve(values.dir ?? ".");
164
+ const file = join(dir, LESSON_FILE);
165
+ if (values.rule !== undefined && !loadRuleIds(PACKAGE_ROOT).has(values.rule)) {
166
+ process.stderr.write(`leanprompt: unknown rule id ${values.rule}\n`);
167
+ return 2;
168
+ }
169
+ let text;
170
+ if (existsSync(file)) {
171
+ text = readFileSync(file, "utf8");
172
+ process.stdout.write(`leanprompt lesson: checking your existing draft ${file} (not overwritten; delete it to start again)\n`);
173
+ }
174
+ else {
175
+ const profile = loadProfile(dir);
176
+ const target = profile ? profileTargets(profile).map((t) => t.engine ?? t.provider).join(", ") : "";
177
+ const after = readScore(join(dir, SCORE_FILE));
178
+ if (values.rule === undefined && after?.kind !== "measured") {
179
+ const have = after === null ? "there is no score yet" : `the score is ${after.kind ?? "of unknown kind"}, not measured`;
180
+ process.stderr.write(`leanprompt lesson: nothing to share yet: ${have}, and no --rule was given. A lesson needs a measured before and after (run leanprompt score --measured after your fix) or a rule that misled you (leanprompt lesson --rule <id>).\n`);
181
+ return 2;
182
+ }
183
+ const before = values.before === undefined ? null : readScore(resolve(values.before));
184
+ if (values.before !== undefined && before === null)
185
+ throw new Error(`${resolve(values.before)}: no such file`);
186
+ text = buildDraft(values.rule ?? "", target, before, after);
187
+ mkdirSync(dirname(file), { recursive: true });
188
+ writeFileSync(file, text);
189
+ process.stdout.write(`leanprompt lesson: wrote a draft to ${file}\n`);
190
+ }
191
+ const { blocked } = scanLesson(text);
192
+ if (blocked.length > 0) {
193
+ process.stderr.write(`leanprompt lesson: remove these from ${file} before sharing, then run this command again:\n`);
194
+ for (const b of blocked)
195
+ process.stderr.write(` - ${b}\n`);
196
+ return 1;
197
+ }
198
+ process.stdout.write([
199
+ "Read the draft and fill in the empty sections, then run this command again to check it.",
200
+ "To share it, open this link, then paste the text of the draft into the form. You open the issue yourself; leanprompt sends nothing, and the link carries no text from the draft:",
201
+ issueUrl(values.rule ?? ruleOf(text)),
202
+ "",
203
+ ].join("\n"));
204
+ return 0;
205
+ }
@@ -0,0 +1,7 @@
1
+ import { type LintIssue } from "./rules.js";
2
+ export declare const STALE_DAYS = 90;
3
+ /**
4
+ * Lint providers/*.md, models/*.md and runtimes/*.md: dated, sourced, and (providers) a well-formed cache block;
5
+ * (runtimes) a source URL on every table row.
6
+ */
7
+ export declare function lintFacts(root: string, today: string): LintIssue[];
@@ -0,0 +1,163 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CACHE_MODES } from "../facts.js";
4
+ import { parseDoc } from "../frontmatter.js";
5
+ import { isMain } from "../isMain.js";
6
+ import { posix } from "./rules.js";
7
+ export const STALE_DAYS = 90;
8
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
9
+ const DAY_MS = 86_400_000;
10
+ function asDate(v) {
11
+ if (v instanceof Date)
12
+ return v.toISOString().slice(0, 10);
13
+ return typeof v === "string" && DATE_RE.test(v) ? v : undefined;
14
+ }
15
+ function isNum(v) {
16
+ return typeof v === "number" && Number.isFinite(v) && v >= 0;
17
+ }
18
+ /**
19
+ * Lint providers/*.md, models/*.md and runtimes/*.md: dated, sourced, and (providers) a well-formed cache block;
20
+ * (runtimes) a source URL on every table row.
21
+ */
22
+ export function lintFacts(root, today) {
23
+ const issues = [];
24
+ const tables = [];
25
+ for (const [dir, kind] of [["providers", "provider"], ["models", "model"], ["runtimes", "runtime"]]) {
26
+ const p = join(root, dir);
27
+ if (!existsSync(p))
28
+ continue;
29
+ for (const f of readdirSync(p).sort())
30
+ if (f.endsWith(".md"))
31
+ tables.push({ file: posix(join(dir, f)), kind });
32
+ }
33
+ for (const { file, kind } of tables) {
34
+ const err = (msg) => issues.push({ file, level: "error", msg });
35
+ let doc;
36
+ try {
37
+ doc = parseDoc(readFileSync(join(root, file), "utf8"));
38
+ }
39
+ catch (e) {
40
+ err(`bad frontmatter: ${e.message.split("\n")[0]}`);
41
+ continue;
42
+ }
43
+ const { meta } = doc;
44
+ const nameKey = kind === "provider" ? "provider" : kind === "model" ? "family" : "runtime";
45
+ if (typeof meta[nameKey] !== "string" || !meta[nameKey])
46
+ err(`missing field: ${nameKey}`);
47
+ if (typeof meta.source !== "string" || !/^https?:\/\/\S+$/.test(meta.source))
48
+ err("missing source (a URL)");
49
+ const checked = asDate(meta.checked);
50
+ if (!checked)
51
+ err("missing or bad checked date (YYYY-MM-DD)");
52
+ else {
53
+ const age = Math.floor((Date.parse(today) - Date.parse(checked)) / DAY_MS);
54
+ if (age < 0)
55
+ err(`checked date ${checked} is after ${today}`);
56
+ else if (age > STALE_DAYS)
57
+ issues.push({ file, level: "warn", msg: `checked ${checked} is ${age} days old (limit ${STALE_DAYS})` });
58
+ }
59
+ if (doc.sections.length === 0)
60
+ err("empty body: no fact table sections");
61
+ if (kind === "runtime") {
62
+ const text = readFileSync(join(root, file), "utf8").replace(/\r\n/g, "\n");
63
+ const rows = rowsWithoutSource(text);
64
+ if (rows.total === 0)
65
+ err("no table rows");
66
+ for (const r of rows.missing)
67
+ err(`table row without a source URL: ${r}`);
68
+ }
69
+ if (kind === "provider") {
70
+ const c = meta.cache;
71
+ if (!c || typeof c !== "object") {
72
+ err("missing cache block");
73
+ continue;
74
+ }
75
+ if (!CACHE_MODES.includes(c.mode))
76
+ err(`bad cache.mode ${String(c.mode)}`);
77
+ if (!isNum(c.min_tokens))
78
+ err("cache.min_tokens must be a number");
79
+ if (!isNum(c.ttl_seconds))
80
+ err("cache.ttl_seconds must be a number");
81
+ for (const k of ["step_tokens", "block_tokens", "max_breakpoints"]) {
82
+ if (c[k] !== undefined && !isNum(c[k]))
83
+ err(`cache.${k} must be a number`);
84
+ }
85
+ if (c.drops_last_block !== undefined && typeof c.drops_last_block !== "boolean")
86
+ err("cache.drops_last_block must be a boolean");
87
+ if (c.mode === "block" && c.block_tokens === undefined)
88
+ err("cache.block_tokens required for mode block");
89
+ if (c.mode === "breakpoints" && c.max_breakpoints === undefined)
90
+ err("cache.max_breakpoints required for mode breakpoints");
91
+ }
92
+ }
93
+ issues.push(...lintAssistantPaths(root, today));
94
+ return issues;
95
+ }
96
+ const PATHS_FILE = "docs/assistant-paths.md";
97
+ /** Lint docs/assistant-paths.md: dated, a `paths:` map, and a source URL on every table row. Skipped when the file is absent. */
98
+ function lintAssistantPaths(root, today) {
99
+ const file = PATHS_FILE;
100
+ const full = join(root, file);
101
+ if (!existsSync(full))
102
+ return [];
103
+ const issues = [];
104
+ const err = (msg) => issues.push({ file, level: "error", msg });
105
+ const text = readFileSync(full, "utf8").replace(/\r\n/g, "\n");
106
+ let doc;
107
+ try {
108
+ doc = parseDoc(text);
109
+ }
110
+ catch (e) {
111
+ err(`bad frontmatter: ${e.message.split("\n")[0]}`);
112
+ return issues;
113
+ }
114
+ const checked = asDate(doc.meta.checked);
115
+ if (!checked)
116
+ err("missing or bad checked date (YYYY-MM-DD)");
117
+ else {
118
+ const age = Math.floor((Date.parse(today) - Date.parse(checked)) / DAY_MS);
119
+ if (age < 0)
120
+ err(`checked date ${checked} is after ${today}`);
121
+ else if (age > STALE_DAYS)
122
+ issues.push({ file, level: "warn", msg: `checked ${checked} is ${age} days old (limit ${STALE_DAYS})` });
123
+ }
124
+ const paths = doc.meta.paths;
125
+ if (!paths || typeof paths !== "object" || Array.isArray(paths) || Object.keys(paths).length === 0)
126
+ err("missing paths map");
127
+ if (doc.sections.length === 0)
128
+ err("empty body: no assistant sections");
129
+ const rows = rowsWithoutSource(text);
130
+ for (const r of rows.missing)
131
+ err(`table row without a source URL: ${r}`);
132
+ if (rows.total === 0)
133
+ err("no table rows");
134
+ return issues;
135
+ }
136
+ /** Every table row (not the header, not the separator) needs an http(s) URL as its source. */
137
+ function rowsWithoutSource(text) {
138
+ const lines = text.replace(/^---[ \t]*\n[\s\S]*?\n---[ \t]*(?:\n|$)/, "").split("\n");
139
+ let total = 0;
140
+ const missing = [];
141
+ lines.forEach((line, i) => {
142
+ if (!line.trimStart().startsWith("|"))
143
+ return;
144
+ if (/^\s*\|[\s:|-]+\|\s*$/.test(line))
145
+ return; // separator
146
+ if (/^\s*\|[\s:|-]+\|\s*$/.test(lines[i + 1] ?? ""))
147
+ return; // header
148
+ total++;
149
+ if (!/https?:\/\/\S+/.test(line))
150
+ missing.push(line.trim().slice(0, 60));
151
+ });
152
+ return { total, missing };
153
+ }
154
+ // CLI entry for `npm run lint:facts`: lint the repo root, exit 1 on errors, print warnings.
155
+ if (isMain(import.meta.url)) {
156
+ const root = process.argv[2] ?? process.cwd();
157
+ const issues = lintFacts(root, new Date().toISOString().slice(0, 10));
158
+ for (const i of issues)
159
+ process.stderr.write(`${i.level}: ${i.file}: ${i.msg}\n`);
160
+ const errors = issues.filter((i) => i.level === "error").length;
161
+ process.stdout.write(`lint:facts: ${errors} error(s), ${issues.length - errors} warning(s)\n`);
162
+ process.exit(errors ? 1 : 0);
163
+ }
@@ -0,0 +1,26 @@
1
+ import { type LintIssue } from "./rules.js";
2
+ /** The fields of an `eval/results/*.json` file this check reads (the full type is eval/run.ts `ResultFile`). */
3
+ export interface ResultFile {
4
+ kind: "measured" | "simulated";
5
+ app: string;
6
+ form: string;
7
+ provider: string;
8
+ model: string;
9
+ date: string;
10
+ /** The file's basename when it was read from disk; otherwise derived with `resultFileName`. */
11
+ file?: string;
12
+ }
13
+ export declare function resultFileName(r: ResultFile): string;
14
+ export declare const NOT_QUOTABLE: Set<string>;
15
+ /**
16
+ * Every line that states a number with a unit must cite an evidence row `(E<n>)` that exists, or link
17
+ * a result file under `eval/results/` whose kind is `measured`. Simulated results are never quotable.
18
+ * Fenced code blocks, inline code and HTML comments are ignored.
19
+ */
20
+ export declare function checkNumbers(markdown: string, results: ResultFile[], evidence: Set<string>): LintIssue[];
21
+ export declare function loadResults(root: string): ResultFile[];
22
+ export declare const DOCS_NOT_PUBLIC: Set<string>;
23
+ /** The public docs: every Markdown file directly under docs/ except the working records. */
24
+ export declare function publicDocs(root: string): string[];
25
+ /** The public copy: README.md, the public docs/ pages and every Markdown file under skills/. */
26
+ export declare function checkNumbersInRepo(root: string): LintIssue[];
@@ -0,0 +1,163 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { basename, join, relative } from "node:path";
3
+ import { isMain } from "../isMain.js";
4
+ import { loadEvidenceIds, posix } from "./rules.js";
5
+ // Same file naming as eval/run.ts.
6
+ const safe = (s) => s.replace(/[^A-Za-z0-9._-]+/g, "-");
7
+ export function resultFileName(r) {
8
+ return `${r.date}-${safe(r.app)}-${r.form}-${safe(r.provider)}-${safe(r.model)}.json`;
9
+ }
10
+ // A number is a claim when it carries one of these units: %, seconds (" s"), a multiplier (3x, 1.5×),
11
+ // tokens, or dollars. Plain counts ("50 calls", "40 lines", "8 sessions") and versions are not.
12
+ const NUM = String.raw `\d(?:[\d,.]*\d)?`;
13
+ const TRIGGERS = [
14
+ new RegExp(`${NUM}\\s?%`),
15
+ new RegExp(`${NUM} s\\b`),
16
+ new RegExp(`${NUM}(?:x|\\s?×)(?![A-Za-z0-9])`),
17
+ new RegExp(`${NUM}[kKM]? tokens?\\b`),
18
+ /\$\s?\d/,
19
+ ];
20
+ // (E1), (E1, E7), [E7](docs/evidence.md)
21
+ const CITATION = /[([]\s*(E\d+(?:\s*[,;]\s*E\d+)*)\s*[)\]]/g;
22
+ // Rows that may be cited but not quoted with a number yet (docs/DESIGN.md Q2, Q3): E8 waits on the
23
+ // owner's wording approval, E12 on a measured before/after.
24
+ export const NOT_QUOTABLE = new Set(["E8", "E12"]);
25
+ const RESULT_LINK = /eval\/results\/([^\s)\]"'<>#`]+)/g;
26
+ /** Text a reader sees as prose: inline code spans and HTML comments removed. */
27
+ function prose(line) {
28
+ return line.replace(/(`+)[\s\S]*?\1/g, " ").replace(/<!--[\s\S]*?-->/g, " ");
29
+ }
30
+ /**
31
+ * Every line that states a number with a unit must cite an evidence row `(E<n>)` that exists, or link
32
+ * a result file under `eval/results/` whose kind is `measured`. Simulated results are never quotable.
33
+ * Fenced code blocks, inline code and HTML comments are ignored.
34
+ */
35
+ export function checkNumbers(markdown, results, evidence) {
36
+ const issues = [];
37
+ const byName = new Map(results.map((r) => [r.file ?? resultFileName(r), r]));
38
+ const lines = markdown.split(/\r?\n/);
39
+ let fence = null;
40
+ let inComment = false;
41
+ lines.forEach((raw, i) => {
42
+ const err = (msg) => issues.push({ file: "", level: "error", msg: `line ${i + 1}: ${msg}` });
43
+ const fenceMark = /^\s{0,3}(`{3,}|~{3,})/.exec(raw);
44
+ if (fence) {
45
+ if (fenceMark && fenceMark[1][0] === fence[0] && fenceMark[1].length >= fence.length && raw.trim() === fenceMark[1])
46
+ fence = null;
47
+ return;
48
+ }
49
+ if (fenceMark) {
50
+ fence = fenceMark[1];
51
+ return;
52
+ }
53
+ let line = raw;
54
+ if (inComment) {
55
+ const end = line.indexOf("-->");
56
+ if (end < 0)
57
+ return;
58
+ line = line.slice(end + 3);
59
+ inComment = false;
60
+ }
61
+ line = prose(line);
62
+ const open = line.indexOf("<!--");
63
+ if (open >= 0) {
64
+ line = line.slice(0, open);
65
+ inComment = true;
66
+ }
67
+ const hit = TRIGGERS.map((t) => t.exec(line)).find((m) => m);
68
+ // A row of the evidence table itself (`| E1 | ... |`) is the source, not a claim that needs one.
69
+ const row = /^\|\s*(E\d+)\s*\|/.exec(line);
70
+ let sourced = !!row && evidence.has(row[1]);
71
+ let bad = false;
72
+ for (const m of line.matchAll(CITATION)) {
73
+ for (const id of m[1].split(/\s*[,;]\s*/)) {
74
+ if (hit && NOT_QUOTABLE.has(id)) {
75
+ err(`${id} cannot be quoted with a number yet (see docs/DESIGN.md open questions)`);
76
+ bad = true;
77
+ }
78
+ else if (evidence.has(id))
79
+ sourced = true;
80
+ else {
81
+ err(`unknown evidence ${id}`);
82
+ bad = true;
83
+ }
84
+ }
85
+ }
86
+ for (const m of line.matchAll(RESULT_LINK)) {
87
+ const name = m[1];
88
+ const r = byName.get(name);
89
+ if (!r) {
90
+ err(`unknown result eval/results/${name}`);
91
+ bad = true;
92
+ }
93
+ else if (r.kind !== "measured") {
94
+ err(`simulated result cannot be quoted: eval/results/${name}`);
95
+ bad = true;
96
+ }
97
+ else
98
+ sourced = true;
99
+ }
100
+ if (sourced || bad)
101
+ return;
102
+ if (hit)
103
+ err(`"${hit[0]}" needs a source: cite (E<n>) from docs/evidence.md or link a measured eval/results file`);
104
+ });
105
+ return issues;
106
+ }
107
+ function markdownUnder(dir) {
108
+ if (!existsSync(dir))
109
+ return [];
110
+ const out = [];
111
+ for (const e of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
112
+ const p = join(dir, e.name);
113
+ if (e.isDirectory())
114
+ out.push(...markdownUnder(p));
115
+ else if (e.name.endsWith(".md"))
116
+ out.push(p);
117
+ }
118
+ return out;
119
+ }
120
+ export function loadResults(root) {
121
+ const dir = join(root, "eval", "results");
122
+ if (!existsSync(dir))
123
+ return [];
124
+ return readdirSync(dir)
125
+ .filter((f) => f.endsWith(".json"))
126
+ .map((f) => ({ ...JSON.parse(readFileSync(join(dir, f), "utf8")), file: f }));
127
+ }
128
+ // docs/ pages that are working records (planning notes and background research), not public claims.
129
+ export const DOCS_NOT_PUBLIC = new Set(["DESIGN.md", "RESEARCH-similar-projects.md"]);
130
+ /** The public docs: every Markdown file directly under docs/ except the working records. */
131
+ export function publicDocs(root) {
132
+ const dir = join(root, "docs");
133
+ if (!existsSync(dir))
134
+ return [];
135
+ return readdirSync(dir)
136
+ .filter((f) => f.endsWith(".md") && !DOCS_NOT_PUBLIC.has(f))
137
+ .sort()
138
+ .map((f) => join(dir, f));
139
+ }
140
+ /** The public copy: README.md, the public docs/ pages and every Markdown file under skills/. */
141
+ export function checkNumbersInRepo(root) {
142
+ const evidence = loadEvidenceIds(root);
143
+ const results = loadResults(root);
144
+ const files = [join(root, "README.md"), ...publicDocs(root), ...markdownUnder(join(root, "skills"))].filter((f) => existsSync(f));
145
+ const issues = [];
146
+ if (!existsSync(join(root, "README.md")))
147
+ issues.push({ file: "README.md", level: "error", msg: "missing README.md" });
148
+ for (const f of files) {
149
+ const rel = posix(relative(root, f)) || basename(f);
150
+ for (const i of checkNumbers(readFileSync(f, "utf8"), results, evidence))
151
+ issues.push({ ...i, file: rel });
152
+ }
153
+ return issues;
154
+ }
155
+ // CLI entry for `npm run check:numbers`: check the repo root, exit 1 on any error.
156
+ if (isMain(import.meta.url)) {
157
+ const root = process.argv[2] ?? process.cwd();
158
+ const issues = checkNumbersInRepo(root);
159
+ for (const i of issues)
160
+ process.stderr.write(`${i.level}: ${i.file}: ${i.msg}\n`);
161
+ process.stdout.write(`check:numbers: ${issues.length} error(s)\n`);
162
+ process.exit(issues.length ? 1 : 0);
163
+ }
@@ -0,0 +1,20 @@
1
+ /** A path for display: always "/" separators, whatever the OS. */
2
+ export declare const posix: (p: string) => string;
3
+ export interface LintIssue {
4
+ file: string;
5
+ level: "error" | "warn";
6
+ msg: string;
7
+ }
8
+ export declare const REQUIRED_SECTIONS: string[];
9
+ /** Ids from the `| E<n> |` rows of docs/evidence.md. */
10
+ export declare function loadEvidenceIds(root: string): Set<string>;
11
+ export declare function ruleFiles(root: string): string[];
12
+ export type RuleInfo = {
13
+ title: string;
14
+ skill: string;
15
+ };
16
+ /** Rule id -> title and skill, from the frontmatter of skills/*\/rules/*.md. */
17
+ export declare function loadRules(root: string): Map<string, RuleInfo>;
18
+ /** Rule ids (`LP-PC-01`, ...) declared in the skills rules directories; files with bad frontmatter are skipped. */
19
+ export declare function loadRuleIds(root: string): Set<string>;
20
+ export declare function lintRules(root: string): LintIssue[];