@uselazuli/cli 0.0.0-stage → 1.0.1

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 (179) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -0
  3. package/README.md +202 -2
  4. package/agents/lazuli-design-reviewer.md +30 -0
  5. package/agents/lazuli-first-look.md +22 -0
  6. package/agents/lazuli-task-tester.md +25 -0
  7. package/bin/lazuli.mjs +699 -0
  8. package/package.json +11 -4
  9. package/rules/accessibility/HYPOTHESES.md +8 -0
  10. package/rules/accessibility/_area.yaml +7 -0
  11. package/rules/accessibility/operable.yaml +100 -0
  12. package/rules/accessibility/perceivable.yaml +153 -0
  13. package/rules/accessibility/robust.yaml +24 -0
  14. package/rules/accessibility/understandable.yaml +72 -0
  15. package/rules/color/HYPOTHESES.md +27 -0
  16. package/rules/color/_area.yaml +10 -0
  17. package/rules/color/adapt.yaml +183 -0
  18. package/rules/color/create.yaml +259 -0
  19. package/rules/color/review.yaml +215 -0
  20. package/rules/color/signal.yaml +196 -0
  21. package/rules/content/HYPOTHESES.md +18 -0
  22. package/rules/content/_area.yaml +8 -0
  23. package/rules/content/review.yaml +347 -0
  24. package/rules/content/voice.yaml +144 -0
  25. package/rules/content/writing.yaml +202 -0
  26. package/rules/data/HYPOTHESES.md +11 -0
  27. package/rules/data/_area.yaml +7 -0
  28. package/rules/data/charts.yaml +189 -0
  29. package/rules/data/dashboards.yaml +141 -0
  30. package/rules/data/review.yaml +159 -0
  31. package/rules/graphic/HYPOTHESES.md +17 -0
  32. package/rules/graphic/_area.yaml +8 -0
  33. package/rules/graphic/identity.yaml +141 -0
  34. package/rules/graphic/pieces.yaml +164 -0
  35. package/rules/graphic/review.yaml +242 -0
  36. package/rules/graphic/symbol.yaml +141 -0
  37. package/rules/motion/HYPOTHESES.md +19 -0
  38. package/rules/motion/_area.yaml +7 -0
  39. package/rules/motion/micro.yaml +143 -0
  40. package/rules/motion/review.yaml +347 -0
  41. package/rules/motion/transitions.yaml +169 -0
  42. package/rules/typography/HYPOTHESES.md +12 -0
  43. package/rules/typography/_area.yaml +8 -0
  44. package/rules/typography/adapt.yaml +45 -0
  45. package/rules/typography/create.yaml +126 -0
  46. package/rules/typography/review.yaml +127 -0
  47. package/rules/ui/HYPOTHESES.md +23 -0
  48. package/rules/ui/_area.yaml +9 -0
  49. package/rules/ui/compose.yaml +219 -0
  50. package/rules/ui/grid.yaml +75 -0
  51. package/rules/ui/review.yaml +399 -0
  52. package/rules/ui/states.yaml +257 -0
  53. package/rules/ux/HYPOTHESES.md +13 -0
  54. package/rules/ux/_area.yaml +8 -0
  55. package/rules/ux/flows.yaml +164 -0
  56. package/rules/ux/forms.yaml +142 -0
  57. package/rules/ux/review.yaml +186 -0
  58. package/skills/lazuli/SKILL.md +180 -0
  59. package/skills/lazuli/procedures/create.md +29 -0
  60. package/skills/lazuli/procedures/explain-decisions.md +22 -0
  61. package/skills/lazuli/procedures/improve.md +30 -0
  62. package/skills/lazuli/procedures/remember-this.md +41 -0
  63. package/skills/lazuli/procedures/review-design.md +35 -0
  64. package/skills/lazuli/procedures/show-options.md +32 -0
  65. package/skills/lazuli-accessibility-check/SKILL.md +68 -0
  66. package/skills/lazuli-color-context-and-culture/SKILL.md +53 -0
  67. package/skills/lazuli-color-context-and-culture/references/sectors.md +26 -0
  68. package/skills/lazuli-color-palette-by-intent/SKILL.md +54 -0
  69. package/skills/lazuli-color-palette-by-intent/references/intent-chords.md +51 -0
  70. package/skills/lazuli-color-screen-review/SKILL.md +51 -0
  71. package/skills/lazuli-color-states-and-signals/SKILL.md +53 -0
  72. package/skills/lazuli-content-interface-writing/SKILL.md +53 -0
  73. package/skills/lazuli-content-voice/SKILL.md +39 -0
  74. package/skills/lazuli-data-charts-and-dashboards/SKILL.md +59 -0
  75. package/skills/lazuli-graphic-derived-pieces/SKILL.md +40 -0
  76. package/skills/lazuli-graphic-derived-pieces/references/piece-template.html +24 -0
  77. package/skills/lazuli-graphic-identity/SKILL.md +43 -0
  78. package/skills/lazuli-motion-micro-and-transitions/SKILL.md +49 -0
  79. package/skills/lazuli-typography-choose-and-pair/SKILL.md +50 -0
  80. package/skills/lazuli-typography-screen-review/SKILL.md +51 -0
  81. package/skills/lazuli-ui-composition/SKILL.md +42 -0
  82. package/skills/lazuli-ui-composition/references/option-template.html +34 -0
  83. package/skills/lazuli-ui-layout-review/SKILL.md +47 -0
  84. package/skills/lazuli-ui-states-and-system/SKILL.md +54 -0
  85. package/skills/lazuli-ux-flows-and-forms/SKILL.md +51 -0
  86. package/skills/lazuli-ux-task-test/SKILL.md +44 -0
  87. package/src/browser.mjs +161 -0
  88. package/src/commands/capture.mjs +313 -0
  89. package/src/commands/catalog.mjs +37 -0
  90. package/src/commands/check-design.mjs +428 -0
  91. package/src/commands/check-goals.mjs +57 -0
  92. package/src/commands/compare-designs.mjs +97 -0
  93. package/src/commands/draft-memo.mjs +161 -0
  94. package/src/commands/hooks.mjs +343 -0
  95. package/src/commands/install-hooks.mjs +120 -0
  96. package/src/commands/install.mjs +132 -0
  97. package/src/commands/list-rules.mjs +49 -0
  98. package/src/commands/map-page.mjs +594 -0
  99. package/src/commands/record-answers.mjs +79 -0
  100. package/src/commands/record-log.mjs +296 -0
  101. package/src/commands/record-task.mjs +250 -0
  102. package/src/commands/render-options.mjs +164 -0
  103. package/src/commands/start-project.mjs +32 -0
  104. package/src/measure/a11y.mjs +383 -0
  105. package/src/measure/asset.mjs +206 -0
  106. package/src/measure/at-rest.mjs +49 -0
  107. package/src/measure/cases.mjs +549 -0
  108. package/src/measure/chart-read.mjs +401 -0
  109. package/src/measure/chart.mjs +264 -0
  110. package/src/measure/coherence.mjs +145 -0
  111. package/src/measure/color.mjs +79 -0
  112. package/src/measure/content.mjs +82 -0
  113. package/src/measure/cvd.mjs +24 -0
  114. package/src/measure/extreme.mjs +241 -0
  115. package/src/measure/forms.mjs +150 -0
  116. package/src/measure/in-page/a11y.js +489 -0
  117. package/src/measure/in-page/color.js +346 -0
  118. package/src/measure/in-page/composition.js +1496 -0
  119. package/src/measure/in-page/contrast.js +15 -0
  120. package/src/measure/in-page/cvd.js +173 -0
  121. package/src/measure/in-page/extreme.js +355 -0
  122. package/src/measure/in-page/frames.js +781 -0
  123. package/src/measure/in-page/look.js +28 -0
  124. package/src/measure/in-page/motion-probe.js +169 -0
  125. package/src/measure/in-page/style.js +107 -0
  126. package/src/measure/in-page/svg-strokes.js +112 -0
  127. package/src/measure/in-page/svg-uses.js +50 -0
  128. package/src/measure/in-page/symbol.js +123 -0
  129. package/src/measure/in-page/type.js +266 -0
  130. package/src/measure/in-page/weight.js +207 -0
  131. package/src/measure/layout.mjs +91 -0
  132. package/src/measure/motion.mjs +508 -0
  133. package/src/measure/piece.mjs +195 -0
  134. package/src/measure/registry.mjs +252 -0
  135. package/src/measure/rhythm.mjs +81 -0
  136. package/src/measure/signature.mjs +65 -0
  137. package/src/measure/states.mjs +240 -0
  138. package/src/measure/style.mjs +13 -0
  139. package/src/measure/symbol.mjs +268 -0
  140. package/src/measure/terms.mjs +153 -0
  141. package/src/measure/tiles.mjs +20 -0
  142. package/src/measure/timeline.mjs +621 -0
  143. package/src/measure/type.mjs +167 -0
  144. package/src/measure/weight.mjs +18 -0
  145. package/src/private-strings.mjs +81 -0
  146. package/src/project/blind.mjs +70 -0
  147. package/src/project/edits.mjs +154 -0
  148. package/src/project/gate.mjs +159 -0
  149. package/src/project/lazuli-md.mjs +497 -0
  150. package/src/project/log.mjs +329 -0
  151. package/src/project/match.mjs +112 -0
  152. package/src/project/records.mjs +380 -0
  153. package/src/project/tasks.mjs +153 -0
  154. package/src/report/evaluate.mjs +27 -0
  155. package/src/report/evaluators/a11y.mjs +206 -0
  156. package/src/report/evaluators/chart.mjs +151 -0
  157. package/src/report/evaluators/coherence.mjs +103 -0
  158. package/src/report/evaluators/color.mjs +86 -0
  159. package/src/report/evaluators/content.mjs +112 -0
  160. package/src/report/evaluators/extreme.mjs +53 -0
  161. package/src/report/evaluators/forms.mjs +116 -0
  162. package/src/report/evaluators/layout.mjs +94 -0
  163. package/src/report/evaluators/motion.mjs +273 -0
  164. package/src/report/evaluators/piece.mjs +69 -0
  165. package/src/report/evaluators/rhythm.mjs +99 -0
  166. package/src/report/evaluators/states.mjs +39 -0
  167. package/src/report/evaluators/style.mjs +35 -0
  168. package/src/report/evaluators/symbol.mjs +110 -0
  169. package/src/report/evaluators/terms.mjs +49 -0
  170. package/src/report/evaluators/type.mjs +163 -0
  171. package/src/report/evaluators/weight.mjs +51 -0
  172. package/src/report/evidence.mjs +4 -0
  173. package/src/report/finding.mjs +11 -0
  174. package/src/report/format.mjs +215 -0
  175. package/src/rules/hypotheses.mjs +28 -0
  176. package/src/rules/load.mjs +256 -0
  177. package/src/rules/public-text.mjs +56 -0
  178. package/src/rules/schema.mjs +212 -0
  179. package/templates/LAZULI.md +86 -0
