@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,161 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { readLazuliMd } from "../project/lazuli-md.mjs";
4
+ import { gateStatus } from "../project/gate.mjs";
5
+ import { matchGoals, sameTarget } from "../project/match.mjs";
6
+ import { readRecords } from "../project/records.mjs";
7
+ import { KIT_RULES_DIR, loadKit } from "../rules/load.mjs";
8
+ import { NoLazuliMdError } from "./check-goals.mjs";
9
+
10
+ const norm = (s) => String(s ?? "").trim().toLowerCase();
11
+
12
+ const BUILDER_LABEL = "Logged by the builder (not checked by the reviewer):";
13
+
14
+ // The latest check-design report (.lazuli/report.json): its target and the ids of the rules that fail in it.
15
+ // No report, or one that cannot be read, gives null.
16
+ async function latestReport(cwd) {
17
+ try {
18
+ const parsed = JSON.parse((await fs.readFile(path.join(cwd, ".lazuli", "report.json"), "utf8")).replace(/^/, ""));
19
+ if (typeof parsed?.target !== "string" || !Array.isArray(parsed.findings)) {
20
+ return null;
21
+ }
22
+ return { target: parsed.target, failed: new Set(parsed.findings.filter((f) => f?.level === "fail").map((f) => norm(f.ruleId))) };
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ // Quotes the first look recorded for the capture of the page's latest review. A review with no first look is a gap.
29
+ async function firstLookOf(cwd, target) {
30
+ const records = await readRecords(cwd, target);
31
+ const review = [...records].reverse().find((r) => r.kind === "review");
32
+ if (!review) {
33
+ return { lines: [], gap: null };
34
+ }
35
+ if (review.data?.verdict === "pending") {
36
+ return { lines: [], gap: `The review is pending (${review.data.reason}); no first look or review was run.` };
37
+ }
38
+ const look = [...records].reverse().find((r) => r.kind === "first-look" && r.captureId === review.captureId);
39
+ if (!look) {
40
+ return { lines: [], gap: "No first look recorded for the reviewed capture." };
41
+ }
42
+ const answers = [...(look.data?.answers ?? [])].sort((a, b) => a.width - b.width);
43
+ return { lines: answers.map((a) => `First look (${look.data.reader}, ${a.width} px): about ${a.about}; main action ${a.mainAction}; feeling ${a.feeling}`), gap: null };
44
+ }
45
+
46
+ // The evidence for explain-decisions: what LAZULI.md and the records say, per goal, with every hole listed under Gaps.
47
+ // It reads only; every date comes from a record, never from now, so the same inputs give the same text.
48
+ // What the reviewer judged is stated as the reviewer's; decisions and breaks are the builder's own log and are labeled so.
49
+ export async function draftMemo({ cwd = process.cwd(), target } = {}) {
50
+ const root = path.resolve(cwd);
51
+ const md = await readLazuliMd(root);
52
+ if (md === null) {
53
+ throw new NoLazuliMdError();
54
+ }
55
+ const kit = await loadKit({
56
+ dirs: [process.env.LAZULI_RULES_DIR ?? KIT_RULES_DIR],
57
+ projectDir: path.join(root, ".lazuli", "rules"),
58
+ });
59
+ const ruleOf = (id) => kit.rules.find((r) => norm(r.id) === norm(id)) ?? null;
60
+ const gate = await gateStatus({ cwd: root, md, ...(target ? { target } : {}) });
61
+ const wanted = target ? matchGoals(md, target, root) : md.goals;
62
+ const allPieces = new Set(md.goals.map((g) => norm(g.piece)));
63
+
64
+ const gaps = [];
65
+ const report = await latestReport(root);
66
+ // True when the latest check-design report is of a page of this piece and fails this rule.
67
+ const reportFails = (piece, rule) =>
68
+ report !== null &&
69
+ report.failed.has(norm(rule)) &&
70
+ md.goals.some((g) => norm(g.piece) === norm(piece) && g.target && sameTarget(report.target, g.target, root));
71
+ // Every problem of every decision, in LAZULI.md order. A decision with any problem is not printed as a fact.
72
+ const printable = new Set();
73
+ for (const d of md.decisions) {
74
+ const before = gaps.length;
75
+ if (!allPieces.has(norm(d.piece))) {
76
+ gaps.push(`Decision "${d.decision}": "${d.piece}" is not a goal.`);
77
+ }
78
+ if (d.action !== "none" && !ruleOf(d.rule)) {
79
+ gaps.push(`Decision "${d.decision}": unknown rule ${d.rule}.`);
80
+ }
81
+ if (d.action === "broken" && !md.breaks.some((b) => b.status === "kept" && norm(b.rule) === norm(d.rule) && norm(b.piece) === norm(d.piece))) {
82
+ gaps.push(`Decision "${d.decision}": ${d.rule} is marked broken but no kept break for ${d.rule} on ${d.piece} is logged.`);
83
+ }
84
+ if (d.action === "followed" && reportFails(d.piece, d.rule)) {
85
+ gaps.push(`Decision "${d.decision}": ${d.rule} is marked followed but check-design reports a fail for ${d.rule}.`);
86
+ }
87
+ if (d.action === "accepted" && reportFails(d.piece, d.rule)) {
88
+ gaps.push(`Decision "${d.decision}": ${d.rule} is marked accepted but check-design reports a fail for ${d.rule}.`);
89
+ }
90
+ if (gaps.length === before) {
91
+ printable.add(d);
92
+ }
93
+ }
94
+ // Every break on a piece that is not a goal, and every break whose rule does not exist, once.
95
+ const unknownBreaks = new Set();
96
+ for (const b of md.breaks) {
97
+ if (!allPieces.has(norm(b.piece))) {
98
+ gaps.push(`Break "${b.rule}" on ${b.piece}: "${b.piece}" is not a goal.`);
99
+ } else if (!ruleOf(b.rule)) {
100
+ unknownBreaks.add(b);
101
+ gaps.push(`Break "${b.rule}" on ${b.piece}: unknown rule.`);
102
+ }
103
+ }
104
+ if (target && wanted.length === 0) {
105
+ gaps.push(...gate.items.filter((i) => i.startsWith("No goal in LAZULI.md has this Target")));
106
+ }
107
+
108
+ const out = ["# Decisions", "", `Idea: ${md.idea ?? "not declared"}`];
109
+ const donePieces = new Set();
110
+ for (const goal of wanted) {
111
+ const piece = norm(goal.piece);
112
+ const first = !donePieces.has(piece);
113
+ donePieces.add(piece);
114
+ const checked = gate.goals.find((g) => norm(g.piece) === piece && g.target === goal.target);
115
+ out.push("", `## ${goal.piece}`, "", `Goal: understand ${goal.understand}; feel ${goal.feel}; do ${goal.do}`);
116
+ let check = `Recorded check: ${checked?.status ?? "not-checked"}`;
117
+ if (checked?.verdict && checked.reviewedAt) {
118
+ check += `, review ${checked.verdict} by ${checked.reviewer ?? "unknown reviewer"} on ${checked.reviewedAt.slice(0, 10)}`;
119
+ }
120
+ out.push(check);
121
+ if (goal.target) {
122
+ const look = await firstLookOf(root, goal.target);
123
+ out.push(...look.lines);
124
+ if (look.gap) {
125
+ gaps.push(`${goal.piece}: ${look.gap}`);
126
+ }
127
+ }
128
+
129
+ if (first) {
130
+ const own = md.decisions.filter((d) => norm(d.piece) === piece);
131
+ const keptBreaks = md.breaks.filter((b) => norm(b.piece) === piece && b.status === "kept" && !unknownBreaks.has(b));
132
+ for (const d of own.filter((x) => printable.has(x))) {
133
+ const rule = d.action === "none" ? null : ruleOf(d.rule);
134
+ const line = rule === null ? [] : [d.action === "accepted" ? `Hint left open on purpose: ${rule.id} (${rule.name})` : `Rule: ${rule.id} (${rule.name}) ${d.action}`];
135
+ out.push("", `### ${d.decision}`, BUILDER_LABEL, `Goal: ${d.goal}`, ...line, `Measure: ${d.measure}`);
136
+ }
137
+ for (const b of keptBreaks) {
138
+ const rule = ruleOf(b.rule);
139
+ out.push("", `### Rule broken on purpose: ${rule.id} (${rule.name})`, BUILDER_LABEL, `Effect: ${b.effect}`, `Check: ${b.check}`);
140
+ }
141
+ const undone = md.breaks.filter((b) => norm(b.piece) === piece && b.status === "reverted" && !unknownBreaks.has(b));
142
+ if (undone.length > 0) {
143
+ out.push("", BUILDER_LABEL);
144
+ for (const b of undone) {
145
+ const rule = ruleOf(b.rule);
146
+ out.push(`Tried and undone: ${rule.id} (${rule.name}), ${b.effect}`);
147
+ }
148
+ }
149
+ if (own.length === 0) {
150
+ gaps.push(`${goal.piece}: no decision is logged.`);
151
+ }
152
+ }
153
+ if (checked && checked.status !== "met") {
154
+ gaps.push(`${goal.piece}: the effect is ${checked.status}, not met.`);
155
+ }
156
+ }
157
+
158
+ out.push("", "## Gaps", "");
159
+ out.push(...(gaps.length > 0 ? gaps.map((g) => `- ${g}`) : ["None."]));
160
+ return { text: `${out.join("\n")}\n`, gaps };
161
+ }
@@ -0,0 +1,343 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { toUrl } from "../browser.mjs";
7
+ import { isAssetGoal, readLazuliMd } from "../project/lazuli-md.mjs";
8
+ import { gateStatus as realGateStatus } from "../project/gate.mjs";
9
+ import { identity } from "../project/match.mjs";
10
+ import { readEdits, recordEdit } from "../project/edits.mjs";
11
+ import { writeFileAtomic } from "../project/records.mjs";
12
+ import { isLoopbackHost } from "../project/tasks.mjs";
13
+ import { KIT_RULES_DIR, loadKit } from "../rules/load.mjs";
14
+
15
+ // Implementation tolerances, not rules. The cap is the whole budget of one edit, for every target together.
16
+ export const HOOK_CHECK_CAP_MS = 150000;
17
+ export const HOOK_WIDTHS = [1440];
18
+ export const MAX_HOOK_TARGETS = 3;
19
+ export const ADDITIONAL_CONTEXT_CAP = 4000;
20
+
21
+ const KIT_BIN = fileURLToPath(new URL("../../bin/lazuli.mjs", import.meta.url));
22
+ const HTML = new Set([".html", ".htm"]);
23
+ const STYLE = new Set([".css"]);
24
+ // Component and preprocessor files: watched only when a goal has a URL Target (a dev server renders them).
25
+ const SOURCE = new Set([".jsx", ".tsx", ".vue", ".svelte", ".astro", ".scss", ".sass", ".less"]);
26
+ const CUT = " (cut; read the full report)";
27
+ const SILENT = { exitCode: 0, stdout: "" };
28
+
29
+ const out = (obj) => ({ exitCode: 0, stdout: JSON.stringify(obj) });
30
+ const firstLine = (text) => String(text ?? "").split(/\r?\n/).map((l) => l.trim()).find((l) => l !== "") ?? "unknown error";
31
+ function isUrlTarget(target, cwd) {
32
+ try {
33
+ return !toUrl(target, cwd).startsWith("file:");
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ function isLocalhost(target, cwd) {
40
+ try {
41
+ return isLoopbackHost(new URL(toUrl(target, cwd)).hostname);
42
+ } catch {
43
+ return false;
44
+ }
45
+ }
46
+
47
+ function isExistingFile(target, cwd) {
48
+ const url = toUrl(target, cwd);
49
+ return url.startsWith("file:") && existsSync(fileURLToPath(url));
50
+ }
51
+
52
+ function inside(child, parent) {
53
+ const norm = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
54
+ const rel = path.relative(norm(parent), norm(child));
55
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
56
+ }
57
+
58
+ // Stops a check and everything it started (check-design starts a browser).
59
+ function killTree(child) {
60
+ try {
61
+ if (process.platform === "win32") {
62
+ spawnSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true });
63
+ } else {
64
+ process.kill(-child.pid, "SIGKILL");
65
+ }
66
+ } catch {
67
+ // already gone
68
+ }
69
+ }
70
+
71
+ // The areas the hook checks: every area check-design would load for this project (the kit, or
72
+ // LAZULI_RULES_DIR, and the project's learned rules) except motion and content, which do not fit the hook's
73
+ // budget: the motion recording, and the extreme content cases (a source open and six case pages per width).
74
+ // check-design --area motion runs after motion work, check-design --area content after writing copy.
75
+ async function hookAreas(cwd) {
76
+ const kit = await loadKit({ dirs: [process.env.LAZULI_RULES_DIR ?? KIT_RULES_DIR], projectDir: path.join(cwd, ".lazuli", "rules") });
77
+ return kit.areas.map((a) => a.area).filter((a) => a !== "motion" && a !== "content");
78
+ }
79
+
80
+ // Runs check-design in its own process, so a hung page can be stopped with its browser. A kit that cannot be
81
+ // loaded gives no check (never a run that would record motion).
82
+ function defaultRunCheck(bin) {
83
+ return async (target, cwd, capMs) => {
84
+ let areas;
85
+ try {
86
+ areas = await hookAreas(cwd);
87
+ } catch (err) {
88
+ return { status: 2, result: null, error: err?.message ?? String(err) };
89
+ }
90
+ return runChild(bin, target, cwd, capMs, areas);
91
+ };
92
+ }
93
+
94
+ function runChild(bin, target, cwd, capMs, areas) {
95
+ return new Promise((resolve) => {
96
+ let child;
97
+ try {
98
+ // --area goes after --json, so the target stays the argument after check-design.
99
+ child = spawn(process.execPath, [bin, "check-design", target, "--width", HOOK_WIDTHS.join(","), "--json", "--area", areas.join(",")], {
100
+ cwd,
101
+ // The check stops itself at this deadline even if this hook is killed first (an interrupt), so its browser goes too.
102
+ // LAZULI_SHEETS off, so the check writes no review sheet (the chart sheet) into the project on every edit.
103
+ env: { ...process.env, LAZULI_DEADLINE_MS: String(Math.max(1, Math.floor(capMs))), LAZULI_SHEETS: "off" },
104
+ windowsHide: true,
105
+ detached: process.platform !== "win32",
106
+ stdio: ["ignore", "pipe", "pipe"],
107
+ });
108
+ } catch (err) {
109
+ resolve({ status: 2, result: null, error: err?.message ?? String(err) });
110
+ return;
111
+ }
112
+ let stdout = "";
113
+ let stderr = "";
114
+ let done = false;
115
+ const finish = (value) => {
116
+ if (!done) {
117
+ done = true;
118
+ clearTimeout(timer);
119
+ resolve(value);
120
+ }
121
+ };
122
+ const timer = setTimeout(() => {
123
+ killTree(child);
124
+ // Do not wait for the pipes: a leftover grandchild could hold them open.
125
+ child.stdout.destroy();
126
+ child.stderr.destroy();
127
+ finish({ status: 2, result: null, error: `the check ran past ${Math.round(capMs / 100) / 10} s and was stopped` });
128
+ }, Math.max(0, capMs));
129
+ child.stdout.setEncoding("utf8");
130
+ child.stderr.setEncoding("utf8");
131
+ child.stdout.on("data", (d) => (stdout += d));
132
+ child.stderr.on("data", (d) => (stderr += d));
133
+ child.on("error", (err) => finish({ status: 2, result: null, error: err?.message ?? String(err) }));
134
+ child.on("close", (status) => {
135
+ if (status === 0 || status === 1) {
136
+ try {
137
+ finish({ status, result: JSON.parse(stdout), error: null });
138
+ return;
139
+ } catch {
140
+ finish({ status: 2, result: null, error: `check-design printed no report. ${stderr}` });
141
+ return;
142
+ }
143
+ }
144
+ finish({ status: status ?? 2, result: null, error: stderr || `check-design exited with ${status}` });
145
+ });
146
+ });
147
+ }
148
+
149
+ export function summarizeForAgent(result, file) {
150
+ const findings = result?.findings ?? [];
151
+ const fails = findings.filter((f) => f.level === "fail");
152
+ const hints = findings.filter((f) => f.level === "hint");
153
+ const parts = [`Lazuli check-design after editing ${file}: ${result?.target} at ${HOOK_WIDTHS.join(", ")} px, ${fails.length} fail, ${hints.length} hint.`];
154
+ if (fails.length > 0) {
155
+ parts.push(`Fails: ${fails.map((f) => `${f.ruleId} ${f.name}: ${String(f.message ?? "").replace(/\.+$/, "")}`).join("; ")}.`);
156
+ }
157
+ if ((result?.uncheckedNorms ?? []).length > 0) {
158
+ parts.push(`Not checked (measurer failed): ${result.uncheckedNorms.join(", ")}.`);
159
+ }
160
+ parts.push(`Full report: ${result?.reportPath}.`);
161
+ return capText(parts.join(" "));
162
+ }
163
+
164
+ function capText(text) {
165
+ return text.length <= ADDITIONAL_CONTEXT_CAP ? text : `${text.slice(0, ADDITIONAL_CONTEXT_CAP - CUT.length)}${CUT}`;
166
+ }
167
+
168
+ const couldNotCheck = (target, error) => `Lazuli could not check ${target} after this edit: ${firstLine(error).replace(/\.+$/, "")}. The edit is not blocked.`;
169
+
170
+ // A goal Target that cannot be read as a URL or path is reported, never thrown.
171
+ function pickTargets(file, ext, md, cwd) {
172
+ if (HTML.has(ext)) {
173
+ return { targets: [file], skipped: 0, bad: [] };
174
+ }
175
+ const seen = new Set();
176
+ const found = [];
177
+ const bad = [];
178
+ for (const g of md.goals ?? []) {
179
+ // A derived piece or a symbol is not a page: it is checked with --asset, so it never takes a page's place.
180
+ if (!g.target || isAssetGoal(g)) {
181
+ continue;
182
+ }
183
+ try {
184
+ if (!(isExistingFile(g.target, cwd) || isLocalhost(g.target, cwd))) {
185
+ continue;
186
+ }
187
+ const id = identity(g.target, cwd);
188
+ if (!seen.has(id)) {
189
+ seen.add(id);
190
+ found.push(g.target);
191
+ }
192
+ } catch (err) {
193
+ bad.push(couldNotCheck(g.target, err?.message ?? String(err)));
194
+ }
195
+ }
196
+ return { targets: found.slice(0, MAX_HOOK_TARGETS), skipped: Math.max(0, found.length - MAX_HOOK_TARGETS), bad };
197
+ }
198
+
199
+ // Each check of an edit overwrites .lazuli/report.json, so the hook keeps its own copy per target:
200
+ // .lazuli/reports/hook-<n>.json, n the 1-based target index in this edit (replaced by the next edit).
201
+ async function keepReport(result, cwd, n) {
202
+ const copy = path.join(cwd, ".lazuli", "reports", `hook-${n}.json`);
203
+ try {
204
+ await fs.mkdir(path.dirname(copy), { recursive: true });
205
+ await writeFileAtomic(copy, JSON.stringify(result, null, 2));
206
+ return { ...result, reportPath: copy };
207
+ } catch {
208
+ return result;
209
+ }
210
+ }
211
+
212
+ const inputCwd = (input) => path.resolve(typeof input?.cwd === "string" && input.cwd !== "" ? input.cwd : process.cwd());
213
+
214
+ // The project folder install-hooks wrote in the args (--project) wins over the session cwd, which can be a subfolder.
215
+ // An install made before that option has none, and the session cwd is used as before.
216
+ const projectOf = (sessionCwd, deps) => (typeof deps.projectDir === "string" && deps.projectDir !== "" ? path.resolve(deps.projectDir) : sessionCwd);
217
+
218
+ export async function handlePostEdit(input, deps = {}) {
219
+ const started = Date.now();
220
+ const capMs = deps.capMs ?? HOOK_CHECK_CAP_MS;
221
+ const runCheck = deps.runCheck ?? defaultRunCheck(deps.bin ?? KIT_BIN);
222
+ const sessionCwd = inputCwd(input);
223
+ const cwd = projectOf(sessionCwd, deps);
224
+ const raw = input?.tool_input?.file_path;
225
+ if (typeof raw !== "string" || raw === "") {
226
+ return SILENT;
227
+ }
228
+ const md = await readLazuliMd(cwd);
229
+ if (md === null) {
230
+ return SILENT;
231
+ }
232
+ // A relative file_path is relative to where the session is, not to the project folder.
233
+ const file = path.resolve(sessionCwd, raw);
234
+ if (inside(file, path.join(cwd, ".lazuli"))) {
235
+ return SILENT;
236
+ }
237
+ const ext = path.extname(file).toLowerCase();
238
+ const watched = HTML.has(ext) || STYLE.has(ext) || (SOURCE.has(ext) && (md.goals ?? []).some((g) => g.target && isUrlTarget(g.target, cwd)));
239
+ if (!watched) {
240
+ return SILENT;
241
+ }
242
+
243
+ const notes = [];
244
+ try {
245
+ await recordEdit({ cwd, sessionId: input.session_id, file });
246
+ } catch (err) {
247
+ notes.push(`Lazuli could not record this edit in .lazuli/edits.json: ${firstLine(err?.message)}`);
248
+ }
249
+
250
+ const { targets, skipped, bad } = pickTargets(file, ext, md, cwd);
251
+ if (skipped > 0) {
252
+ notes.push(`${skipped} more goal target${skipped === 1 ? " was" : "s were"} skipped (at most ${MAX_HOOK_TARGETS} per edit); run check-design on ${skipped === 1 ? "it" : "them"} by hand.`);
253
+ }
254
+ const summaries = [];
255
+ const failures = [...bad];
256
+ const notReached = [];
257
+ for (const [i, target] of targets.entries()) {
258
+ const left = capMs - (Date.now() - started);
259
+ if (left <= 0) {
260
+ notReached.push(target);
261
+ continue;
262
+ }
263
+ let r;
264
+ try {
265
+ r = await runCheck(target, cwd, left);
266
+ } catch (err) {
267
+ r = { status: 2, result: null, error: err?.message ?? String(err) };
268
+ }
269
+ if ((r?.status === 0 || r?.status === 1) && r.result) {
270
+ summaries.push(summarizeForAgent(await keepReport(r.result, cwd, i + 1), file));
271
+ } else {
272
+ failures.push(couldNotCheck(target, r?.error));
273
+ }
274
+ }
275
+ if (notReached.length > 0) {
276
+ notes.push(`Not checked, the time ran out: ${notReached.join(", ")}.`);
277
+ }
278
+
279
+ const obj = {};
280
+ if (summaries.length > 0) {
281
+ obj.hookSpecificOutput = { hookEventName: "PostToolUse", additionalContext: capText([...summaries, ...notes].join("\n")) };
282
+ }
283
+ const message = [...failures, ...(summaries.length > 0 ? [] : notes)];
284
+ if (message.length > 0) {
285
+ obj.systemMessage = message.join(" ");
286
+ }
287
+ return Object.keys(obj).length > 0 ? out(obj) : SILENT;
288
+ }
289
+
290
+ // The session id the post-edit hook used for this session (recordEdit files a missing id under "unknown").
291
+ function sessionKey(id) {
292
+ return id === undefined || id === null || String(id) === "__proto__" ? "unknown" : String(id);
293
+ }
294
+
295
+ const oneLine = (items) => items.map((i) => String(i).replace(/\.+$/, "")).join("; ");
296
+
297
+ export async function handleStop(input, deps = {}) {
298
+ const gateStatus = deps.gateStatus ?? realGateStatus;
299
+ const cwd = projectOf(inputCwd(input), deps);
300
+ const md = await readLazuliMd(cwd);
301
+ if (md === null) {
302
+ return SILENT;
303
+ }
304
+ const edits = await readEdits(cwd);
305
+ // An edits.json that cannot be read may hide an edit of this session, so it counts as edited.
306
+ if (!edits.corrupt && !Object.hasOwn(edits.sessions, sessionKey(input?.session_id))) {
307
+ return SILENT;
308
+ }
309
+ let gate;
310
+ try {
311
+ gate = await gateStatus({ cwd, md });
312
+ } catch (err) {
313
+ if (err?.code !== "RECORD_INVALID") {
314
+ throw err;
315
+ }
316
+ const problems = Array.isArray(err.problems) && err.problems.length > 0 ? err.problems : [err.message];
317
+ gate = { mode: md.mode ?? "director", passed: false, items: problems, notes: [] };
318
+ }
319
+ if (gate.passed) {
320
+ return SILENT;
321
+ }
322
+ const delegate = gate.mode === "delegate";
323
+ const active = input?.stop_hook_active === true;
324
+ if (gate.items.length === 0) {
325
+ // Nothing is gated (no goal has a Target): never block on an empty list.
326
+ if (!delegate || active || gate.notes.length === 0) {
327
+ return SILENT;
328
+ }
329
+ return out({ systemMessage: `Lazuli effect gate (delegate mode) has nothing it can check: ${gate.notes.join(" ")}` });
330
+ }
331
+ if (delegate && !active) {
332
+ return out({
333
+ decision: "block",
334
+ reason: [
335
+ "Lazuli effect gate (delegate mode) is open:",
336
+ ...gate.items.map((i) => `- ${i}`),
337
+ "Record the checks (capture, first look, review-design), and review the breaks with review-design or revert them, then finish. To turn this gate off: lazuli install-hooks --remove.",
338
+ ].join("\n"),
339
+ });
340
+ }
341
+ const label = delegate ? "delegate mode, already asked once" : "director mode";
342
+ return out({ systemMessage: `Lazuli effect gate (${label}) is open: ${oneLine(gate.items)}. You decide whether to deliver.` });
343
+ }
@@ -0,0 +1,120 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { writeFileAtomic } from "../project/records.mjs";
5
+
6
+ const KIT_BIN = fileURLToPath(new URL("../../bin/lazuli.mjs", import.meta.url));
7
+
8
+ export class SettingsError extends Error {
9
+ constructor(file, why) {
10
+ super(`${file} is not valid JSON; left untouched.${why ? ` (${why})` : ""}`);
11
+ this.name = "SettingsError";
12
+ this.code = "SETTINGS_INVALID";
13
+ this.file = file;
14
+ }
15
+ }
16
+
17
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
18
+
19
+ export function isLazuliHandler(h) {
20
+ return isObject(h) && Array.isArray(h.args) && h.args[1] === "hook" && typeof h.args[0] === "string" && h.args[0].endsWith("lazuli.mjs");
21
+ }
22
+
23
+ // The project folder goes in the args: the hook input cwd follows the session, which can move into a subfolder.
24
+ function entries(execPath, bin, projectDir) {
25
+ return {
26
+ PostToolUse: { matcher: "Edit|Write", hooks: [{ type: "command", command: execPath, args: [bin, "hook", "post-edit", "--project", projectDir], timeout: 180 }] },
27
+ Stop: { hooks: [{ type: "command", command: execPath, args: [bin, "hook", "stop", "--project", projectDir], timeout: 30 }] },
28
+ };
29
+ }
30
+
31
+ async function readSettings(file) {
32
+ let text;
33
+ try {
34
+ text = await fs.readFile(file, "utf8");
35
+ } catch (err) {
36
+ if (err?.code === "ENOENT") {
37
+ return { settings: {}, text: null };
38
+ }
39
+ throw err;
40
+ }
41
+ let settings;
42
+ try {
43
+ settings = JSON.parse(text.replace(/^/, ""));
44
+ } catch (err) {
45
+ throw new SettingsError(file, err?.message);
46
+ }
47
+ if (!isObject(settings)) {
48
+ throw new SettingsError(file, "the file must hold an object");
49
+ }
50
+ if (settings.hooks !== undefined) {
51
+ if (!isObject(settings.hooks)) {
52
+ throw new SettingsError(file, "hooks must be an object");
53
+ }
54
+ for (const [event, groups] of Object.entries(settings.hooks)) {
55
+ if (!Array.isArray(groups) || groups.some((g) => !isObject(g) || (g.hooks !== undefined && !Array.isArray(g.hooks)))) {
56
+ throw new SettingsError(file, `hooks.${event} must be a list of groups with a hooks list`);
57
+ }
58
+ }
59
+ }
60
+ return { settings, text };
61
+ }
62
+
63
+ // Takes the Lazuli handlers out of every event. Only groups and events that this emptied are deleted.
64
+ function strip(hooks) {
65
+ let removed = 0;
66
+ for (const event of Object.keys(hooks)) {
67
+ const groups = hooks[event];
68
+ let emptied = false;
69
+ const kept = [];
70
+ for (const g of groups) {
71
+ const own = (g.hooks ?? []).filter(isLazuliHandler).length;
72
+ if (own === 0) {
73
+ kept.push(g);
74
+ continue;
75
+ }
76
+ removed += own;
77
+ const rest = g.hooks.filter((h) => !isLazuliHandler(h));
78
+ if (rest.length > 0) {
79
+ kept.push({ ...g, hooks: rest });
80
+ } else {
81
+ emptied = true;
82
+ }
83
+ }
84
+ if (kept.length === 0 && emptied) {
85
+ delete hooks[event];
86
+ } else {
87
+ hooks[event] = kept;
88
+ }
89
+ }
90
+ return removed;
91
+ }
92
+
93
+ // Adds (or with remove, takes out) the Lazuli hooks in <projectDir>/.claude/settings.local.json. Every other key
94
+ // and hook is kept. The file is written only when its content changes.
95
+ export async function installHooks({ projectDir = process.cwd(), remove = false, execPath = process.execPath, bin = KIT_BIN } = {}) {
96
+ const file = path.join(path.resolve(projectDir), ".claude", "settings.local.json");
97
+ const { settings, text } = await readSettings(file);
98
+ const before = JSON.stringify(settings);
99
+ const hadHooks = settings.hooks !== undefined;
100
+ const hooks = settings.hooks ?? {};
101
+ const removed = strip(hooks);
102
+ if (!remove) {
103
+ for (const [event, group] of Object.entries(entries(execPath, bin, path.resolve(projectDir)))) {
104
+ hooks[event] = [...(hooks[event] ?? []), group];
105
+ }
106
+ }
107
+ // A hooks object that only the Lazuli handlers filled goes away with them.
108
+ if (Object.keys(hooks).length > 0 || (hadHooks && removed === 0)) {
109
+ settings.hooks = hooks;
110
+ } else {
111
+ delete settings.hooks;
112
+ }
113
+ const changed = JSON.stringify(settings) !== before || (text === null && !remove);
114
+ if (changed) {
115
+ await fs.mkdir(path.dirname(file), { recursive: true });
116
+ // Temp file + rename, so a crash mid-write never leaves a cut settings file.
117
+ await writeFileAtomic(file, `${JSON.stringify(settings, null, 2)}\n`);
118
+ }
119
+ return { file, changed, removed };
120
+ }