Displays lesson hint cards when tool calls match known patterns. Advisory only: a lesson never blocks a tool call.

Not listed in any marketplace.
Retired 2026-10-23. It duplicated the hq-ext lesson guard with different matching rules (#4730) and was already disabled on the operator's machine. The source stays here as the test mod for tests/probes/function-hooks-probe.sh and the CC contract probe. Its useful idea (one short card with numbered answers: why, knew it, dismiss) moves to the guard's advisory text.
Displays lesson hint cards when tool calls match known patterns. Advisory only: a lesson never blocks a tool call (operator word 2026-10-21). The classic hq-ext pretool-lesson-guard is advisory too as of Yonatan-HQ/hq-ext-plugin#2449.
Requires Claude Code 2.1.266 or later (first measured classic.* binary).
bash cp -r mods/lesson-cards/ /path/to/your/project/mods/ ``bash export CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 ``Or in ~/.claude/settings.json:
{
"env": {
"CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1"
}
}
bash claude --plugin-dir mods/ ``~/.claude/hq/floor-*/lessons.md and indexes by command tokens{ deny } and never opens a dialog. A block-severity pattern's context starts with BLOCK-SEVERITY LESSON (advisory, not enforced): and keeps the lesson text and its Fix (including any ALLOWED-FORM line). When several patterns match an Edit or Write, a block match always ranks before a warncontext line. ORK_LESSON_CARDS_CARD_ONLY_DIRS (card-only lanes, 1.1.x) is no longer read: every session now behaves the way a card-only lane did| Event | Matcher | Notes |
|---|---|---|
session.start | {} | Load corpus (patterns + bullets) |
tool.call | { tool: 'Bash' } | Match command, return context |
tool.call | { tool: 'Edit' } | Match file/content, return context |
tool.call | { tool: 'Write' } | Match file/content, return context |
ui.render | { component: 'ToolUse' } | Wrap the row and the card in a column Box built from $.ui.resolve(e) |
command.register | {} | Handle /lessons command |
$.env.get - Read HOME$.fs.read - Read lesson-patterns.json and lessons.md files$.fs.list - List hq-ext versions and floor directories$.fs.exists - Skip floor dirs with no lessons.md before any stat (no logged ENOENT per dir); absent on older engines, then stat-only$.fs.stat - Get file mtimes for sorting$.ui.notice - Show hint during permission dialog (if open)$.ui.resolve - The element constructors (Box, Text) the card is built from. On CC 2.1.282 a render hook may only return nodes built by these; a plain { type: 'Box' } object draws nothing, and the tree next(e) returns is an opaque engine node that must be wrapped, never mutated$.ui.invalidate - Refresh UI after /lessons reloadprocess.runhttp.fetchtool.call (all reads happen at session.start)bash rm -rf mods/lesson-cards # or claude plugin disable lesson-cards ``bash unset CLAUDE_CODE_ENABLE_FUNCTION_HOOKS ``No state persisted except the in-memory match map, which is safe to drop.
/lessons - Reload corpus from hq-ext cache and lessons.md fileslesson-cards matches before the tool runs, so its card and context come before the classic guards inside next(e). The quoted parts of a command are blanked before matching (shell-faithful), so a pattern inside an echo "..." string matches nothing; it has to be in the command itself. Patterns with a repos list (for example the platform ones) match only in that repo.
Harmless ways to see each surface (measured on CC 2.1.282, 2026-09-25):
echo pgvector/pgvector:pg16 matches pgvector-pg-version-mismatch and draws a yellow card under the row.git ls-files mods | grep register matches git-ls-files-quotepath-blind and draws a red card; the call still runs, and the model reads the lesson marked advisory.Other ways that also work:
/lessons command reloads corpusLow. Advisory only; the only behavioral change is one extra context line per matched call.
hooks/register.ts 336 lines1/**
2 * Hook registration for lesson-cards.
3 *
4 * Events:
5 * - session.start: Load corpus (patterns + bullets)
6 * - tool.call{tool=Bash}: Match command, return context
7 * - tool.call{tool=Edit}: Match file/content, return context
8 * - tool.call{tool=Write}: Match file/content, return context
9 * - ui.render{component=ToolUse}: Append card under tool row
10 * - command.run{command=lessons}: /lessons reload (declared with $.command.register at session start)
11 *
12 * Advisory only: a lesson never blocks a tool call. Every match, block or
13 * warn severity, in every session, adds a card and model context and the
14 * call runs. No refusal, no dialog (operator word 2026-10-21).
15 *
16 * Hooks module format: exports register(on, options); $ is only ever used
17 * as $.noun.event(...), so all $-taking helpers live in this file.
18 */
19
20import {
21 parseLessonsMd,
22 joinPath,
23 type Corpus,
24 type LessonPattern,
25 type LessonBullet,
26} from '../src/corpus.js';
27import { matchAll, matchFileEdit } from '../src/match.js';
28import { buildCard, formatContext, type CardElements } from '../src/card.js';
29import type { MatchedLesson } from '../src/types.js';
30
31/** Minimal $ facade for the events this module uses. */
32type Hook$ = {
33 env: {
34 get: (name: string) => Promise<string | undefined>;
35 };
36 fs: {
37 read: (path: string) => Promise<string>;
38 list: (path: string) => Promise<Array<{ name: string; kind: 'file' | 'dir' | 'other' }> | null>;
39 stat: (path: string) => Promise<{ size: number; mtimeMs: number; kind: 'file' | 'dir' | 'other' } | null>;
40 /** true or false, never a logged failure; absent on engines that predate it. */
41 exists: (path: string) => Promise<boolean>;
42 };
43 ui: {
44 notice: (toolUseId: string, message: string) => Promise<void>;
45 invalidate: (component: string) => Promise<void>;
46 /** The element constructors this render may return (Box, Text, ...). */
47 resolve: (e: UiRenderEvent) => Promise<CardElements>;
48 };
49 command: {
50 register: (spec: { name: string; description: string }) => Promise<unknown>;
51 };
52};
53
54type ToolCallEvent = {
55 tool: string;
56 tool_use_id?: string;
57 [argument: string]: unknown;
58};
59
60type UiRenderEvent = {
61 component: string;
62 requestId?: string;
63};
64
65type NextFn<E> = (ev: E) => Promise<unknown>;
66
67type SessionStartEvent = { cwd: string; isInteractive: boolean };
68
69// Module-scope state (per session)
70let corpus: Corpus | null = null;
71const matchMap = new Map<string, MatchedLesson[]>();
72
73/**
74 * Find the newest hq-ext version directory.
75 */
76async function findNewestHqExt($: Hook$, home: string): Promise<string | null> {
77 const cacheBase = joinPath(home, '.claude', 'plugins', 'cache', 'yonatan-hq', 'hq-ext');
78
79 try {
80 const entries = await $.fs.list(cacheBase);
81 if (!entries || entries.length === 0) return null;
82
83 // Sort by version, highest first
84 const versions = entries
85 .filter(e => e.kind === 'dir')
86 .map(e => e.name)
87 .sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
88
89 return versions.length > 0 ? joinPath(cacheBase, versions[0]) : null;
90 } catch {
91 return null;
92 }
93}
94
95/**
96 * Load lesson-patterns.json from hq-ext cache.
97 */
98async function loadPatterns($: Hook$, hqExtPath: string): Promise<LessonPattern[]> {
99 const configPath = joinPath(hqExtPath, 'configs', 'lesson-patterns.json');
100 try {
101 const content = await $.fs.read(configPath);
102 if (typeof content !== 'string') return [];
103 const parsed = JSON.parse(content) as unknown;
104 return Array.isArray(parsed) ? (parsed as LessonPattern[]) : [];
105 } catch {
106 return [];
107 }
108}
109
110/**
111 * Load newest three lessons.md files.
112 */
113async function loadLessonsMds($: Hook$, home: string): Promise<LessonBullet[]> {
114 const hqBase = joinPath(home, '.claude', 'hq');
115 const allBullets: LessonBullet[] = [];
116
117 try {
118 // Find floor directories
119 const hqEntries = await $.fs.list(hqBase);
120 if (!hqEntries) return [];
121
122 const floorDirs = hqEntries
123 .filter(e => e.kind === 'dir' && e.name.startsWith('floor-'))
124 .map(e => joinPath(hqBase, e.name));
125
126 // Collect lessons.md files with their mtime
127 const lessonsFiles: { path: string; mtime: number }[] = [];
128 for (const dir of floorDirs) {
129 const lessonsPath = joinPath(dir, 'lessons.md');
130 // Most floor dirs have no lessons.md: ask fs.exists first, so the engine does not log a
131 // failed fs.stat (ENOENT) for each of them (88 such lines per session start, measured
132 // 2026-10-20). An engine without fs.exists keeps the old stat-only path.
133 // $ is only ever called as $.noun.event(...) (the validator refuses a feature test such as
134 // `if ($.fs.exists)`), so an engine without fs.exists is detected by its throw: null = unknown,
135 // and the old stat-only path runs.
136 let present: boolean | null = null;
137 try {
138 present = (await $.fs.exists(lessonsPath)) === true;
139 } catch {
140 present = null;
141 }
142 if (present === false) continue;
143 try {
144 const stat = await $.fs.stat(lessonsPath);
145 if (stat && stat.kind === 'file') {
146 lessonsFiles.push({ path: lessonsPath, mtime: stat.mtimeMs });
147 }
148 } catch {
149 // File doesn't exist, skip
150 }
151 }
152
153 // Sort by mtime, newest first, take top 3
154 lessonsFiles.sort((a, b) => b.mtime - a.mtime);
155 const newest = lessonsFiles.slice(0, 3);
156
157 for (const { path } of newest) {
158 try {
159 const content = await $.fs.read(path);
160 if (typeof content === 'string') {
161 allBullets.push(...parseLessonsMd(content));
162 }
163 } catch {
164 // Skip files we can't read
165 }
166 }
167 } catch {
168 // hq directory doesn't exist
169 }
170
171 return allBullets;
172}
173
174/**
175 * Load the full corpus at session.start.
176 */
177async function loadCorpus($: Hook$): Promise<Corpus> {
178 // A mod has no process.env: HOME comes from $.env (types/claude-code.d.ts `$.env.get("HOME")`).
179 // On Windows HOME is normally unset and USERPROFILE set, so read it second through the
180 // same env reader. Never read the process global: a mod worker does not have it.
181 const home =
182 (await $.env.get('HOME').catch(() => undefined)) ||
183 (await $.env.get('USERPROFILE').catch(() => undefined)) ||
184 '';
185 const startTime = Date.now();
186
187 // No home means every corpus path would be relative and resolve under the session's cwd.
188 if (!home) {
189 return { patterns: [], bullets: [], loadedAt: startTime, loadError: 'HOME and USERPROFILE are not set' };
190 }
191
192 try {
193 const hqExtPath = await findNewestHqExt($, home);
194
195 const [patterns, bullets] = await Promise.all([
196 hqExtPath ? loadPatterns($, hqExtPath) : Promise.resolve([] as LessonPattern[]),
197 loadLessonsMds($, home),
198 ]);
199
200 return {
201 patterns,
202 bullets,
203 loadedAt: Date.now(),
204 };
205 } catch (err) {
206 return {
207 patterns: [],
208 bullets: [],
209 loadedAt: startTime,
210 loadError: err instanceof Error ? err.message : 'Unknown error',
211 };
212 }
213}
214
215/**
216 * Match one tool call against the corpus: Bash by command, Edit and Write by
217 * file path and new content. Pure over its inputs; the hook owns all I/O.
218 */
219function matchToolCall(e: ToolCallEvent, loaded: Corpus): MatchedLesson[] {
220 const args: Record<string, unknown> = e;
221 if (e.tool === 'Bash') {
222 const command = String(args.command || '');
223 return command ? matchAll(command, loaded.patterns, loaded.bullets) : [];
224 }
225 if (e.tool === 'Edit') {
226 const filePath = String(args.file_path || '');
227 const newContent = String(args.new_string || args.content || '');
228 return filePath ? matchFileEdit(filePath, newContent, loaded.patterns, 'Edit') : [];
229 }
230 if (e.tool === 'Write') {
231 const filePath = String(args.file_path || '');
232 const content = String(args.content || '');
233 return filePath ? matchFileEdit(filePath, content, loaded.patterns, 'Write') : [];
234 }
235 return [];
236}
237
238/**
239 * Register the lesson-cards hooks.
240 */
241export function register(on: (event: string, matcherOrHook: unknown, hook?: unknown) => void, _options?: unknown): void {
242 on('session.start', async ($: Hook$, e: SessionStartEvent, next: NextFn<SessionStartEvent>) => {
243 // Register first: CC skips the whole hook when session.start throws, so a
244 // corpus load failure must never take the /lessons command down with it
245 // (measured on a Windows screen 2026-10-05: "Unknown command: /lessons").
246 await $.command.register({ name: 'lessons', description: 'Reload the lesson cards corpus' });
247 matchMap.clear();
248 corpus = await loadCorpus($).catch((err: unknown) => ({
249 patterns: [],
250 bullets: [],
251 loadedAt: Date.now(),
252 loadError: err instanceof Error ? err.message : 'Unknown error',
253 }));
254 return next(e);
255 });
256
257 on('tool.call', async ($: Hook$, e: ToolCallEvent, next?: NextFn<ToolCallEvent>) => {
258 const requestId = e.tool_use_id || `tool-${Date.now()}`;
259
260 if (!corpus) {
261 return next ? ((await next(e)) ?? {}) : {};
262 }
263
264 // Match before the tool runs, so the card and context ride with the call.
265 const matches = matchToolCall(e, corpus);
266 if (matches.length === 0) {
267 return next ? ((await next(e)) ?? {}) : {};
268 }
269
270 // Store matches for ui.render: the card draws under this tool row.
271 matchMap.set(requestId, matches);
272
273 // Try to show notice during permission dialog (only works if dialog is open)
274 try {
275 await $.ui.notice(requestId, `lesson: ${matches[0].id}`);
276 } catch {
277 // Notice refused - dialog not open, ignore
278 }
279
280 // Advisory only: the lesson rides along as context and the call runs.
281 // A block-severity lesson is marked as such, but nothing is enforced.
282 const context = formatContext(matches[0]);
283
284 // A hook adds to the context its next() returned and never replaces it:
285 // CC reads an answer that drops an entry a hook below attached as the
286 // wrong shape and skips this hook.
287 const result = (next ? ((await next(e)) ?? {}) : {}) as Record<string, unknown>;
288 const prior = Array.isArray(result.context)
289 ? (result.context as unknown[]).filter((c): c is string => typeof c === 'string' && c !== '')
290 : [];
291 return { ...result, context: prior.includes(context) ? prior : [...prior, context] };
292 });
293
294 // Wrap, never mutate: next(e) hands back an opaque engine node ({ type, ref }),
295 // so the card goes beside it in a new column Box built from $.ui.resolve(e).
296 on('ui.render', { component: 'ToolUse' }, async ($: Hook$, e: UiRenderEvent, next?: NextFn<UiRenderEvent>) => {
297 const tree = next ? await next(e) : null;
298
299 if (e.component !== 'ToolUse' || !e.requestId) {
300 return tree;
301 }
302
303 const matches = matchMap.get(e.requestId);
304 if (!matches || matches.length === 0) {
305 return tree;
306 }
307
308 const el = await $.ui.resolve(e);
309 const card = buildCard(matches[0], e.requestId, el);
310 return el.Box({ flexDirection: 'column', children: tree ? [tree, card] : [card] });
311 });
312
313 on('command.run', { command: 'lessons' }, async ($: Hook$) => {
314 corpus = await loadCorpus($).catch((err: unknown) => ({
315 patterns: [],
316 bullets: [],
317 loadedAt: Date.now(),
318 loadError: err instanceof Error ? err.message : 'Unknown error',
319 }));
320 matchMap.clear();
321 try {
322 await $.ui.invalidate('ui.render');
323 } catch {
324 // nothing drawn yet: nothing to refresh
325 }
326 const n = corpus ? corpus.patterns.length + corpus.bullets.length : 0;
327 if (n === 0) {
328 const reason = corpus?.loadError ? `: ${corpus.loadError}` : '';
329 return {
330 text: `Lessons reloaded (0 entries)${reason}. Lessons come from configs/lesson-patterns.json in the newest hq-ext cache and ~/.claude/hq/floor-*/lessons.md.`,
331 };
332 }
333 return { text: `Lessons reloaded (${n} entries)` };
334 });
335}
336src/corpus.ts 93 lines1/**
2 * Corpus types and parser for lesson-cards.
3 *
4 * The corpus is assembled from:
5 * - configs/lesson-patterns.json from newest hq-ext under cache
6 * - ~/.claude/hq/floor-N/lessons.md (newest three floor dirs)
7 *
8 * This module is pure: types, path helpers and the lessons.md parser.
9 * The fs reads happen in the hooks module (register.ts) at session.start
10 * or on /lessons reload, never inside tool.call.
11 */
12
13/** Slash-joined path segments; sufficient for read-only fs access on all platforms. */
14export function joinPath(...parts: string[]): string {
15 return parts.filter(p => p.length > 0).join('/');
16}
17
18/** One entry from hq-ext's configs/lesson-patterns.json */
19export interface LessonPattern {
20 id: string;
21 /** Corpus entry kind: simple, window-check, block-check or dockerfile-check. */
22 type?: string;
23 severity: 'block' | 'warn';
24 category: string;
25 pattern?: string;
26 trigger_pattern?: string;
27 block_pattern?: string;
28 check_patterns?: string[];
29 require_pattern?: string;
30 file_glob?: string;
31 file_match?: string;
32 exclude_paths?: string[];
33 tool_names?: string[];
34 message: string;
35 why?: string;
36 example_fix?: string;
37 /** One exact command the lesson accepts (hq-ext lesson-patterns.json field). */
38 allowed_form?: string;
39 window_lines?: number;
40 repos?: string[];
41}
42
43/** One bullet parsed from lessons.md */
44export interface LessonBullet {
45 heading: string;
46 text: string;
47 tokens: string[]; // First N tokens for indexing
48}
49
50/** In-memory corpus loaded at session.start */
51export interface Corpus {
52 patterns: LessonPattern[];
53 bullets: LessonBullet[];
54 loadedAt: number;
55 loadError?: string;
56}
57
58/**
59 * Parse a lessons.md file into indexed bullets.
60 *
61 * Format:
62 * ## heading
63 * - bullet text
64 * - bullet text
65 */
66export function parseLessonsMd(content: string): LessonBullet[] {
67 const bullets: LessonBullet[] = [];
68 let currentHeading = '';
69
70 for (const line of content.split('\n')) {
71 const headingMatch = /^##\s+(.+)$/.exec(line);
72 if (headingMatch) {
73 currentHeading = headingMatch[1].trim();
74 continue;
75 }
76
77 const bulletMatch = /^-\s+(.+)$/.exec(line);
78 if (bulletMatch && currentHeading) {
79 const text = bulletMatch[1].trim();
80 // Extract first few command tokens for indexing
81 // Tokens like 'gh', 'git', 'pnpm', 'herdr', 'vm_stat', etc.
82 const tokens = text.split(/\s+/).slice(0, 3).filter(t => /^[a-z_-]/i.test(t));
83 bullets.push({
84 heading: currentHeading,
85 text,
86 tokens,
87 });
88 }
89 }
90
91 return bullets;
92}
93src/match.ts 534 lines1/**
2 * Pattern matcher for lesson-cards.
3 *
4 * Pure matching logic:
5 * - For Bash: blank heredoc bodies and quoted strings first, then run pattern table
6 * - For Edit/Write: match file_path against file_glob, content against check_patterns
7 *
8 * No external dependencies - uses simple glob matching.
9 */
10
11import type { LessonPattern, LessonBullet } from './corpus.js';
12import type { MatchedLesson } from './types.js';
13
14/** Expand every closed {a,b} group into one pattern per alternative. */
15function expandBraces(pattern: string): string[] {
16 const open = pattern.indexOf('{');
17 if (open === -1) return [pattern];
18 const close = pattern.indexOf('}', open + 1);
19 if (close === -1) return [pattern];
20 const head = pattern.slice(0, open);
21 const tail = pattern.slice(close + 1);
22 return pattern
23 .slice(open + 1, close)
24 .split(',')
25 .flatMap(part => expandBraces(head + part + tail));
26}
27
28/**
29 * Simple glob pattern matching.
30 * Supports:
31 * - * matches any sequence of characters (except /)
32 * - ** matches any sequence including /
33 * - ? matches single character
34 * - {a,b} alternatives (one flat group per brace pair)
35 * - literal characters match themselves
36 */
37function simpleGlobMatch(str: string, pattern: string): boolean {
38 // {a,b} alternatives, as the hq-ext guard reads them (matchesFileGlob): one
39 // flat group, no nesting; a { with no closing } stays a literal character.
40 const alternatives = expandBraces(pattern);
41 if (alternatives.length > 1 || alternatives[0] !== pattern) {
42 return alternatives.some(alt => simpleGlobMatch(str, alt));
43 }
44
45 // Normalize pattern and string
46 const normalizedStr = str.replace(/\\/g, '/');
47 const normalizedPattern = pattern.replace(/\\/g, '/');
48
49 // Split pattern into segments
50 const patternParts = normalizedPattern.split('/');
51 const strParts = normalizedStr.split('/');
52
53 let patternIdx = 0;
54 let strIdx = 0;
55
56 while (patternIdx < patternParts.length && strIdx < strParts.length) {
57 const patPart = patternParts[patternIdx];
58 const strPart = strParts[strIdx];
59
60 if (patPart === '**') {
61 // ** matches zero or more path segments
62 patternIdx++;
63
64 // If this is the last pattern part, it matches everything remaining
65 if (patternIdx >= patternParts.length) {
66 return true;
67 }
68
69 // Try to match the remaining pattern at each position
70 while (strIdx <= strParts.length) {
71 const remainingStr = strParts.slice(strIdx).join('/');
72 const remainingPat = patternParts.slice(patternIdx).join('/');
73 if (simpleGlobMatch(remainingStr, remainingPat)) {
74 return true;
75 }
76 strIdx++;
77 }
78 return false;
79 } else {
80 // Match single segment
81 if (!segmentMatch(strPart, patPart)) {
82 return false;
83 }
84 patternIdx++;
85 strIdx++;
86 }
87 }
88
89 // Handle trailing ** that can match zero segments
90 while (patternIdx < patternParts.length && patternParts[patternIdx] === '**') {
91 patternIdx++;
92 }
93
94 return patternIdx === patternParts.length && strIdx === strParts.length;
95}
96
97/**
98 * Match a single path segment against a pattern.
99 */
100function segmentMatch(segment: string, pattern: string): boolean {
101 if (pattern === '*') {
102 return true;
103 }
104
105 // Simple pattern matching for single segment
106 let si = 0;
107 let pi = 0;
108
109 while (si < segment.length && pi < pattern.length) {
110 const pc = pattern[pi];
111
112 if (pc === '*') {
113 // * matches zero or more characters
114 pi++;
115 // Skip * and try to match rest
116 while (si <= segment.length) {
117 if (segmentMatch(segment.slice(si), pattern.slice(pi))) {
118 return true;
119 }
120 si++;
121 }
122 return false;
123 } else if (pc === '?') {
124 // ? matches exactly one character
125 si++;
126 pi++;
127 } else if (segment[si] === pc) {
128 si++;
129 pi++;
130 } else {
131 return false;
132 }
133 }
134
135 // Skip remaining * in pattern
136 while (pi < pattern.length && pattern[pi] === '*') {
137 pi++;
138 }
139
140 return si === segment.length && pi === pattern.length;
141}
142
143/**
144 * Blank out quoted strings for shell-faithful matching.
145 * Prevents patterns from matching content inside quotes.
146 */
147export function blankQuotedContent(cmd: string): string {
148 // Single-quoted strings: no escaping inside
149 let result = cmd.replace(/'[^']*'/g, "''");
150 // Double-quoted strings: handle escaped quotes
151 result = result.replace(/"(?:[^"\\]|\\.)*"/g, '""');
152 return result;
153}
154
155/**
156 * Blank out quoted heredoc bodies.
157 * Quoted heredoc delimiters (<<'EOF') disable expansion in the body.
158 */
159export function blankQuotedHeredocBodies(cmd: string): string {
160 // <<'DELIM' or <<"DELIM" followed by body until DELIM on its own line
161 return cmd.replace(
162 /(<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]{0,63})\2)([\s\S]{0,20000}?)(^[ \t]*\3[ \t]*$)/gm,
163 (_m, open: string, _q: string, _delim: string, _body: string, close: string) =>
164 `${open}\n${close}`,
165 );
166}
167
168/**
169 * Check if a repo is allowed by the pattern's repos filter.
170 */
171function repoAllowed(pattern: LessonPattern, currentRepo?: string): boolean {
172 if (!pattern.repos || pattern.repos.length === 0) {
173 return true; // No repo filter, matches all
174 }
175 if (!currentRepo) {
176 return false; // Pattern has repos filter but we don't know current repo
177 }
178 return pattern.repos.some(r => {
179 // Support owner/repo format
180 if (r.includes('/')) {
181 return currentRepo === r || simpleGlobMatch(currentRepo, r);
182 }
183 // Just repo name
184 return currentRepo.endsWith('/' + r) || currentRepo === r;
185 });
186}
187
188/**
189 * Check if a path is excluded by the pattern's exclude_paths.
190 */
191function pathExcluded(pattern: LessonPattern, filePath: string): boolean {
192 if (!pattern.exclude_paths || pattern.exclude_paths.length === 0) {
193 return false;
194 }
195 const normalized = filePath.replace(/\\/g, '/');
196 // The corpus writes plain substrings ("/tests/", ".md", "/configs/"); an
197 // entry with glob characters keeps the glob reading.
198 return pattern.exclude_paths.some(ex =>
199 /[*?[]/.test(ex) ? simpleGlobMatch(filePath, ex) : normalized.includes(ex.replace(/\\/g, '/')),
200 );
201}
202
203/**
204 * Match a Bash command against patterns.
205 *
206 * Steps:
207 * 1. Blank quoted content and heredoc bodies for shell-faithful matching
208 * 2. Require an explicit Bash tool name
209 * 3. Check trigger_pattern or pattern
210 * 4. If block_pattern is set, must also match that (for guard patterns)
211 */
212export function matchBashCommand(
213 command: string,
214 patterns: LessonPattern[],
215 currentRepo?: string
216): MatchedLesson[] {
217 const matches: MatchedLesson[] = [];
218
219 // Blank quoted heredoc bodies first (before quoted strings break delimiter detection)
220 // then blank quoted strings for shell-faithful matching
221 const blankedCommand = blankQuotedContent(blankQuotedHeredocBodies(command));
222 const targetText = blankedCommand.toLowerCase();
223
224 for (const pat of patterns) {
225 // Check tool_names filter
226 if (!pat.tool_names?.includes('Bash')) {
227 continue;
228 }
229
230 // Check repo filter
231 if (!repoAllowed(pat, currentRepo)) {
232 continue;
233 }
234
235 // Check trigger_pattern or pattern
236 const triggerRegex = pat.trigger_pattern || pat.pattern;
237 if (!triggerRegex) {
238 continue;
239 }
240
241 // Create regex from pattern string
242 let regex: RegExp;
243 try {
244 regex = new RegExp(triggerRegex, 'i');
245 } catch {
246 // Invalid regex, skip
247 continue;
248 }
249
250 if (!regex.test(targetText)) {
251 continue;
252 }
253
254 // If block_pattern is set, this is a guard pattern that needs both conditions
255 if (pat.block_pattern) {
256 let blockRegex: RegExp;
257 try {
258 blockRegex = new RegExp(pat.block_pattern, 'i');
259 } catch {
260 continue;
261 }
262 if (!blockRegex.test(targetText)) {
263 continue;
264 }
265 }
266
267 matches.push({
268 id: pat.id,
269 severity: pat.severity,
270 message: pat.message,
271 fix: pat.example_fix,
272 allowedForm: pat.allowed_form,
273 source: 'pattern',
274 });
275 }
276
277 return matches;
278}
279
280/**
281 * The content test of a corpus file entry, read the way the hq-ext guard
282 * (pretool-lesson-guard evalSimple / evalWindowCheck) reads it:
283 * - simple (pattern): the regex with flag m against the whole content.
284 * - window-check (trigger_pattern): each line is tested alone, and a trigger
285 * line fires only when require_pattern is absent from the window_lines
286 * lines on both sides of it. No require_pattern means the trigger decides.
287 * An invalid regex never fires.
288 */
289function contentFires(pat: LessonPattern, content: string): boolean {
290 try {
291 if (pat.trigger_pattern) {
292 const trigger = new RegExp(pat.trigger_pattern);
293 const required = pat.require_pattern ? new RegExp(pat.require_pattern) : null;
294 const span = pat.window_lines ?? 0;
295 const lines = content.split('\n');
296 for (let i = 0; i < lines.length; i++) {
297 if (!trigger.test(lines[i])) continue;
298 if (!required) return true;
299 const window = lines.slice(Math.max(0, i - span), Math.min(lines.length, i + span + 1)).join('\n');
300 if (!required.test(window)) return true;
301 }
302 return false;
303 }
304 return new RegExp(pat.pattern as string, 'm').test(content);
305 } catch {
306 return false;
307 }
308}
309
310/**
311 * The two typed corpus kinds that carry their own rule, read the way the
312 * hq-ext guard reads them (evalBlockCheck, evalDockerfileCheck). The path
313 * must END with file_match; the content then decides.
314 * - block-check: block_pattern captures a region (group 1, else the whole
315 * match) and check_patterns are tested against that region only.
316 * - dockerfile-check: each `uv pip install ... -e /app/packages/<pkg>` needs
317 * a `COPY --from=builder /app/packages/<pkg>/src` in the same file.
318 * An invalid regex never fires.
319 */
320function typedCheckFires(pat: LessonPattern, filePath: string, content: string): boolean {
321 if (!pat.file_match || !filePath.endsWith(pat.file_match)) return false;
322 try {
323 if (pat.type === 'block-check') {
324 if (!pat.block_pattern) return false;
325 const block = content.match(new RegExp(pat.block_pattern));
326 if (!block) return false;
327 const body = block[1] || block[0];
328 return (pat.check_patterns ?? []).some(check => new RegExp(check).test(body));
329 }
330 const editable = /uv pip install[^\n]*-e\s+\/app\/packages\/([\w-]+)\/?/g;
331 for (const found of content.matchAll(editable)) {
332 if (!new RegExp(`COPY\\s+--from=builder\\s+/app/packages/${found[1]}/src`).test(content)) return true;
333 }
334 return false;
335 } catch {
336 return false;
337 }
338}
339
340/**
341 * Match Edit/Write args against patterns.
342 *
343 * Checks file_path against file_glob and new content against check_patterns.
344 */
345export function matchFileEdit(
346 filePath: string,
347 content: string,
348 patterns: LessonPattern[],
349 toolName: 'Edit' | 'Write',
350 currentRepo?: string
351): MatchedLesson[] {
352 const matches: MatchedLesson[] = [];
353
354 for (const pat of patterns) {
355 // Check tool_names filter
356 if (pat.tool_names && !pat.tool_names.includes(toolName)) {
357 continue;
358 }
359
360 // Check repo filter
361 if (!repoAllowed(pat, currentRepo)) {
362 continue;
363 }
364
365 // block-check and dockerfile-check carry their own rule; the generic
366 // glob, exclude and check_patterns steps below do not apply to them.
367 if (pat.type === 'block-check' || pat.type === 'dockerfile-check') {
368 if (typedCheckFires(pat, filePath, content)) {
369 matches.push({ id: pat.id, severity: pat.severity, message: pat.message, fix: pat.example_fix, allowedForm: pat.allowed_form, source: 'pattern' });
370 }
371 continue;
372 }
373
374 // Check file_glob filter
375 if (pat.file_glob) {
376 if (!simpleGlobMatch(filePath, pat.file_glob)) {
377 continue;
378 }
379 }
380
381 // Check exclude_paths
382 if (pathExcluded(pat, filePath)) {
383 continue;
384 }
385
386 // Check file_match pattern if present
387 if (pat.file_match) {
388 let fileMatchRegex: RegExp;
389 try {
390 fileMatchRegex = new RegExp(pat.file_match, 'i');
391 } catch {
392 continue;
393 }
394 if (!fileMatchRegex.test(filePath)) {
395 continue;
396 }
397 }
398
399 // Check check_patterns against content
400 if (pat.check_patterns && pat.check_patterns.length > 0) {
401 let matchedAny = false;
402 for (const checkPat of pat.check_patterns) {
403 let checkRegex: RegExp;
404 try {
405 checkRegex = new RegExp(checkPat, 'i');
406 } catch {
407 continue;
408 }
409 if (checkRegex.test(content)) {
410 matchedAny = true;
411 break;
412 }
413 }
414 if (!matchedAny) {
415 continue;
416 }
417 } else if (pat.pattern || pat.trigger_pattern) {
418 // A present content test decides, with or without a file filter, as in
419 // the guard. The glob alone would fire on every matching file. A Bash-only
420 // entry never gets here: its tool_names stops it at the top of the loop.
421 if (!contentFires(pat, content)) {
422 continue;
423 }
424 } else if (!pat.file_glob && !pat.file_match) {
425 // No file filter and no content test, skip
426 continue;
427 }
428
429 matches.push({
430 id: pat.id,
431 severity: pat.severity,
432 message: pat.message,
433 fix: pat.example_fix,
434 allowedForm: pat.allowed_form,
435 source: 'pattern',
436 });
437 }
438
439 // Block before warn (stable within a severity): callers act on matches[0],
440 // so corpus order must never let a warn hide a block (estate-6 HOLD on #4429).
441 return bySeverity(matches);
442}
443
444/** Severity rank: block first. */
445const SEVERITY_RANK: Record<MatchedLesson['severity'], number> = { block: 0, warn: 1 };
446
447/** Stable sort of matches, block before warn. */
448export function bySeverity(matches: MatchedLesson[]): MatchedLesson[] {
449 return matches
450 .map((m, i) => ({ m, i }))
451 .sort((a, b) => SEVERITY_RANK[a.m.severity] - SEVERITY_RANK[b.m.severity] || a.i - b.i)
452 .map(({ m }) => m);
453}
454
455/**
456 * Match a Bash command against lessons.md bullets.
457 *
458 * Bullets are indexed by their first few command tokens.
459 * Returns at most one bullet match (advisory, grey).
460 */
461export function matchLessonsBullet(
462 command: string,
463 bullets: LessonBullet[]
464): MatchedLesson | null {
465 const tokens = command.trim().split(/\s+/).slice(0, 3);
466 if (tokens.length === 0) {
467 return null;
468 }
469
470 // Find bullet whose tokens match our command tokens
471 for (const bullet of bullets) {
472 const bulletTokens = bullet.tokens;
473 if (bulletTokens.length === 0) {
474 continue;
475 }
476
477 // Check if command starts with bullet's indexed tokens
478 let matches = true;
479 for (let i = 0; i < bulletTokens.length && i < tokens.length; i++) {
480 if (tokens[i].toLowerCase() !== bulletTokens[i].toLowerCase()) {
481 matches = false;
482 break;
483 }
484 }
485
486 if (matches) {
487 return {
488 id: bullet.heading.replace(/\s+/g, '-').toLowerCase(),
489 severity: 'warn', // Advisory, grey
490 message: bullet.text,
491 source: 'bullet',
492 };
493 }
494 }
495
496 return null;
497}
498
499/**
500 * Combine pattern matches with bullet matches.
501 * Guard pattern match takes priority, capped at one card per call.
502 */
503export function matchAll(
504 command: string,
505 patterns: LessonPattern[],
506 bullets: LessonBullet[],
507 currentRepo?: string
508): MatchedLesson[] {
509 const patternMatches = matchBashCommand(command, patterns, currentRepo);
510
511 // Guard patterns (severity 'block') take priority
512 const blockMatches = patternMatches.filter(m => m.severity === 'block');
513 if (blockMatches.length > 0) {
514 return [blockMatches[0]]; // Cap at one
515 }
516
517 // Warn matches are additive
518 const warnMatches = patternMatches.filter(m => m.severity === 'warn');
519
520 // Bullet matches are advisory (grey)
521 const bulletMatch = matchLessonsBullet(command, bullets);
522
523 // Combine: warn first, then bullet if no warn
524 if (warnMatches.length > 0) {
525 return [warnMatches[0]];
526 }
527
528 if (bulletMatch) {
529 return [bulletMatch];
530 }
531
532 return [];
533}
534src/card.ts 89 lines1/**
2 * UI tree builder for lesson cards.
3 *
4 * Creates a Box containing the lesson card that renders under a ToolUse row.
5 * The element constructors come from $.ui.resolve(e) in the hooks module: on
6 * CC 2.1.282 a render hook may only return nodes built by those constructors.
7 * A plain { type: 'Box' } object is refused as "not an element" and draws
8 * nothing, which is why the card never showed before (measured 2026-09-25).
9 */
10
11import type { MatchedLesson } from './types.js';
12
13/** One element constructor, as handed out by $.ui.resolve(e). */
14export type ElementCtor = (props?: Record<string, unknown>) => unknown;
15
16/** The subset of the resolved element table the card uses. */
17export interface CardElements {
18 Box: ElementCtor;
19 Text: ElementCtor;
20}
21
22/** Border and title color per severity: block red, warn yellow, bullet gray. */
23export function cardColor(lesson: MatchedLesson): 'red' | 'yellow' | 'gray' {
24 if (lesson.source === 'bullet') return 'gray';
25 return lesson.severity === 'block' ? 'red' : 'yellow';
26}
27
28/**
29 * Build a lesson card from resolved elements.
30 *
31 * Structure:
32 * - Round border box in the severity color
33 * - Title row: "lesson: <id>" (bold, colored) and the severity word
34 * - Message row
35 * - Fix row (dim, if available)
36 */
37export function buildCard(lesson: MatchedLesson, requestId: string, el: CardElements): unknown {
38 const color = cardColor(lesson);
39 const label = lesson.source === 'bullet' ? 'note' : lesson.severity;
40
41 const rows: unknown[] = [
42 el.Box({
43 children: [
44 el.Text({ bold: true, color, children: `lesson: ${lesson.id}` }),
45 el.Text({ dimColor: true, children: ` ${label}` }),
46 ],
47 }),
48 el.Text({ children: lesson.message }),
49 ];
50
51 if (lesson.fix) {
52 rows.push(el.Text({ dimColor: true, children: `Fix: ${lesson.fix}` }));
53 }
54
55 return el.Box({
56 key: `lesson-${requestId}`,
57 flexDirection: 'column',
58 borderStyle: 'round',
59 borderColor: color,
60 paddingX: 1,
61 children: rows,
62 });
63}
64
65/**
66 * Format lesson context for model consumption.
67 *
68 * Returns the message and fix (if any), capped at a reasonable length.
69 * This is added to the tool.call return context array. Lessons are advisory:
70 * a block-severity pattern is marked so, and the call still runs.
71 */
72export const BLOCK_ADVISORY_PREFIX = 'BLOCK-SEVERITY LESSON (advisory, not enforced): ';
73
74export function formatContext(lesson: MatchedLesson, maxLength = 32000): string {
75 const prefix = lesson.severity === 'block' && lesson.source === 'pattern' ? BLOCK_ADVISORY_PREFIX : '';
76 let text = `${prefix}[lesson:${lesson.id}] ${lesson.message}`;
77 if (lesson.fix) {
78 text += ` Fix: ${lesson.fix}`;
79 }
80 // The ALLOWED-FORM line is the command the agent should run instead, so it is
81 // never cut by the cap: the body is trimmed to make room for it.
82 const allowed = lesson.allowedForm ? `\nALLOWED-FORM: ${lesson.allowedForm}` : '';
83 const room = Math.max(0, maxLength - allowed.length);
84 if (text.length > room) {
85 text = text.slice(0, Math.max(0, room - 3)) + '...';
86 }
87 return text + allowed;
88}
89src/types.ts 60 lines1/**
2 * Type definitions for lesson-cards.
3 *
4 * Minimal $ facade for testing with a fake implementation.
5 */
6
7export interface FsEntry {
8 name: string;
9 isDirectory: boolean;
10 isFile: boolean;
11}
12
13export interface FileStat {
14 size: number;
15 mtime?: number;
16 isFile: boolean;
17 isDirectory: boolean;
18}
19
20export interface $ {
21 fs: {
22 read: (path: string, encoding?: string) => Promise<string | Uint8Array>;
23 list: (path: string) => Promise<FsEntry[] | null>;
24 stat: (path: string) => Promise<FileStat | null>;
25 };
26 ui: {
27 notice: (toolUseId: string, message: string) => Promise<void>;
28 invalidate: (component: string) => Promise<void>;
29 };
30}
31
32export interface ToolCallEvent {
33 tool: string;
34 args: Record<string, unknown>;
35 tool_use_id?: string;
36}
37
38export interface UiRenderEvent {
39 component: string;
40 requestId?: string;
41}
42
43export interface SessionStartEvent {
44 // Empty payload for session.start
45}
46
47export interface CommandRegisterEvent {
48 command: string;
49}
50
51export interface MatchedLesson {
52 id: string;
53 severity: 'block' | 'warn';
54 message: string;
55 fix?: string;
56 /** The pattern's allowed_form: the one command the lesson hands the agent. */
57 allowedForm?: string;
58 source: 'pattern' | 'bullet';
59}
60