@@ -0,0 +1,215 @@
1
+ const ORDER = { fail: 0, hint: 1, break: 2, pass: 3 };
2
+
3
+ // Rules that share a measure give identical findings; show them once with all rule ids.
4
+ function group(rows) {
5
+ const map = new Map();
6
+ for (const f of rows) {
7
+ const key = JSON.stringify([f.level, f.message, f.evidence ?? [], f.measuredAt ?? null, f.screens ?? null]);
8
+ const g = map.get(key);
9
+ if (g) {
10
+ g.ruleIds.push(f.ruleId);
11
+ g.names.push(f.name);
12
+ } else {
13
+ map.set(key, { level: f.level, message: f.message, evidence: f.evidence ?? [], ruleIds: [f.ruleId], names: [f.name], measuredAt: f.measuredAt, screens: f.screens });
14
+ }
15
+ }
16
+ return [...map.values()];
17
+ }
18
+
19
+ // "RV2, ES5 Name: message" when the rules share a name, else each id with its own name.
20
+ function label(g) {
21
+ const names = g.names.filter(Boolean);
22
+ if (names.length === 0) return `${g.ruleIds.join(", ")} ${g.message}`;
23
+ if (new Set(names).size === 1) return `${g.ruleIds.join(", ")} ${names[0]}: ${g.message}`;
24
+ return `${g.ruleIds.map((id, i) => (g.names[i] ? `${id} (${g.names[i]})` : id)).join(", ")} ${g.message}`;
25
+ }
26
+
27
+ // Each rule counts once, at its worst level across widths.
28
+ function ruleCounts(findings) {
29
+ const worst = new Map();
30
+ for (const f of findings) {
31
+ const cur = worst.get(f.ruleId);
32
+ if (cur === undefined || ORDER[f.level] < ORDER[cur]) worst.set(f.ruleId, f.level);
33
+ }
34
+ const counts = { fail: 0, hint: 0, break: 0, pass: 0 };
35
+ for (const level of worst.values()) counts[level] = (counts[level] ?? 0) + 1;
36
+ return counts;
37
+ }
38
+
39
+ const at = (widths) => `at ${widths.join(", ")} px`;
40
+ // A finding measured once for the whole check (reflow at its rule width) names that width, not the check widths.
41
+ // A site finding compares several screens: "across 3 screens at 1440 px".
42
+ const atOf = (g) => (Array.isArray(g.screens) ? `across ${g.screens.length} screens ` : "") + at(g.measuredAt ?? g.widths);
43
+
44
+ // Group per width first (shared measures), then merge identical groups across widths.
45
+ function mergeAcrossWidths(findings, widths) {
46
+ const merged = new Map();
47
+ for (const width of widths) {
48
+ for (const g of group(findings.filter((f) => f.width === width))) {
49
+ const key = JSON.stringify([g.level, g.message, g.evidence, g.ruleIds, g.measuredAt ?? null, g.screens ?? null]);
50
+ const m = merged.get(key);
51
+ if (m) m.widths.push(width);
52
+ else merged.set(key, { ...g, widths: [width] });
53
+ }
54
+ }
55
+ return [...merged.values()];
56
+ }
57
+
58
+ const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
59
+
60
+ // A result without areas (v0.1 shape) is split by the area each finding carries.
61
+ function blocksFor(result) {
62
+ if (Array.isArray(result.areas)) {
63
+ const blocks = result.areas.map((a) => ({ ...a, findings: result.findings.filter((f) => f.area === a.area) }));
64
+ const known = new Set(result.areas.map((a) => a.area));
65
+ const stray = result.findings.filter((f) => !known.has(f.area));
66
+ if (stray.length > 0) blocks.push({ area: null, title: "Other", findings: stray });
67
+ return blocks;
68
+ }
69
+ const blocks = [];
70
+ for (const f of result.findings) {
71
+ const name = f.area ?? null;
72
+ let block = blocks.find((b) => b.area === name);
73
+ if (!block) {
74
+ block = { area: name, title: name ? capitalize(name) : "Other", findings: [] };
75
+ blocks.push(block);
76
+ }
77
+ block.findings.push(f);
78
+ }
79
+ const other = blocks.findIndex((b) => b.area === null);
80
+ if (other > -1) blocks.push(...blocks.splice(other, 1));
81
+ return blocks;
82
+ }
83
+
84
+ export function formatReport(result) {
85
+ const { findings, hasLazuliMd, target, asset, measures = [], siteMeasures = [], screens = [], siteSkipped = false, reportPath, copiedTo, mode, goals = [], effects = [], unmatchedGoals = 0, problems = [], projectProblems = [], uncheckedNorms = [], unappliedBreaks = [] } = result;
86
+ // On an asset run a width is a size label ("1200x630", "512 to 16").
87
+ const widths = [...new Set([...measures.map((m) => m.width), ...findings.map((f) => f.width)])];
88
+ const allMeasures = [...measures, ...siteMeasures];
89
+
90
+ // A page run leaves out an area whose measured rules all read assets, unless it has a finding.
91
+ const blocks = blocksFor(result)
92
+ .filter((b) => !(b.assetOnly && b.findings.length === 0))
93
+ .map((b) => ({ ...b, groups: mergeAcrossWidths(b.findings, widths) }));
94
+ const total = ruleCounts(findings);
95
+ const failedCount = new Set(allMeasures.flatMap((m) => Object.keys(m.errors ?? {}))).size;
96
+ const failedText = failedCount > 0 ? `${failedCount} measurer${failedCount === 1 ? "" : "s"} failed` : "";
97
+ const top =
98
+ findings.length === 0
99
+ ? `Nothing was measured${failedText ? `, ${failedText}` : ""}.`
100
+ : `${total.fail} fail, ${total.hint} hint, ${total.pass} pass${total.break > 0 ? `, ${total.break} break` : ""} (rules)${failedText ? `, ${failedText}` : ""}`;
101
+ const lines = [`Lazuli design check: ${top}`];
102
+ if (uncheckedNorms.length > 0) {
103
+ lines.push(`Norms and learned rules not checked because their measurer failed: ${uncheckedNorms.join(", ")}.`);
104
+ }
105
+ if (asset) {
106
+ lines.push(`Asset: ${asset.target} (${asset.kind === "piece" ? (asset.raster ? "piece, raster" : "piece") : "symbol"})`);
107
+ } else if (target) {
108
+ lines.push(`Target: ${target}`);
109
+ }
110
+ // Only when site measures ran: with no site rule selected, nothing is marked "across".
111
+ if (screens.length > 1 && siteMeasures.length > 0) {
112
+ lines.push(`Page findings are for the target. Findings marked "across" compare ${screens.length} screens: ${screens.join(", ")}.`);
113
+ }
114
+ // A report written before the names were kept has only siteSkipped, which then meant coherence.
115
+ const notAcross = result.siteNotMeasured ?? (siteSkipped ? ["coherence"] : []);
116
+ if (notAcross.length > 0) {
117
+ const names = notAcross.length < 2 ? notAcross[0] : `${notAcross.slice(0, -1).join(", ")} and ${notAcross.at(-1)}`;
118
+ // "terms" reads as a plural noun.
119
+ const many = notAcross.length > 1 || notAcross[0] === "terms";
120
+ lines.push(`${capitalize(names)} across screens ${many ? "were" : "was"} not measured: ${many ? "they need" : "it needs"} two or more screens (give more targets or use --site).`);
121
+ }
122
+ // A symbol whose measurer read no size has the label "no size read", printed without "px".
123
+ if (widths.length) lines.push(`${asset ? "Sizes" : "Widths"}: ${widths.join(", ")}${widths.every((w) => /\d$/.test(String(w))) ? " px" : ""}`);
124
+ if (asset?.written?.length) lines.push(`Files written: ${asset.written.join(", ")}`);
125
+ if (asset?.blindSheet) lines.push(`Blind look sheet (GR5, the only path to give a fresh agent): ${asset.blindSheet}`);
126
+
127
+ const declared = [];
128
+ if (hasLazuliMd && mode) declared.push(`Mode: ${mode}`);
129
+ if (goals.length > 0) {
130
+ declared.push("Goals for this page and their recorded check:");
131
+ for (const [i, g] of goals.entries()) {
132
+ const v = (x) => (x ? x : "not set");
133
+ // effects and goals come from the same match, in the same order.
134
+ const e = effects.length === goals.length ? effects[i] : effects.find((x) => x.piece === g.piece);
135
+ const status = e ? ` [${e.status}]${e.verdict ? `, review ${e.verdict}` : ""}` : "";
136
+ declared.push(` ${g.piece}: understand ${v(g.understand)}; feel ${v(g.feel)}; do ${v(g.do)}${status}`);
137
+ if (g.rhythm?.length) declared.push(` Rhythm: ${g.rhythm.join(", ")}`);
138
+ }
139
+ } else if (unmatchedGoals > 0) {
140
+ declared.push(`LAZULI.md has ${unmatchedGoals} ${unmatchedGoals === 1 ? "goal" : "goals"}, none with a Target equal to this page.`);
141
+ }
142
+ if (unappliedBreaks.length > 0) {
143
+ declared.push("Breaks not applied:", ...unappliedBreaks.map((b) => ` ${b.rule} on ${b.piece}: ${b.reason}`));
144
+ }
145
+ if (problems.length > 0) {
146
+ declared.push("LAZULI.md problems:", ...problems.map((p) => ` - ${p}`));
147
+ }
148
+ if (declared.length > 0) lines.push("", ...declared);
149
+ if (projectProblems.length > 0) {
150
+ lines.push("", "Learned rules problems (these rules were skipped):", ...projectProblems.map((p) => ` - ${p}`));
151
+ }
152
+
153
+ for (const b of blocks) {
154
+ const counts = ruleCounts(b.findings);
155
+ const count = (level) => counts[level];
156
+ lines.push("");
157
+ const failedNote = b.failed?.length ? `${b.failed.join(", ")} measurer failed, see notes` : "";
158
+ if (b.measured === 0 && b.findings.length === 0) {
159
+ lines.push(failedNote ? `${b.title}: ${failedNote}.` : `${b.title}: no rule of this area is measured by check-design yet.`);
160
+ continue;
161
+ }
162
+ const coverage =
163
+ b.rules === undefined
164
+ ? ""
165
+ : ` (${b.measured} of ${b.rules} rules measured here; ${failedNote ? `${failedNote}; ` : ""}the others are checked by your agent or by people)`;
166
+ const brk = count("break") > 0 ? `, ${count("break")} break` : "";
167
+ lines.push(`${b.title}: ${count("fail")} fail, ${count("hint")} hint, ${count("pass")} pass${brk}${coverage}`);
168
+
169
+ const shown = b.groups.filter((g) => g.level !== "pass").sort((a, c) => ORDER[a.level] - ORDER[c.level]);
170
+ for (const g of shown) {
171
+ lines.push(` ${g.level.padEnd(4)} ${label(g)} (${atOf(g)})`);
172
+ for (const e of g.evidence) lines.push(` ${e}`);
173
+ }
174
+
175
+ const passBy = new Map();
176
+ for (const g of b.groups.filter((x) => x.level === "pass")) {
177
+ const key = atOf(g);
178
+ const ids = passBy.get(key) ?? new Set();
179
+ for (const id of g.ruleIds) ids.add(id);
180
+ passBy.set(key, ids);
181
+ }
182
+ for (const [key, ids] of passBy) lines.push(` pass ${[...ids].join(", ")} (${key})`);
183
+ }
184
+
185
+ // Measurement notes, once each, with the widths they came from when not all.
186
+ const notes = new Map();
187
+ // Notes about the asset itself (--size on a symbol) hold for every size.
188
+ for (const n of asset?.notes ?? []) notes.set(n, [...widths]);
189
+ for (const m of allMeasures) {
190
+ const found = [];
191
+ for (const [name, value] of Object.entries(m)) {
192
+ if (name === "width" || name === "errors") continue;
193
+ for (const n of value?.notes ?? []) found.push(`${name}: ${n}`);
194
+ }
195
+ for (const [name, message] of Object.entries(m.errors ?? {})) {
196
+ found.push(`${name}: ${name} measurer failed: ${message}`);
197
+ }
198
+ for (const n of found) {
199
+ const ws = notes.get(n) ?? [];
200
+ ws.push(m.width);
201
+ notes.set(n, ws);
202
+ }
203
+ }
204
+ if (notes.size) {
205
+ lines.push("", "Notes:");
206
+ for (const [n, ws] of notes) lines.push(` - ${n}${ws.length < widths.length ? ` (${at(ws)})` : ""}`);
207
+ }
208
+
209
+ if (reportPath) lines.push("", `Full report (JSON): ${reportPath}`);
210
+ if (copiedTo) lines.push(`Report also written to ${copiedTo}`);
211
+ if (!hasLazuliMd) {
212
+ lines.push("", "Tip: run lazuli start-project (or /lazuli start-project in your agent) to record your goals.");
213
+ }
214
+ return lines.join("\n");
215
+ }
@@ -0,0 +1,28 @@
1
+ const ID_RE = /^H\d{1,3}$/;
2
+
3
+ // Reads the rows of the markdown tables in an area's HYPOTHESES.md.
4
+ // A row counts when its first cell is an id like H3; columns are
5
+ // id, principle, candidate limit, how to validate.
6
+ export function parseHypotheses(text) {
7
+ const map = new Map();
8
+ for (const line of text.replace(/^\uFEFF/, "").split(/\r?\n/)) {
9
+ const trimmed = line.trim();
10
+ if (!trimmed.startsWith("|")) {
11
+ continue;
12
+ }
13
+ const cells = trimmed.replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
14
+ if (!ID_RE.test(cells[0])) {
15
+ continue;
16
+ }
17
+ if (map.has(cells[0])) {
18
+ throw new Error(`duplicate hypothesis ${cells[0]}`);
19
+ }
20
+ map.set(cells[0], {
21
+ id: cells[0],
22
+ principle: cells[1] ?? "",
23
+ limit: cells[2] ?? "",
24
+ validate: cells[3] ?? "",
25
+ });
26
+ }
27
+ return map;
28
+ }
@@ -0,0 +1,256 @@
1
+ import { access, readdir, readFile, stat } from "node:fs/promises";
2
+ import { join, relative } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import YAML from "yaml";
5
+ import { parseHypotheses } from "./hypotheses.mjs";
6
+ import { validateArea, validateRule } from "./schema.mjs";
7
+
8
+ export const KIT_RULES_DIR = fileURLToPath(new URL("../../rules", import.meta.url));
9
+
10
+ export class RulesDirNotFoundError extends Error {
11
+ constructor(dir, message = `Rules folder not found: ${dir}`) {
12
+ super(message);
13
+ this.name = "RulesDirNotFoundError";
14
+ this.code = "RULES_DIR_NOT_FOUND";
15
+ }
16
+ }
17
+
18
+ const YAML_FILE_RE = /\.ya?ml$/;
19
+
20
+ async function listYaml(dir, { flat = false } = {}) {
21
+ const entries = await readdir(dir, { withFileTypes: true });
22
+ const files = [];
23
+ for (const entry of entries) {
24
+ const full = join(dir, entry.name);
25
+ if (entry.isDirectory()) {
26
+ if (!flat) {
27
+ files.push(...(await listYaml(full)));
28
+ }
29
+ } else if (
30
+ entry.isFile() &&
31
+ YAML_FILE_RE.test(entry.name) &&
32
+ !entry.name.startsWith("_")
33
+ ) {
34
+ files.push(full);
35
+ }
36
+ }
37
+ return files.sort();
38
+ }
39
+
40
+ async function readText(file) {
41
+ return (await readFile(file, "utf8")).replace(/^\uFEFF/, "");
42
+ }
43
+
44
+ async function exists(file) {
45
+ try {
46
+ await access(file);
47
+ return true;
48
+ } catch (err) {
49
+ if (err?.code === "ENOENT" || err?.code === "ENOTDIR") {
50
+ return false;
51
+ }
52
+ throw err;
53
+ }
54
+ }
55
+
56
+ // Reads and validates every rule file under dir. Problems are pushed, not thrown.
57
+ // File names in messages are relative to base; seen tracks ids across calls.
58
+ async function collectRules(dir, { base = dir, seen = new Map(), problems, flat = false }) {
59
+ const rules = [];
60
+ for (const file of await listYaml(dir, { flat })) {
61
+ const name = relative(base, file) || file;
62
+ let parsed;
63
+ try {
64
+ parsed = YAML.parse(await readText(file));
65
+ } catch (err) {
66
+ problems.push(`${name}: invalid YAML (${err.message})`);
67
+ continue;
68
+ }
69
+ const items = Array.isArray(parsed) ? parsed : [parsed];
70
+ for (const item of items) {
71
+ const { ok, errors } = validateRule(item);
72
+ if (!ok) {
73
+ const label = item && item.id ? ` (${item.id})` : "";
74
+ problems.push(`${name}${label}: ${errors.join("; ")}`);
75
+ continue;
76
+ }
77
+ if (seen.has(item.id)) {
78
+ problems.push(`${name}: duplicate id ${item.id} (also in ${seen.get(item.id)})`);
79
+ continue;
80
+ }
81
+ seen.set(item.id, name);
82
+ rules.push(item);
83
+ }
84
+ }
85
+ return rules;
86
+ }
87
+
88
+ export async function loadRules(dir) {
89
+ const problems = [];
90
+ const rules = await collectRules(dir, { problems });
91
+ if (problems.length > 0) {
92
+ throw new Error(`Invalid rules:\n${problems.join("\n")}`);
93
+ }
94
+ return rules;
95
+ }
96
+
97
+ const PROJECT_AREA = {
98
+ area: "project",
99
+ title: "Learned rules",
100
+ summary: "Rules this project learned from corrections, written by remember-this.",
101
+ order: 1000,
102
+ prefixes: ["LR"],
103
+ skills: [],
104
+ };
105
+
106
+ export async function loadKit({ dirs, projectDir }) {
107
+ const problems = [];
108
+ const seen = new Map();
109
+ const areas = [];
110
+ const rules = [];
111
+ const hypotheses = new Map();
112
+ const areaNames = new Set();
113
+ const prefixOwner = new Map();
114
+
115
+ for (const dir of dirs) {
116
+ if (!(await exists(dir))) {
117
+ throw new RulesDirNotFoundError(dir);
118
+ }
119
+ if (!(await stat(dir)).isDirectory()) {
120
+ throw new RulesDirNotFoundError(dir, `Rules path is not a folder: ${dir}`);
121
+ }
122
+ const entries = await readdir(dir, { withFileTypes: true });
123
+ const looseFiles = entries
124
+ .filter((e) => e.isFile() && YAML_FILE_RE.test(e.name))
125
+ .map((e) => e.name)
126
+ .sort();
127
+ if (looseFiles.length > 0) {
128
+ problems.push(
129
+ `${dir}: rule files sit directly in this folder (${looseFiles.join(", ")}); each area needs its own folder with _area.yaml`,
130
+ );
131
+ }
132
+ const folders = entries
133
+ .filter((e) => e.isDirectory())
134
+ .map((e) => e.name)
135
+ .sort();
136
+
137
+ for (const folder of folders) {
138
+ const areaDir = join(dir, folder);
139
+ const manifestFile = join(areaDir, "_area.yaml");
140
+ if (!(await exists(manifestFile))) {
141
+ problems.push(`${folder}: missing _area.yaml`);
142
+ continue;
143
+ }
144
+
145
+ let manifest;
146
+ try {
147
+ manifest = YAML.parse(await readText(manifestFile));
148
+ } catch (err) {
149
+ problems.push(`${folder}/_area.yaml: invalid YAML (${err.message})`);
150
+ continue;
151
+ }
152
+ const check = validateArea(manifest, folder);
153
+ if (!check.ok) {
154
+ problems.push(`${folder}/_area.yaml: ${check.errors.join("; ")}`);
155
+ continue;
156
+ }
157
+
158
+ if (areaNames.has(folder)) {
159
+ problems.push(`area ${folder} is defined twice`);
160
+ continue;
161
+ }
162
+ areaNames.add(folder);
163
+
164
+ for (const prefix of manifest.prefixes) {
165
+ if (prefixOwner.has(prefix)) {
166
+ problems.push(`prefix ${prefix} is claimed by ${prefixOwner.get(prefix)} and ${folder}`);
167
+ } else {
168
+ prefixOwner.set(prefix, folder);
169
+ }
170
+ }
171
+
172
+ let hyp = new Map();
173
+ const hypFile = join(areaDir, "HYPOTHESES.md");
174
+ if (await exists(hypFile)) {
175
+ try {
176
+ hyp = parseHypotheses(await readText(hypFile));
177
+ } catch (err) {
178
+ problems.push(`${folder}/HYPOTHESES.md: ${err.message}`);
179
+ }
180
+ }
181
+ hypotheses.set(folder, hyp);
182
+
183
+ areas.push({
184
+ area: folder,
185
+ title: manifest.title,
186
+ summary: manifest.summary,
187
+ order: manifest.order,
188
+ prefixes: manifest.prefixes,
189
+ skills: manifest.skills,
190
+ dir: areaDir,
191
+ });
192
+
193
+ const own = await collectRules(areaDir, { base: dir, seen, problems });
194
+ for (const rule of own) {
195
+ let ok = true;
196
+ if (rule.area !== folder) {
197
+ problems.push(`${rule.id}: area must be ${folder}`);
198
+ ok = false;
199
+ }
200
+ const prefix = rule.id.slice(0, 2);
201
+ if (!manifest.prefixes.includes(prefix)) {
202
+ problems.push(`${rule.id}: prefix ${prefix} is not listed in ${folder}/_area.yaml`);
203
+ ok = false;
204
+ }
205
+ if (rule.hypothesis !== undefined) {
206
+ const ids = Array.isArray(rule.hypothesis) ? rule.hypothesis : [rule.hypothesis];
207
+ for (const id of ids) {
208
+ if (!hyp.has(id)) {
209
+ problems.push(`${rule.id}: hypothesis ${id} is not in ${folder}/HYPOTHESES.md`);
210
+ ok = false;
211
+ }
212
+ }
213
+ }
214
+ if (ok) {
215
+ rules.push(rule);
216
+ }
217
+ }
218
+ }
219
+ }
220
+
221
+ if (problems.length > 0) {
222
+ throw new Error(`Invalid rules:\n${problems.join("\n")}`);
223
+ }
224
+
225
+ const projectProblems = [];
226
+ if (projectDir && (await exists(projectDir)) && !(await stat(projectDir)).isDirectory()) {
227
+ projectProblems.push(`${projectDir}: the project rules path is not a folder`);
228
+ } else if (projectDir && (await exists(projectDir))) {
229
+ const projectRules = await collectRules(projectDir, { seen, problems: projectProblems, flat: true });
230
+ const kept = [];
231
+ for (const rule of projectRules) {
232
+ const errs = [];
233
+ if (rule.area !== "project") {
234
+ errs.push(`${rule.id}: area must be project`);
235
+ }
236
+ if (!rule.id.startsWith("LR")) {
237
+ errs.push(`${rule.id}: a learned rule id must start with LR`);
238
+ }
239
+ if (rule.origin === "norm") {
240
+ errs.push(`${rule.id}: a learned rule cannot be a norm`);
241
+ }
242
+ if (errs.length > 0) {
243
+ projectProblems.push(...errs);
244
+ } else {
245
+ kept.push(rule);
246
+ }
247
+ }
248
+ if (kept.length > 0) {
249
+ areas.push({ ...PROJECT_AREA, dir: projectDir });
250
+ rules.push(...kept);
251
+ }
252
+ }
253
+
254
+ areas.sort((a, b) => a.order - b.order || a.area.localeCompare(b.area));
255
+ return { areas, rules, hypotheses, projectProblems };
256
+ }
@@ -0,0 +1,56 @@
1
+ // Patterns for process language that must not reach public kit text: pointers to the author's working
2
+ // notes, their ids and their wording. The kit text test and the release check both read this list.
3
+ // Names and regex sources are spelled with escapes and character classes so this file never matches
4
+ // its own patterns.
5
+
6
+ // Between the words of a phrase: spaces, or a line break with an optional comment marker, so a phrase
7
+ // wrapped across two comment or prose lines is still one match.
8
+ const GAP = String.raw`(?:[ \t]*\r?\n[ \t]*(?:\/\/+|#|\*)?[ \t]*|[ \t]+)`;
9
+ const words = (...parts) => parts.join(GAP);
10
+
11
+ export const PROCESS_PATTERNS = [
12
+ { name: "pre\u002dflight", re: /\bpre-?fligh[t]\b/i },
13
+ { name: "pre\u002dflight id", re: /(?<![\w-])P\d{1,2}\b/i },
14
+ { name: "plan letter", re: new RegExp(String.raw`\b(?:sub-)?` + words("plans?", String.raw`[A-K]\b`), "i") },
15
+ { name: "plan task", re: new RegExp(String.raw`\b` + words("Task", String.raw`\d+\b`), "i") },
16
+ { name: "ledg\u0065r", re: /\bledge[r]s?\b/i },
17
+ { name: "process folders", re: /docs[/]superpowers|[.]superpowers/i },
18
+ { name: "internal spec", re: new RegExp(String.raw`\b` + words("Lazuli", String.raw`spec\b`), "i") },
19
+ {
20
+ name: "process wording",
21
+ re: new RegExp(
22
+ [
23
+ words("(?:set|fixed|written|chosen)", "in", "the", "plan"),
24
+ words("the", "plan(?:'s|" + GAP + "leaves)"),
25
+ words("kit", "plan"),
26
+ "control[l]er",
27
+ words("fix", "(?:round|wave)"),
28
+ words("final", "review"),
29
+ words("(?:Minor|Important|Critical)", String.raw`\d+`),
30
+ "roadma[p]",
31
+ words("owner", "decision"),
32
+ ].map((p) => String.raw`\b` + p + String.raw`\b`).join("|"),
33
+ "i",
34
+ ),
35
+ },
36
+ ];
37
+
38
+ // Files that must hold matching samples: exempt from the process kind only.
39
+ export const PROCESS_EXEMPT = ["src/rules/public-text.mjs", "tests/kit-text.test.mjs"];
40
+
41
+ // Path prefixes of the release tool and its test, which quote process samples on purpose.
42
+ export const PROCESS_SKIP_PREFIXES = ["scripts/release/", "tests/release-"];
43
+
44
+ export function findProcessRefs(text) {
45
+ // Matched on the whole text, so a phrase may wrap; each match is reported on the line where it starts.
46
+ const all = String(text);
47
+ const found = [];
48
+ for (const { name, re } of PROCESS_PATTERNS) {
49
+ const global = new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g");
50
+ for (const m of all.matchAll(global)) {
51
+ const line = all.slice(0, m.index).split("\n").length;
52
+ found.push({ name, match: m[0].replace(/\s+/g, " "), line });
53
+ }
54
+ }
55
+ return found.sort((a, b) => a.line - b.line);
56
+ }