@litfamily/litclaude 1.0.57 → 1.0.59

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.
@@ -0,0 +1,729 @@
1
+ // The pure prompt router of the UserPromptSubmit hook (bin/litclaude-hook.js imports it): the trigger
2
+ // table, the inert-text helpers that set fenced, backtick-quoted and host-authored text aside, and the
3
+ // cascade that picks one route. Nothing here reads files, the environment or the clock.
4
+ // explainRoute() at the end says which rule picked the route, for `litclaude-ai why`.
5
+
6
+ import { renameAliases } from "./rename-aliases.mjs";
7
+ import { hasInterfaceModeWord } from "./interface-mode.mjs";
8
+
9
+ const plainWordBoundary = /^[A-Za-z0-9]$/u;
10
+ const compoundWordBoundary = /^[A-Za-z0-9_-]$/u;
11
+
12
+ const triggerByToken = {
13
+ "deep-interview": { command: "/litclaude:deep-interview", skill: "Skill(deep-interview)", skillId: "deep-interview", discipline: "deep-interview" },
14
+ "native-workflow": { command: "/litclaude:lit-loop", skill: "Skill(lit-loop)", skillId: "lit-loop", discipline: "native-workflow" },
15
+ // Team phrases and the named skill share the same native setup gate.
16
+ "agent-team": { command: "/litclaude:lit-loop", skill: "Skill(lit-team)", skillId: "lit-team", discipline: "agent-team" },
17
+ "lit-team": { command: "/litclaude:lit-loop", skill: "Skill(lit-team)", skillId: "lit-team", discipline: "agent-team" },
18
+ // Named-only, like refactor and debugging: a user reaches for structural search when a text
19
+ // search already failed them, so they name it. No NL route — "search" and "find" are far too
20
+ // common to gate on, and a wrong activation here sends the model after a parser it may not have.
21
+ "structural-search": { command: "structural-search", skill: "Skill(structural-search)", skillId: "structural-search", discipline: "structural-search" },
22
+ "browser-drive": { command: "browser-drive", skill: "Skill(browser-drive)", skillId: "browser-drive", discipline: "browser-drive" },
23
+ "lit-crucible": { command: "/litclaude:lit-plan", skill: "Skill(lit-crucible)", skillId: "lit-crucible", discipline: "lit-plan" },
24
+ // Open ideation. The natural routes (`lit brainstorm …`, `lit ideation …`, `lit idea …`) are in
25
+ // hasExplicitBrainstormRoute; the bare skill name is the leading-token form. It carries no goal line.
26
+ "lit-brainstorm": { command: "/litclaude:lit-brainstorm", skill: "Skill(lit-brainstorm)", skillId: "lit-brainstorm", discipline: "lit-brainstorm" },
27
+ // Ideation at scale: `ultra-brainstorm <topic>` (leading token), `lit ultra-brainstorm <topic>` (hasExplicitUltraBrainstormRoute)
28
+ // and /litclaude:ultra-brainstorm. Read-only apart from its .litclaude/brainstorm/ notes; it carries no goal line.
29
+ "ultra-brainstorm": { command: "/litclaude:ultra-brainstorm", skill: "Skill(ultra-brainstorm)", skillId: "ultra-brainstorm", discipline: "ultra-brainstorm" },
30
+ // Porting someone else's published technique into the user's own skill or system. The natural
31
+ // routes (`lit hijack …`, `lit 하이재킹 …`) are in hasExplicitHijackRoute; the skill name leads.
32
+ "lit-hijack": { command: "/litclaude:lit-hijack", skill: "Skill(lit-hijack)", skillId: "lit-hijack", discipline: "lit-hijack" },
33
+ "lit-init": { command: "/litclaude:lit-init", skill: "Skill(lit-init)", skillId: "lit-init", discipline: "lit-init" },
34
+ "lit-plan": { command: "/litclaude:lit-plan", skill: "Skill(lit-plan)", skillId: "lit-plan", discipline: "lit-plan" },
35
+ // lit-recap moved into lit-adhd: `lit recap`, `litrecap` and /litclaude:lit-recap open lit-adhd's recap view.
36
+ "lit-recap": { command: "/litclaude:lit-adhd", skill: "Skill(lit-adhd)", skillId: "lit-adhd", discipline: "lit-adhd", view: "recap", movedFrom: "lit-recap" },
37
+ // The trigger surface is deliberately wider than the skill id. `lit-comprehend` is the
38
+ // canonical name, but bare `comprehend` stays a route for the same reason bare `recap`
39
+ // does — it is what a user actually types. Breadth is safe here only because activation
40
+ // no longer implies execution: with no explicit scope the skill states what it would
41
+ // explain and waits, so a loose match costs one line, not a multi-minute artifact build.
42
+ // The natural-language forms ("설명해줘", "explain this", "이해가 안 돼") stay out of the
43
+ // hook regardless — those are left to Claude Code's own Skill-description matching.
44
+ "lit-comprehend": { command: "/litclaude:lit-comprehend", skill: "Skill(lit-comprehend)", skillId: "lit-comprehend", discipline: "lit-comprehend" },
45
+ comprehend: { command: "/litclaude:lit-comprehend", skill: "Skill(lit-comprehend)", skillId: "lit-comprehend", discipline: "lit-comprehend" },
46
+ // The cross-session brief. `lit-rewind` is a permanent alias with the same skill and discipline,
47
+ // so the card's rewind look and the read-only stack rule key on one name.
48
+ "lit-adhd": { command: "/litclaude:lit-adhd", skill: "Skill(lit-adhd)", skillId: "lit-adhd", discipline: "lit-adhd" },
49
+ "lit-rewind": { command: "/litclaude:lit-rewind", skill: "Skill(lit-adhd)", skillId: "lit-adhd", discipline: "lit-adhd" },
50
+ "lit-loop": { command: "/litclaude:lit-loop", skill: "Skill(lit-loop)", skillId: "lit-loop", discipline: "lit-loop" },
51
+ "start-work": { command: "/litclaude:start-work", skill: "Skill(start-work)", skillId: "start-work", discipline: "start-work" },
52
+ "review-work": { command: "/litclaude:review-work", skill: "Skill(review-work)", skillId: "review-work", discipline: "review-work" },
53
+ litgoal: { command: "/litclaude:litgoal", skill: "Skill(litgoal)", skillId: "litgoal", discipline: "litgoal" },
54
+ litresearch: { command: "/litclaude:litresearch", skill: "Skill(litresearch)", skillId: "litresearch", discipline: "litresearch" },
55
+ // `litwork` is a documented trigger (README, docs/hooks.md) that previously had no route of its own: it fell
56
+ // through the natural-language cascade to lit-loop and picked up a soft-confirm meant for a stray English
57
+ // "lit". `command` stays on lit-loop because there is no commands/litwork.md — the exact `commands/`
58
+ // listing is asserted by test/plugin-manifest.test.mjs — but the skill body is now litwork's own.
59
+ litwork: { command: "/litclaude:lit-loop", skill: "Skill(litwork)", skillId: "litwork", discipline: "litwork" },
60
+ // Intent-shaped skills. A user names these directly, so a bare token is the whole route; they carry no
61
+ // slash command, and `command` is the bare word the user typed.
62
+ debugging: { command: "debugging", skill: "Skill(debugging)", skillId: "debugging", discipline: "debugging" },
63
+ refactor: { command: "refactor", skill: "Skill(refactor)", skillId: "refactor", discipline: "refactor" },
64
+ "lit-burnoff": { command: "lit-burnoff", skill: "Skill(lit-burnoff)", skillId: "lit-burnoff", discipline: "lit-burnoff" },
65
+ "lit-burnoff-file": { command: "lit-burnoff-file", skill: "Skill(lit-burnoff-file)", skillId: "lit-burnoff-file", discipline: "lit-burnoff" },
66
+ // Previously reachable ONLY through a post-edit event, which for a design skill is
67
+ // backwards: the guidance is needed when someone says they are designing a UI, not after
68
+ // the CSS is written. Opening the chat routes is additive — the PostToolUse/PreToolUse
69
+ // event routes stay exactly as they were.
70
+ "frontend-ui-ux": { command: "frontend-ui-ux", skill: "Skill(frontend-ui-ux)", skillId: "frontend-ui-ux", discipline: "frontend-ui-ux" },
71
+ "readme-studio": { command: "readme-studio", skill: "Skill(readme-studio)", skillId: "readme-studio", discipline: "readme-studio" },
72
+ // Leading token only. The words "diagram" or "chart" alone must not pull interface or
73
+ // measured-data work away from frontend-ui-ux and lit-scientific-visualization.
74
+ "lit-diagram-drawer": { command: "/litclaude:lit-diagram-drawer", skill: "Skill(lit-diagram-drawer)", skillId: "lit-diagram-drawer", discipline: "lit-diagram-drawer" },
75
+ // Physical schematics: P&IDs, PFDs, apparatus figures, isometric cutaways. A leading token names
76
+ // the skill; a bare `lit` plus schematic wording reaches it through hasSchematicIntent below.
77
+ "lit-schematic": { command: "/litclaude:lit-schematic", skill: "Skill(lit-schematic)", skillId: "lit-schematic", discipline: "lit-schematic" },
78
+ // Office deliverables. A leading token names the skill; a bare `lit` plus report or slide
79
+ // wording reaches them through hasOfficeIntent below.
80
+ "lit-pptx": { command: "/litclaude:lit-pptx", skill: "Skill(lit-pptx)", skillId: "lit-pptx", discipline: "lit-pptx" },
81
+ "lit-docx": { command: "/litclaude:lit-docx", skill: "Skill(lit-docx)", skillId: "lit-docx", discipline: "lit-docx" },
82
+ // Film requests. A leading token names the skill; a bare `lit` plus a creation verb and
83
+ // motion-video wording reaches it through hasMotionVideoIntent, ahead of office and UI.
84
+ "lit-typographic-motion": { command: "/litclaude:lit-typographic-motion", skill: "Skill(lit-typographic-motion)", skillId: "lit-typographic-motion", discipline: "lit-typographic-motion" },
85
+ "visual-qa": { command: "visual-qa", skill: "Skill(visual-qa)", skillId: "visual-qa", discipline: "visual-qa" },
86
+ "lit-commit": { command: "lit-commit", skill: "Skill(lit-commit)", skillId: "lit-commit", discipline: "lit-commit" },
87
+ "lsp-setup": { command: "lsp-setup", skill: "Skill(lsp-setup)", skillId: "lsp-setup", discipline: "lsp-setup" },
88
+ autoresearch: { command: "/litclaude:autoresearch", skill: "Skill(autoresearch)", skillId: "autoresearch", discipline: "autoresearch" },
89
+ autoconference: { command: "/litclaude:autoconference", skill: "Skill(autoconference)", skillId: "autoconference", discipline: "autoconference" },
90
+ wikify: { command: "/litclaude:wikify", skill: "Skill(wikify)", skillId: "wikify", discipline: "wikify" },
91
+ };
92
+
93
+ // Canonical agent prompts keep their native tool and permission contracts.
94
+ Object.assign(triggerByToken, {
95
+ "lit-code": { command: "lit-code", skill: "Skill(lit-code)", skillId: "lit-code", discipline: "lit-code" },
96
+ "lit-humanizer": { command: "/litclaude:lit-humanizer", skill: "Skill(lit-humanizer)", skillId: "lit-humanizer", discipline: "lit-humanizer" },
97
+ "lit-planner": { ...triggerByToken["lit-plan"], agentId: "lit-planner" },
98
+ "lit-executor": { ...triggerByToken["start-work"], agentId: "lit-executor", safetyBlock: true },
99
+ "lit-verifier": { ...triggerByToken["review-work"], agentId: "lit-verifier" },
100
+ });
101
+ for (const [oldId, newId] of Object.entries(renameAliases)) {
102
+ triggerByToken[oldId] = { ...triggerByToken[newId], renameFrom: oldId };
103
+ }
104
+
105
+ const withoutClosedCodeFences = (text) => {
106
+ const lines = text.split(/\r\n|[\n\r]/u);
107
+ for (let index = 0; index < lines.length; index += 1) {
108
+ const opening = /^ {0,3}(`{3,}|~{3,})[^\r\n]*$/u.exec(lines[index]);
109
+ if (!opening) continue;
110
+ const marker = opening[1][0];
111
+ const minimumLength = opening[1].length;
112
+ let closingIndex = index + 1;
113
+ while (closingIndex < lines.length) {
114
+ const closing = /^ {0,3}(`{3,}|~{3,})[ \t]*$/u.exec(lines[closingIndex]);
115
+ if (closing && closing[1][0] === marker && closing[1].length >= minimumLength) break;
116
+ closingIndex += 1;
117
+ }
118
+ if (closingIndex === lines.length) continue;
119
+ lines.fill("", index, closingIndex + 1);
120
+ index = closingIndex;
121
+ }
122
+ return lines.join("\n");
123
+ };
124
+
125
+ const withoutCode = (text) => withoutClosedCodeFences(text).replace(/`[^`]*`/gu, " ");
126
+
127
+ // Claude Code (and herdr, which relays pane events the same way) can deliver a
128
+ // UserPromptSubmit turn whose `prompt` is host-generated background content rather
129
+ // than something the user typed — observed 3x on 2026-09-17 as a `<task-notification>`
130
+ // block reporting a finished background agent, which happened to contain UI-shaped
131
+ // prose ("dashboard", "configure", ...) and fired the frontend-ui-ux route. A
132
+ // `<system-reminder>` block is the same class of host-authored wrapper and is stripped
133
+ // for the same reason, even though only `<task-notification>` has been directly
134
+ // observed here. Only WELL-FORMED, fully-closed blocks are stripped — same rule as
135
+ // `withoutClosedCodeFences` for fences — so a bare, unclosed opening tag (accidental or
136
+ // not) stays visible and eligible rather than silently swallowing real user text.
137
+ // Genuine user prose outside (or between) these blocks is untouched and still routes
138
+ // normally; a prompt that consists ONLY of host-generated blocks reduces to nothing and
139
+ // therefore activates no route, which is the intended fix.
140
+ // A `<cross-session-message>` block (another session's message relayed into this one, observed
141
+ // 2026-10-27 firing the lit-adhd route on test names it mentioned) is someone else's text too;
142
+ // its opening tag may carry attributes.
143
+ // A prompt that OPENS with an unclosed `<task-notification>` (a hand-back cut off by the host) or
144
+ // with the host's `[SYSTEM NOTIFICATION - NOT USER INPUT]` banner is host text from its first
145
+ // character, so the whole prompt is inert (observed 2026-11-15 firing lit-adhd and frontend-ui-ux).
146
+ // A tag mentioned later in a typed prompt is still left alone.
147
+ const HOST_NOTIFICATION_OPENING = /^\s*(?:\[SYSTEM NOTIFICATION - NOT USER INPUT\]|<task-notification>(?![\s\S]*<\/task-notification>))/u;
148
+ const withoutHostNotifications = (text) => HOST_NOTIFICATION_OPENING.test(text) ? " " : text
149
+ .replace(/<task-notification>[\s\S]*?<\/task-notification>/gu, " ")
150
+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gu, " ")
151
+ .replace(/<cross-session-message(?:\s[^>]*)?>[\s\S]*?<\/cross-session-message>/gu, " ");
152
+ const rawTriggerText = (text) => withoutCode(withoutHostNotifications(text)).toLowerCase();
153
+ const normalizedTriggerText = (text) => rawTriggerText(text).replace(/[_-]+/gu, " ");
154
+
155
+ const isPlainWordBoundary = (value) => value === undefined || !plainWordBoundary.test(value);
156
+ const isCompoundWordBoundary = (value) => value === undefined || !compoundWordBoundary.test(value);
157
+
158
+ const containsPlainWord = (text, word) => {
159
+ for (let index = 0; index < text.length; index += 1) {
160
+ if (!text.startsWith(word, index)) continue;
161
+ const previous = index === 0 ? undefined : text[index - 1];
162
+ const next = text[index + word.length];
163
+ if (isPlainWordBoundary(previous) && isPlainWordBoundary(next)) return true;
164
+ }
165
+ return false;
166
+ };
167
+
168
+ const containsCompoundBoundedWord = (text, word) => {
169
+ for (let index = 0; index < text.length; index += 1) {
170
+ if (!text.startsWith(word, index)) continue;
171
+ const previous = index === 0 ? undefined : text[index - 1];
172
+ const next = text[index + word.length];
173
+ if (isCompoundWordBoundary(previous) && isCompoundWordBoundary(next)) return true;
174
+ }
175
+ return false;
176
+ };
177
+
178
+ const slashCommandMentions = [
179
+ "/autoconference",
180
+ "/autoresearch",
181
+ "/comprehend",
182
+ "/lit-comprehend",
183
+ "/litclaude:lit-comprehend",
184
+ "/deep-interview",
185
+ "/goal",
186
+ "/lit-crucible",
187
+ "/lit-init",
188
+ "/lit-loop",
189
+ "/lit-plan",
190
+ "/lit-recap",
191
+ "/litclaude:deep-interview",
192
+ "/litclaude:autoconference",
193
+ "/litclaude:autoresearch",
194
+ "/litclaude:lit-init",
195
+ "/litclaude:lit-handoff",
196
+ "/litclaude:lit-loop",
197
+ "/litclaude:lit-plan",
198
+ "/litclaude:lit-recap",
199
+ "/litclaude:litgoal",
200
+ "/litclaude:litresearch",
201
+ "/litclaude:review-work",
202
+ "/litclaude:start-work",
203
+ "/litclaude:wikify",
204
+ "/litgoal",
205
+ "/litrecap",
206
+ "/litresearch",
207
+ "/review-work",
208
+ "/start-work",
209
+ "/wikify",
210
+ ];
211
+
212
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
213
+
214
+ slashCommandMentions.push(...Object.keys(triggerByToken).flatMap((id) => [`/${id}`, `/litclaude:${id}`]));
215
+
216
+ const namedTriggerTokens = Object.keys(triggerByToken)
217
+ .filter((id) => !["agent-team", "native-workflow"].includes(id))
218
+ .sort((a, b) => b.length - a.length)
219
+ .map(escapeRegExp).join("|");
220
+ const dollarCommandPattern = new RegExp(`(?:^|\\s)\\$(${namedTriggerTokens})(?=$|[^\\w-])`, "u");
221
+ const leadingBareCommandPattern = new RegExp(`^\\s*(${namedTriggerTokens})(?=$|[^\\w-])`, "u");
222
+
223
+ const slashCommandMentionPattern = new RegExp(
224
+ `(^|\\s)(?:${slashCommandMentions.map(escapeRegExp).join("|")})(?=$|[\\s.,;:!?)}\\]])`,
225
+ "u",
226
+ );
227
+ const slashLitPhrasePattern = /(^|\s)\/lit(?:work)?\s+(?:plan|recap|comprehend|adhd|rewind|review|research|search|query|goal|workflow|dynamic\s+workflow|ultracode|team|team\s+mode|teammates|start\s+work|ultra[\s-]?brainstorm(?:ing)?|brainstorm(?:ing)?|ideation|ideas?|hijack(?:ing)?)(?=$|[\s.,;:!?)}\]])/u;
228
+
229
+ const containsSlashCommandMention = (text) => slashCommandMentionPattern.test(text) || slashLitPhrasePattern.test(text);
230
+
231
+ const familyTriggerTokens = new Set(["autoconference", "autoresearch", "wikify"]);
232
+ const hasSafeFamilyArgumentBoundary = (raw, match) => {
233
+ if (!familyTriggerTokens.has(match[1])) return true;
234
+ const next = raw[match.index + match[0].length];
235
+ return next === undefined || /\s/u.test(next);
236
+ };
237
+
238
+ const findDollarCommandTrigger = (raw) => {
239
+ const match = dollarCommandPattern.exec(raw);
240
+ if (!match) return undefined;
241
+ if (!hasSafeFamilyArgumentBoundary(raw, match)) return undefined;
242
+ if (match[1] === "start-work" && !/^\s*\$start-work(?=$|[^\w-])/u.test(raw)) return undefined;
243
+ return { ...triggerByToken[match[1]], source: "dollar-command" };
244
+ };
245
+
246
+ const findLeadingBareCommandTrigger = (raw) => {
247
+ // LEADING-position only, deliberately — not anywhere-tokens. The repo's own negative
248
+ // controls treat "plain review-work discussion" as a non-activation, and an anywhere-token
249
+ // would make "plain lit-commit discussion" fire. Keep named routes leading-only unless
250
+ // the explicit trailing-token table below admits them.
251
+ const match = leadingBareCommandPattern.exec(raw);
252
+ if (!match) return undefined;
253
+ if (!hasSafeFamilyArgumentBoundary(raw, match)) return undefined;
254
+ return { ...triggerByToken[match[1]], source: "bare-command" };
255
+ };
256
+
257
+ // A bare `lit` carries no task. `lit continue` asks to carry on what exists. `lit new` and
258
+ // `lit restart` ask for a fresh start, so the session's earlier activation does not count.
259
+ const bareLitPattern = /^\s*lit(?:work)?[\s.!?]*$/u;
260
+ const resumeLitPattern = /^\s*lit(?:work)?\s+(?:continue|resume|계속)[\s.!?]*$/u;
261
+ const restartLitPattern = /(?:^|\s)lit(?:work)?\s+(?:new|restart)(?=$|[^\w-])/u;
262
+
263
+ const hasLitTrigger = (raw) => containsCompoundBoundedWord(raw, "lit") || containsCompoundBoundedWord(raw, "litwork");
264
+ const hasTrailingLitInvocation = (raw) => /(?:^|\s)lit(?:work)?\s*$/u.test(raw);
265
+
266
+ const hangulSyllable = /^[가-힣]$/u;
267
+
268
+ const containsKoreanRecap = (raw) => {
269
+ for (let index = 0; index < raw.length; index += 1) {
270
+ if (!raw.startsWith("리캡", index)) continue;
271
+ const previous = index === 0 ? undefined : raw[index - 1];
272
+ const next = raw[index + 2];
273
+ if (previous !== undefined && hangulSyllable.test(previous)) continue;
274
+ if (next === "처" || next === "쳐") continue;
275
+ return true;
276
+ }
277
+ return false;
278
+ };
279
+
280
+ const findRecapTrigger = (raw) => {
281
+ if (containsCompoundBoundedWord(raw, "litrecap")) return { ...triggerByToken["lit-recap"], source: "bare-command" };
282
+ if (containsPlainWord(raw, "recap")) return { ...triggerByToken["lit-recap"], source: "natural-language" };
283
+ if (containsKoreanRecap(raw)) return { ...triggerByToken["lit-recap"], source: "natural-language" };
284
+ return undefined;
285
+ };
286
+
287
+ // `lit comprehend` used to fall through to the generic lit cascade and land on lit-loop —
288
+ // the bare `lit` token caught it, so the route looked alive while injecting the wrong body.
289
+ // This is the same shape of defect the litwork and lit-team comments above describe.
290
+ const findComprehendPhraseTrigger = (raw) =>
291
+ (/(?:^|\s)lit(?:work)?[\s-]comprehend(?=$|[^\w-])/u.test(raw)
292
+ ? { ...triggerByToken["lit-comprehend"], source: "bare-command" }
293
+ : undefined);
294
+
295
+ // `lit adhd` / `lit rewind` name the brief as two tokens, like `lit comprehend`; without this the
296
+ // bare `lit` would catch them and start a loop. The word must end at a boundary, so `lit adhder`
297
+ // and `lit rewinding` keep their ordinary routes.
298
+ const findAdhdPhraseTrigger = (raw) => {
299
+ if (!/(?:^|\s)lit(?:work)?[\s-](?:adhd|rewind)(?=$|[^\w-])/u.test(raw)) return undefined;
300
+ // `lit adhd recap [session]` is the per-session recap view (it replaced lit-recap).
301
+ const recap = /(?:^|\s)lit(?:work)?[\s-](?:adhd|rewind)\s+(?:recap|리캡)(?:\s+([A-Za-z0-9][A-Za-z0-9._:-]{3,63}))?(?=$|\s)/u.exec(raw);
302
+ const detail = !recap && /(?:자세히|상세|\bdetails?\b|\bper[\s-]session\b)/iu.test(raw);
303
+ return { ...triggerByToken["lit-adhd"], source: "bare-command", ...(recap ? { view: "recap", recapSession: recap[1] ?? null } : detail ? { view: "detail" } : {}) };
304
+ };
305
+
306
+ const hasExplicitWorkflowRoute = (normalized) => /\blit(?:work)?\s+(?:dynamic\s+workflow|workflow|ultracode)\b/u.test(normalized);
307
+ // Open ideation. A route word must sit directly after `lit` (`lit brainstorm a name`), or the stronger
308
+ // verbs may lead a prompt that carries `lit` anywhere (`brainstorm a name for my app lit`). `idea` and
309
+ // `ideas` are common nouns, so they count only directly after `lit`: "lit review the brainstorm notes" and
310
+ // "lit fix the idea generator" keep their own routes.
311
+ const hasExplicitBrainstormRoute = (normalized) => /\blit(?:work)?\s+(?:brainstorm(?:ing)?|ideation|ideate|ideas?|브레인스토밍|아이디어)(?=$|[^\w-])/u.test(normalized)
312
+ || /^\s*(?:brainstorm(?:ing)?|ideation|ideate)(?=$|[^\w-])/u.test(normalized);
313
+ // Porting a published technique. The route word must sit directly after `lit`: "lit debug the session
314
+ // hijack" and "lit review the hijack ledger" keep their own routes, and the bare word never activates.
315
+ // `lit ultra-brainstorm <topic>` (the hyphen reads as a space here); ahead of the plain brainstorm route.
316
+ const hasExplicitUltraBrainstormRoute = (normalized) => /\blit(?:work)?\s+ultra\s?brainstorm(?:ing)?(?=$|[^\w-])/u.test(normalized);
317
+ const hasExplicitHijackRoute = (normalized) => /\blit(?:work)?\s+(?:hijack(?:ing)?|하이재킹|하이잭)(?=$|[^\w-])/u.test(normalized);
318
+ const hasExplicitTeamRoute = (normalized) => /\blit(?:work)?\s+(?:team(?:\s+mode)?|teammates)\b/u.test(normalized);
319
+ // A casual one-line request ends with `lit` ("… 조사해줘 lit"), so the research verb is not next to
320
+ // the token. Korean stems are bare substrings for the reason given at the UI route below; 조사를 and
321
+ // a bare 조사 are left out because 조사 is also the grammatical particle ("조사 분리 함수").
322
+ const hasExplicitResearchRoute = (normalized) => /\blit(?:work)?\s+(?:research|search|query)\b/u.test(normalized)
323
+ || /^\s*research\b/u.test(normalized)
324
+ || /조사해|조사하|조사\s?좀|리서치/u.test(normalized);
325
+
326
+ // The ONE new natural-language surface. `design` alone is far too common ("database design",
327
+ // "by design", "design the API"), so this requires BOTH a design-shaped verb AND an interface
328
+ // noun. That conjunction is what keeps it off non-UI work; a single-word trigger here would be
329
+ // the highest false-positive route in the hook.
330
+ // Inflections matter: "add dark mode styling to the settings view" is a design request, and a
331
+ // bare-stem list silently misses it.
332
+ //
333
+ // BOUNDARY RULES, which differ by script and were measured before being relied on:
334
+ // Latin terms keep \b. With the /u flag Hangul is a NON-word character, so \bui\b correctly
335
+ // matches "UI를" (space | 를 are both boundaries) while still rejecting "build" and
336
+ // "guide", where 'ui' sits between word characters.
337
+ // Hangul terms use a BARE SUBSTRING. \b is inert between two non-word characters, so
338
+ // /\b페이지\b/ does not match "페이지를" at all. Korean is agglutinative — particles
339
+ // (를/을/의/에서) and verb endings attach with no delimiter — so matching the STEM and
340
+ // letting the ending follow is the only correct approach: 디자인 covers 디자인해줘,
341
+ // 디자인하고, 디자인할, 디자인했다 and 리디자인 in one term.
342
+ // ACCEPTED RISK: a bare substring fires if a listed Hangul term appears inside an unrelated
343
+ // word. Mitigated by preferring terms of two or more syllables and by dropping ambiguous
344
+ // ones. REJECTED BY NAME, each for a measured collision with a sentence that already
345
+ // clears the verb half:
346
+ // 카드 — "신용카드 결제를 만들어줘" is a payment feature, not a UI request.
347
+ // 메뉴 — a restaurant/domain menu is as common as a UI menu.
348
+ // 폼 — one syllable; too easy to hit inside an unrelated word.
349
+ // 헤더 — the worst of them. "HTTP 헤더를 만들어줘", "요청 헤더를 구성해줘" and
350
+ // "응답 헤더를 배치해줘" all match a verb already in the list (만들 / 구성 /
351
+ // 배치), so adding 헤더 would fire on all three. 푸터 is kept because it has no
352
+ // equivalent high-frequency protocol meaning — there is no HTTP footer.
353
+ const uiDesignVerb = /\b(?:re)?(?:design(?:ing|ed)?|styl(?:e|ing|ed)|skin(?:ning)?|theme|theming)\b|\b(?:mock\s?-?up|lay\s?out|polish(?:ing)?|revamp)\b|디자인|만들|만드|개편|꾸미|꾸며|다듬|배치|구성/u;
354
+ const uiSurfaceNoun = /\b(?:ui|ux|interface|screen|page|view|component|layout|button|form|modal|dialog|dashboard|css|styling|stylesheet|typography|spacing|palette|dark\s?mode|responsive)\b|화면|페이지|인터페이스|레이아웃|버튼|모달|팝업|대시보드|컴포넌트|스타일|테마|다크\s?모드|반응형|아이콘|타이포그래피|여백|색상|컬러|폰트|디자인\s?시스템|사이드바|푸터|툴바|위젯|[내네]비게이션/u;
355
+
356
+ // The conjunction is the whole safety mechanism, and it carries MORE weight in Korean than in
357
+ // English. English can rely on `design` being specific, so `build` and `make` were deliberately
358
+ // left out of the verb list. Korean has no such option: 만들다 is the natural verb for creating
359
+ // a UI, so it must be present, which means every Korean sentence containing 만들어줘 reaches the
360
+ // verb half. The noun half is therefore the only thing separating "디자인 시스템을 만들어줘"
361
+ // from "API 클라이언트를 만들어줘". The Korean negative tests exist to prove it still does.
362
+ // English build verbs route only with a page-shaped noun. `build`, `create` and `make` are far too
363
+ // common to join uiDesignVerb, but "build the landing page" is the most common way an interface is
364
+ // requested, and leaving it unrouted meant the skill activated only when the model happened to
365
+ // load it. The noun list names whole interface surfaces, never a part a backend also has; the
366
+ // exclusion list catches the build objects that share those nouns (BI dashboards, backends, APIs).
367
+ const uiBuildVerb = /\b(?:build|create|make(?!\s+sure\b)|implement|code|develop)\b/u;
368
+ const uiPageNoun = /\b(?:landing\s?page|web\s?page|website|web\s?site|homepage|home\s?page|dashboard|admin\s?(?:panel|console|ui)|settings\s?(?:page|screen)|(?:sign\s?up|log\s?in|checkout|pricing|profile|onboarding)\s?(?:page|screen|form|flow)|user\s?interface|web\s?ui|front\s?end|ui)\b/u;
369
+ const nonInterfaceBuild = /\b(?:grafana|kibana|datadog|metabase|looker|tableau|power\s?bi|backend|back\s?end|api|endpoint|docker|image|cli|migration|schema)\b/u;
370
+ const hasUiBuildIntent = (normalized) => uiBuildVerb.test(normalized) && uiPageNoun.test(normalized) && !nonInterfaceBuild.test(normalized);
371
+ const hasUiDesignIntent = (normalized) => (uiDesignVerb.test(normalized) && uiSurfaceNoun.test(normalized)) || hasUiBuildIntent(normalized);
372
+ // Polish, audit and harden wording (lib/interface-mode.mjs) reaches the interface skill through the
373
+ // same noun half, so "이 문단 다듬어줘" and "서버 상태 점검" stay inert.
374
+ const hasUiModeIntent = (normalized) => hasInterfaceModeWord(normalized) && uiSurfaceNoun.test(normalized);
375
+
376
+ // Office deliverables under a bare `lit`. Same conjunction shape as the UI route: a making
377
+ // verb AND a document or slide noun, because each noun alone is common in engineering talk
378
+ // ("the report says", "deck of cards", "문서 참고"). Hangul terms are bare substrings for the
379
+ // reason given above, except 덱, which would match inside 인덱스 and so needs a non-Hangul
380
+ // neighbour. Code documentation and tool reports are excluded by name: a README, API docs,
381
+ // a docstring, a bug, test, coverage or error report are not Word files. A Markdown file is
382
+ // excluded only when it is a named project document or sits under docs/; any other `.md` is
383
+ // usually the source of the deck or report ("turn notes.md into slides").
384
+ const officeVerb = /\b(?:make|making|made|create|creating|write|writing|draft|drafting|prepare|preparing|build|building|generate|generating|produce|producing|put\s+together|turn\b.*\binto|compile)\b|만들|만드|작성|써\s?줘|써\s?주|써서|써봐|쓰고|정리해|정리하|준비|초안|뽑아|짜\s?줘|구성해/u;
385
+ const slideNoun = /\b(?:slides?|slide\s?deck|deck|presentation|pptx?|powerpoint|keynote)\b|발표|슬라이드|피피티|파워포인트|(?<![가-힣])덱(?![가-힣])|(?<![가-힣])덱을|(?<![가-힣])덱으로/u;
386
+ const documentNoun = /\b(?:reports?|docx|doc|documents?|word\s+(?:doc(?:ument)?|file)|ms\s?word|white\s?papers?|proposals?|memos?)\b|보고서|리포트|기획서|제안서|계획서|문서|워드|백서/u;
387
+ const codeDocumentation = /readme|changelog|contributing|api\s?(?:문서|docs?\b|reference)|docstrings?|jsdoc|javadoc|주석|\b(?:agents|claude|gemini|skill|security|code_of_conduct|license|authors|architecture|support|governance)\.md\b|\bdocs\/|\b(?:bug|test|coverage|error|crash|lint|issue|incident)\s+reports?\b|\breport\s+(?:a|the|this|that)\s+(?:bug|issue|error|problem)/u;
388
+
389
+ // "each document", "all documents", "these docs" spread a task over many files that already exist; one
390
+ // Word deliverable is "a document", "the report", "a docx". A quantified mention is not a deliverable noun.
391
+ const quantifiedDocument = /\b(?:each|every|all|any|both|these|those|other|existing|per)\s+(?:\w+\s+)?(?:documents?|docs?)\b/gu;
392
+
393
+ // A slide count beside a slide noun ("덱 10장", "a 10-slide deck") asks for the deck without a making verb.
394
+ const slideCount = /\d+\s?장|\b\d+[\s-]?slides?\b/u;
395
+
396
+ // Returns the office skills a bare-lit prompt asks for, slides first when both are named.
397
+ const officeIntent = (normalized) => {
398
+ const counted = slideCount.test(normalized) && slideNoun.test(normalized);
399
+ if ((!officeVerb.test(normalized) && !counted) || codeDocumentation.test(normalized)) return [];
400
+ const skills = [];
401
+ if (slideNoun.test(normalized)) skills.push("lit-pptx");
402
+ if (documentNoun.test(normalized.replace(/\b(?:slide|presentation)\s+(?:doc|document)\b/gu, " ").replace(quantifiedDocument, " "))) skills.push("lit-docx");
403
+ return skills;
404
+ };
405
+
406
+ // Film requests under a bare `lit` (MO-C-18..23). A creation verb plus either a compound
407
+ // motion-video noun or a bare video noun fires, unless one of the exclusions names another job:
408
+ // editing existing footage, a video placed inside a page, a video placed inside slides or a
409
+ // report, a text or image artifact about a video, UI motion with no video noun, or video as a
410
+ // software feature (a player, an upload). Bare 모션 / motion / 인트로 / intro never fire alone.
411
+ // Hangul terms are bare substrings for the reason given at the UI route.
412
+ const motionVerb = /\b(?:render|rendering|produce|producing|animate|animating)\b|제작|렌더링|렌더해|영상화/u;
413
+ const motionVideoCompound = /모션\s?그래픽|타이포\s?모션|키네틱\s?타이포|타이포그래피\s?(?:영상|비디오)|(?:가사|리릭)\s?(?:영상|비디오)|뮤직\s?비디오|오프닝\s?타이틀|타이틀\s?시퀀스|\bmotion\s?graphics?\b|\bkinetic\s+(?:type|typography)\b|\btypographic\s+motion\b|\b(?:lyric|music)\s+videos?\b|\btitle\s+sequences?\b|\bopening\s+titles?\b/u;
414
+ const bareVideoNoun = /영상|비디오|동영상|클립(?!보드)|\bvideos?\b|\bclips?\b(?!\s?(?:path|board))/u;
415
+ const footageEdit = /편집|자막|색\s?보정|트리밍|잘라|자르|\b(?:edit|editing|caption|captions|captioning|subtitles?|trim|trimming|crop|cropping|colou?r\s?grad(?:e|ing))\b/u;
416
+ const existingFootage = /(?:이|그|기존|찍은|녹화한|촬영한)\s?(?:영상|클립|동영상|비디오)|\b(?:this|that|the|my|our|existing|recorded)\s+(?:videos?|clips?|footage|recordings?)\b|\bfootage\b/u;
417
+ const webContainer = /페이지|웹사이트|랜딩|화면|컴포넌트|버튼|\b(?:page|pages|website|landing|screen|component|button)\b/u;
418
+ const embedVerb = /넣|삽입|임베드|깔아|깔고|\b(?:embed|embedding|insert|inserting|autoplay)\b/u;
419
+ const backgroundVideo = /배경\s?(?:영상|비디오|동영상)|\b(?:background|hero)\s+videos?\b/u;
420
+ const officeContainer = /발표\s?자료|슬라이드|피피티|보고서|문서|(?<![가-힣])덱(?![가-힣])|\b(?:slides?|deck|pptx?|report|document)\b/u;
421
+ const videoArtifact = /스크립트|대본|썸네일|요약|기획안|\b(?:script|transcript|thumbnails?|summary|summarize|storyboard)\b/u;
422
+ const uiMotionWord = /모션|애니메이션|\bmotion\b|\banimations?\b/u;
423
+ const videoSoftware = /플레이어|업로드|스트리밍|인코딩|\b(?:player|upload|uploader|streaming|playback|encoder|encoding|codec|transcod\w*)\b/u;
424
+
425
+ // Schematic requests under a bare `lit`. A strong noun (P&ID, PFD, cutaway, 계장도, 모식도, 장치도…)
426
+ // is enough; a weak one (schematic, isometric, apparatus) also needs a drawing verb and no
427
+ // web-interface noun, so "an isometric hero for the landing page" stays with the interface route.
428
+ // Hangul terms are bare substrings for the reason given at the UI route.
429
+ const schematicStrongNoun = /\bp\s?&\s?i\s?ds?\b|\bpfds?\b|\bbfds?\b|piping\s+(?:and|&)\s+instrumentation|process\s+flow\s+(?:diagram|sheet)s?|block\s+flow\s+diagrams?|\bplot\s+plans?\b|equipment\s+layouts?|experimental\s+(?:set\s?up|apparatus)|\bcut\s?aways?\b|컷어웨이|배관\s?계장도|계장도|공정\s?흐름도|공정도|모식도|장치도|실험\s?장치|피앤아이디|배치도|계통도|단면도/u;
430
+ // 도면 alone also names a document topic ("도면 번호 체계 정리"), so it needs a drawing verb.
431
+ const schematicWeakNoun = /\bschematics?\b|\bisometric\b|\bapparatus\b|사시도|개략도|아이소메트릭|도면/u;
432
+ // A chart or graph of data belongs to the data-visualization skill even when it names a drawing
433
+ // ("단면도 데이터로 그래프"); "plot plan" is a drawing and stays out.
434
+ const schematicChartNoun = /차트|그래프|\b(?:charts?|graphs?|plots?(?!\s+plans?\b))\b/u;
435
+ // A drawing verb names a picture; a generic making verb ("make", "만들") counts only when no
436
+ // office deliverable is named, so "lit make a report on the P&ID" stays a document request.
437
+ const schematicDrawVerb = /\b(?:draw|drawing|drew|sketch|sketching|illustrate|illustrating|render|rendering|redraw)\b|그려|그리|그림|도식|작도/u;
438
+ // Whole interfaces a schematic can sit inside. "레이아웃" and "layout" stay out: an equipment layout
439
+ // is a drawing.
440
+ const schematicInterfaceNoun = /\b(?:dashboards?|landing\s?pages?|web\s?pages?|websites?|homepages?|web\s?apps?|apps?|screens?|admin\s?(?:panel|console)|user\s?interface|ui)\b|대시보드|웹사이트|랜딩|페이지|화면|앱/u;
441
+ const schematicMakeVerb =/\b(?:make|making|create|creating|design|designing|build|lay\s?out)\b|만들|만드/u;
442
+ const hasSchematicIntent = (normalized) => {
443
+ if (schematicStrongNoun.test(normalized)) return true;
444
+ return schematicWeakNoun.test(normalized) && (schematicDrawVerb.test(normalized) || schematicMakeVerb.test(normalized)) && !webContainer.test(normalized);
445
+ };
446
+
447
+ const hasMotionVideoIntent = (normalized) => {
448
+ if (!(officeVerb.test(normalized) || uiDesignVerb.test(normalized) || motionVerb.test(normalized))) return false;
449
+ const bare = bareVideoNoun.test(normalized);
450
+ if (!motionVideoCompound.test(normalized) && !bare) return false;
451
+ if (footageEdit.test(normalized) && existingFootage.test(normalized)) return false;
452
+ if (backgroundVideo.test(normalized) || (webContainer.test(normalized) && embedVerb.test(normalized))) return false;
453
+ if (officeContainer.test(normalized) && embedVerb.test(normalized)) return false;
454
+ if (videoArtifact.test(normalized)) return false;
455
+ if (!bare && uiMotionWord.test(normalized) && uiSurfaceNoun.test(normalized)) return false;
456
+ return !videoSoftware.test(normalized);
457
+ };
458
+
459
+ // Structural search intent. Same conjunction shape as the UI route, but the discriminating half
460
+ // is the OBJECT, not the verb: whether the thing being searched is a syntax construct or a
461
+ // string. "find the login handler" stays inert because a handler is not a syntax shape; "find
462
+ // every call site" fires because a call site is. Either half alone is far too common.
463
+ const structuralVerb = /\b(?:find|locate|search|rewrite|replace|migrate|codemod)\b/u;
464
+ // ADAPTED from the sibling's list after measuring it here. Dropped bare `signatures?` — it fired
465
+ // on "search the changelog for signatures" (cryptographic, not code) — keeping the qualified
466
+ // `function|method signatures?`. Dropped `references to` — "find references to this symbol" is a
467
+ // SEMANTIC question this skill explicitly routes to Skill(lsp), so matching it here would
468
+ // contradict the skill's own boundary. Added `syntax shape`.
469
+ // THE LINE: ask the language server WHO and WHAT; ask a structural engine WHAT SHAPE.
470
+ // A call site is a syntax node — the `foo($$$ARGS)` expression. A CALLER is the enclosing
471
+ // function that contains it, and naming that requires scope and symbol resolution. Same for
472
+ // `usages of X` and `references to X`: deciding which `X` is *this* X is symbol resolution,
473
+ // which a tree matcher cannot do and will silently over-match on same-named symbols.
474
+ // So every WHO/WHICH-SYMBOL term is excluded and routed to Skill(lsp) by the body:
475
+ // callers · call graph · invocations · references to · usages of · every/all usages
476
+ // This is also why the near-synonym objection is retired: "find every call site" and "find all
477
+ // the callers" were never one intent split by wording — they are two different skills' work.
478
+ const structuralShape = /\b(?:call ?sites?|callsites?|declarations?|import statements?|imports|(?:function|method) signatures?|syntax (?:tree|shape)|ast)\b/u;
479
+ // KNOWN over-fires, kept on purpose: "find the imports in this file" and "locate the AST dump
480
+ // file" both match. The cost is asymmetric — a false fire ends in "probe -> unavailable ->
481
+ // labelled textual", which is what the model would have done anyway, while a MISS on "replace
482
+ // all imports of lodash" produces a naive text replace that breaks code.
483
+ const hasStructuralSearchIntent = (normalized) => structuralVerb.test(normalized) && structuralShape.test(normalized);
484
+
485
+ // Companion-only detectors (S1). Neither ever becomes the primary route: "chart" and "diagram" alone must
486
+ // not pull interface or loop work away (see the lit-diagram-drawer row above). A figure of data needs a
487
+ // plot noun plus measured data or a plotting verb; a diagram needs a diagram noun plus a drawing or making verb.
488
+ const vizNoun = /\b(?:plots?(?!\s+plans?\b)|charts?|graphs?|figures?|histograms?|heat\s?maps?|scatter\s?plots?|box\s?plots?)\b|그래프|차트|플롯|히스토그램|산점도|시각화|그림\s?\d/u;
489
+ const vizCue = /\b(?:data|dataset|csv|xlsx|measure(?:d|ments?)|results?|experiments?|publication|paper|journal)\b|데이터|측정|실험|결과|논문|저널|\b(?:plot|visuali[sz]e)\b/u;
490
+ const hasDataVizIntent = (normalized) => vizNoun.test(normalized) && vizCue.test(normalized);
491
+ const diagramNoun = /\b(?:diagrams?|flow\s?charts?|sequence\s+diagrams?|architecture\s+(?:diagram|map)|system\s+map|timeline\s+(?:diagram|graphic))\b|다이어그램|도식|흐름도|구성도|순서도/u;
492
+ const hasDiagramIntent = (normalized) => diagramNoun.test(normalized) && (schematicDrawVerb.test(normalized) || schematicMakeVerb.test(normalized) || officeVerb.test(normalized));
493
+
494
+ // Every content route a bare-lit prompt matches, in the cascade's own priority order (S1). The cascade
495
+ // still chooses the primary; lib/skill-plan.mjs turns the rest into companions.
496
+ const naturalLitCompanions = (normalized) => {
497
+ const routes = [];
498
+ if (hasMotionVideoIntent(normalized)) routes.push(schematicStrongNoun.test(normalized) ? "lit-schematic" : "lit-typographic-motion");
499
+ if (hasSchematicIntent(normalized) && !schematicChartNoun.test(normalized)) routes.push("lit-schematic");
500
+ routes.push(...officeIntent(normalized));
501
+ if (hasExplicitResearchRoute(normalized)) routes.push("litresearch");
502
+ if (hasUiDesignIntent(normalized) || hasUiModeIntent(normalized)) routes.push("frontend-ui-ux");
503
+ if (hasDataVizIntent(normalized)) routes.push("lit-scientific-visualization");
504
+ if (hasDiagramIntent(normalized)) routes.push("lit-diagram-drawer");
505
+ if (hasStructuralSearchIntent(normalized)) routes.push("structural-search");
506
+ return [...new Set(routes)];
507
+ };
508
+
509
+ const findNaturalLitTrigger = (prompt) => {
510
+ const raw = rawTriggerText(prompt);
511
+ if (containsSlashCommandMention(raw)) return undefined;
512
+ if (containsCompoundBoundedWord(raw, "litresearch")) return { ...triggerByToken.litresearch, source: "bare-command" };
513
+ if (!hasLitTrigger(raw)) return undefined;
514
+
515
+ const normalized = normalizedTriggerText(prompt);
516
+ if (hasExplicitTeamRoute(normalized)) return { ...triggerByToken["agent-team"], source: "natural-language" };
517
+ if (hasExplicitWorkflowRoute(normalized)) return { ...triggerByToken["native-workflow"], source: "natural-language" };
518
+ // Ahead of the plan and review words: "lit brainstorm a plan for the launch" asks for options, and the
519
+ // word `plan` inside it must not pull the prompt to lit-plan.
520
+ if (hasExplicitUltraBrainstormRoute(normalized)) return { ...triggerByToken["ultra-brainstorm"], source: "natural-language" };
521
+ if (hasExplicitBrainstormRoute(normalized)) return { ...triggerByToken["lit-brainstorm"], source: "natural-language" };
522
+ // Ahead of plan, review and research for the same reason: "lit hijack the review lanes into my plan
523
+ // skill" names other skills as material, not as the route.
524
+ if (hasExplicitHijackRoute(normalized)) return { ...triggerByToken["lit-hijack"], source: "natural-language" };
525
+ if (containsPlainWord(normalized, "plan") && hasReviewModifier(prompt)) {
526
+ return { ...triggerByToken["lit-plan"], source: "natural-language" };
527
+ }
528
+ if (containsPlainWord(normalized, "review")) return { ...triggerByToken["review-work"], source: "natural-language" };
529
+ // Above the lit-loop fallthrough: "lit debug the hang" should reach the debugging methodology rather
530
+ // than a generic loop. Both stems are checked because the word boundary makes "debug" miss "debugging".
531
+ if (containsPlainWord(normalized, "debug") || containsPlainWord(normalized, "debugging")) {
532
+ return { ...triggerByToken.debugging, source: "natural-language" };
533
+ }
534
+ if (/^\s*lit(?:work)?\s+start\s+work(?=$|[^\w-])/u.test(normalized)) {
535
+ return { ...triggerByToken["start-work"], source: "natural-language", safetyBlock: true };
536
+ }
537
+ // A cutaway, P&ID or apparatus asked for as a film ("lit 컷어웨이를 모션 영상으로") stays with
538
+ // lit-schematic, which draws the equipment and renders its loop itself; a film about anything
539
+ // else keeps going to the motion route below.
540
+ if (schematicStrongNoun.test(normalized) && hasMotionVideoIntent(normalized)) {
541
+ return { ...triggerByToken["lit-schematic"], source: "natural-language" };
542
+ }
543
+ // Above office and UI (MO-C-18): once the motion trigger matched, a video noun wins over 발표 or
544
+ // 타이포그래피 also in the prompt. "발표자료 만들어줘 lit" (no video noun) still reaches lit-pptx.
545
+ if (hasMotionVideoIntent(normalized)) {
546
+ return { ...triggerByToken["lit-typographic-motion"], source: "natural-language", styleGate: false };
547
+ }
548
+ // Above office, research, goal and plan: "lit 논문용 실험 장치 모식도 그려줘" and "lit draw the
549
+ // plot plan" ask for a drawing. A schematic word in a request to write a report ("lit P&ID 설명
550
+ // 보고서 작성") has no drawing verb and still reaches the office route below.
551
+ // When the deliverable is an interface ("lit build a dashboard showing the P&ID"), frontend-ui-ux
552
+ // owns it and lit-schematic draws only the drawing inside; a drawing verb keeps the drawing here.
553
+ const office = officeIntent(normalized);
554
+ const interfaceDeliverable = hasUiDesignIntent(normalized) && schematicInterfaceNoun.test(normalized) && !schematicDrawVerb.test(normalized);
555
+ if (hasSchematicIntent(normalized) && !interfaceDeliverable && !schematicChartNoun.test(normalized) && (schematicDrawVerb.test(normalized) || office.length === 0)) {
556
+ return { ...triggerByToken["lit-schematic"], source: "natural-language" };
557
+ }
558
+ // Above research, goal and plan: "조사해서 보고서로 만들어줘 lit" and "write a project plan
559
+ // document lit" ask for a file, and the office skill covers the gathering step itself.
560
+ if (office.length > 0) {
561
+ return { ...triggerByToken[office[0]], source: "natural-language", officeSkills: office };
562
+ }
563
+ if (hasExplicitResearchRoute(normalized)) return { ...triggerByToken.litresearch, source: "natural-language" };
564
+ if (containsPlainWord(normalized, "goal")) return { ...triggerByToken.litgoal, source: "natural-language" };
565
+ if (containsPlainWord(normalized, "plan")) return { ...triggerByToken["lit-plan"], source: "natural-language" };
566
+ // Above the lit-loop fallthrough, same position as the debugging route: "lit restyle the
567
+ // dashboard" should reach the interface skill rather than a generic loop.
568
+ if (hasUiDesignIntent(normalized) || hasUiModeIntent(normalized)) return { ...triggerByToken["frontend-ui-ux"], source: "natural-language" };
569
+ if (hasStructuralSearchIntent(normalized)) return { ...triggerByToken["structural-search"], source: "natural-language" };
570
+ if (containsPlainWord(normalized, "start") && containsPlainWord(normalized, "work") && !hasTrailingLitInvocation(normalized)) return undefined;
571
+ return { ...triggerByToken["lit-loop"], source: "natural-language", softConfirm: bareLitPattern.test(raw) };
572
+ };
573
+
574
+ const findWorkflowTrigger = (prompt) => {
575
+ const raw = rawTriggerText(prompt);
576
+ const dollarTrigger = findDollarCommandTrigger(raw);
577
+ if (dollarTrigger) return dollarTrigger;
578
+ if (/(?:^|\s)\$start-work(?=$|[^\w-])/u.test(raw) && !hasTrailingLitInvocation(raw)) return undefined;
579
+ if (containsSlashCommandMention(raw)) return undefined;
580
+ // Ahead of the leading-bare check on purpose: `litwork comprehend` would otherwise match
581
+ // the bare `litwork` token first and inject the wrong body. A two-token phrase names the
582
+ // route more specifically than either token alone, so it wins.
583
+ const comprehendPhraseTrigger = findComprehendPhraseTrigger(raw);
584
+ if (comprehendPhraseTrigger) return comprehendPhraseTrigger;
585
+ const adhdPhraseTrigger = findAdhdPhraseTrigger(raw);
586
+ if (adhdPhraseTrigger) return adhdPhraseTrigger;
587
+ const bareCommandTrigger = findLeadingBareCommandTrigger(raw);
588
+ if (bareCommandTrigger) return bareCommandTrigger;
589
+ for (const token of ["lit-crucible", "lit-init", "lit-burnoff", "lit-burnoff-file"]) {
590
+ if (containsCompoundBoundedWord(raw, token)) return { ...triggerByToken[token], source: "bare-command" };
591
+ const oldId = Object.keys(renameAliases).find((id) => renameAliases[id] === token);
592
+ if (oldId && containsCompoundBoundedWord(raw, oldId)) return { ...triggerByToken[oldId], source: "bare-command" };
593
+ }
594
+ const recapTrigger = findRecapTrigger(raw);
595
+ if (recapTrigger) return recapTrigger;
596
+ const naturalTrigger = findNaturalLitTrigger(prompt);
597
+ if (naturalTrigger) return naturalTrigger;
598
+ // Last resort, and the only route that fires with no lit-family token at all. A design
599
+ // request is the one case where waiting for the user to name LitClaude defeats the point:
600
+ // by the time they know to ask for the interface skill, the CSS is already written.
601
+ // Runs AFTER the whole lit cascade, so it can never hijack an explicit lit route.
602
+ // A motion-video request is not an interface request; with no `lit` it activates nothing, since
603
+ // there is deliberately no token-free motion route.
604
+ if ((hasUiDesignIntent(normalizedTriggerText(prompt)) || hasUiModeIntent(normalizedTriggerText(prompt))) && !hasMotionVideoIntent(normalizedTriggerText(prompt))) {
605
+ return { ...triggerByToken["frontend-ui-ux"], source: "natural-language" };
606
+ }
607
+ if (hasStructuralSearchIntent(normalizedTriggerText(prompt))) {
608
+ return { ...triggerByToken["structural-search"], source: "natural-language" };
609
+ }
610
+ return undefined;
611
+ };
612
+
613
+ // A review modifier anywhere in the prompt makes dual plan review REQUIRED, not optional.
614
+ // Korean "고정밀" is included because the trigger vocabulary is bilingual; the match runs on
615
+ // code-stripped text so a quoted example in a fence cannot arm the gate.
616
+ const reviewModifierPattern = /high[-\s]?accuracy|고정밀|deep\s+review|rigorous\s+review|strict\s+review/iu;
617
+
618
+ const hasReviewModifier = (prompt) => reviewModifierPattern.test(withoutCode(typeof prompt === "string" ? prompt : ""));
619
+
620
+ // explainRoute mirrors the findWorkflowTrigger cascade as an ordered rule list so it can name the rule
621
+ // that won and the next rule that also matched. The route itself always comes from findWorkflowTrigger;
622
+ // the rule list only explains it, and test/route-why.test.mjs holds the two together. A stop rule ends
623
+ // the cascade (`all`) or only the bare-lit part of it (`natural`) without choosing a route. Rules marked
624
+ // `lit` run only when the prompt carries `lit`/`litwork`, as findNaturalLitTrigger requires.
625
+ const routeOf = (token) => triggerByToken[token];
626
+ const namedRuleId = (prefix, trigger) => `${prefix}:${trigger.renameFrom ?? trigger.agentId ?? trigger.movedFrom ?? trigger.skillId}`;
627
+ const ROUTE_RULES = [
628
+ { id: (trigger) => namedRuleId("dollar-command", trigger), match: ({ raw }) => findDollarCommandTrigger(raw) },
629
+ { id: "stop:start-work-not-leading", stop: "all", match: ({ raw }) => /(?:^|\s)\$start-work(?=$|[^\w-])/u.test(raw) && !hasTrailingLitInvocation(raw) },
630
+ { id: "stop:slash-command-mention", stop: "all", match: ({ raw }) => containsSlashCommandMention(raw) },
631
+ { id: "phrase:lit-comprehend", match: ({ raw }) => findComprehendPhraseTrigger(raw) },
632
+ { id: "phrase:lit-adhd", match: ({ raw }) => findAdhdPhraseTrigger(raw) },
633
+ { id: (trigger) => namedRuleId("bare-command", trigger), match: ({ raw }) => findLeadingBareCommandTrigger(raw) },
634
+ {
635
+ id: (trigger) => namedRuleId("token", trigger),
636
+ match: ({ raw }) => {
637
+ for (const token of ["lit-crucible", "lit-init", "lit-burnoff", "lit-burnoff-file"]) {
638
+ if (containsCompoundBoundedWord(raw, token)) return routeOf(token);
639
+ const oldId = Object.keys(renameAliases).find((id) => renameAliases[id] === token);
640
+ if (oldId && containsCompoundBoundedWord(raw, oldId)) return routeOf(oldId);
641
+ }
642
+ return undefined;
643
+ },
644
+ },
645
+ { id: "recap:lit-recap", match: ({ raw }) => findRecapTrigger(raw) },
646
+ { id: "token:litresearch", match: ({ raw }) => containsCompoundBoundedWord(raw, "litresearch") && routeOf("litresearch") },
647
+ { id: "natural:team", lit: true, match: ({ normalized }) => hasExplicitTeamRoute(normalized) && routeOf("agent-team") },
648
+ { id: "natural:workflow", lit: true, match: ({ normalized }) => hasExplicitWorkflowRoute(normalized) && routeOf("native-workflow") },
649
+ { id: "natural:ultra-brainstorm", lit: true, match: ({ normalized }) => hasExplicitUltraBrainstormRoute(normalized) && routeOf("ultra-brainstorm") },
650
+ { id: "natural:brainstorm", lit: true, match: ({ normalized }) => hasExplicitBrainstormRoute(normalized) && routeOf("lit-brainstorm") },
651
+ { id: "natural:hijack", lit: true, match: ({ normalized }) => hasExplicitHijackRoute(normalized) && routeOf("lit-hijack") },
652
+ { id: "natural:plan-review-modifier", lit: true, match: ({ normalized, prompt }) => containsPlainWord(normalized, "plan") && hasReviewModifier(prompt) && routeOf("lit-plan") },
653
+ { id: "natural:review", lit: true, match: ({ normalized }) => containsPlainWord(normalized, "review") && routeOf("review-work") },
654
+ { id: "natural:debug", lit: true, match: ({ normalized }) => (containsPlainWord(normalized, "debug") || containsPlainWord(normalized, "debugging")) && routeOf("debugging") },
655
+ { id: "natural:start-work", lit: true, match: ({ normalized }) => /^\s*lit(?:work)?\s+start\s+work(?=$|[^\w-])/u.test(normalized) && routeOf("start-work") },
656
+ { id: "natural:schematic-film", lit: true, match: ({ normalized }) => schematicStrongNoun.test(normalized) && hasMotionVideoIntent(normalized) && routeOf("lit-schematic") },
657
+ { id: "natural:motion", lit: true, match: ({ normalized }) => hasMotionVideoIntent(normalized) && routeOf("lit-typographic-motion") },
658
+ {
659
+ id: "natural:schematic",
660
+ lit: true,
661
+ match: ({ normalized }) => {
662
+ const interfaceDeliverable = hasUiDesignIntent(normalized) && schematicInterfaceNoun.test(normalized) && !schematicDrawVerb.test(normalized);
663
+ return hasSchematicIntent(normalized) && !interfaceDeliverable && !schematicChartNoun.test(normalized)
664
+ && (schematicDrawVerb.test(normalized) || officeIntent(normalized).length === 0) && routeOf("lit-schematic");
665
+ },
666
+ },
667
+ { id: "natural:office", lit: true, match: ({ normalized }) => routeOf(officeIntent(normalized)[0]) },
668
+ { id: "natural:research", lit: true, match: ({ normalized }) => hasExplicitResearchRoute(normalized) && routeOf("litresearch") },
669
+ { id: "natural:goal", lit: true, match: ({ normalized }) => containsPlainWord(normalized, "goal") && routeOf("litgoal") },
670
+ { id: "natural:plan", lit: true, match: ({ normalized }) => containsPlainWord(normalized, "plan") && routeOf("lit-plan") },
671
+ { id: "natural:interface", lit: true, match: ({ normalized }) => (hasUiDesignIntent(normalized) || hasUiModeIntent(normalized)) && routeOf("frontend-ui-ux") },
672
+ { id: "natural:structural-search", lit: true, match: ({ normalized }) => hasStructuralSearchIntent(normalized) && routeOf("structural-search") },
673
+ { id: "stop:start-work-words", stop: "natural", lit: true, match: ({ normalized }) => containsPlainWord(normalized, "start") && containsPlainWord(normalized, "work") && !hasTrailingLitInvocation(normalized) },
674
+ { id: "natural:lit-loop", lit: true, fallback: true, match: () => routeOf("lit-loop") },
675
+ { id: "untokened:interface", match: ({ normalized }) => (hasUiDesignIntent(normalized) || hasUiModeIntent(normalized)) && !hasMotionVideoIntent(normalized) && routeOf("frontend-ui-ux") },
676
+ { id: "untokened:structural-search", match: ({ normalized }) => hasStructuralSearchIntent(normalized) && routeOf("structural-search") },
677
+ ];
678
+
679
+ // `{route, ruleId, runnerUp, inert}` for one prompt. route is the discipline the hook ignites (null for
680
+ // none); runnerUp is the next non-fallback rule that matched a different route. inert is true when no
681
+ // route fired because text was set aside (a fence, inline code, a host block) or a stop rule held.
682
+ // Routes the hook decides before this cascade (an exact `handoff`, a `lit +…` skill plan, start-work
683
+ // invocations and replies) are outside it.
684
+ export const explainRoute = (prompt) => {
685
+ if (typeof prompt !== "string") return { route: null, ruleId: null, runnerUp: null, inert: false };
686
+ const route = findWorkflowTrigger(prompt)?.discipline ?? null;
687
+ const raw = rawTriggerText(prompt);
688
+ const context = { prompt, raw, normalized: normalizedTriggerText(prompt), lit: hasLitTrigger(raw) };
689
+ let winner = null;
690
+ let runnerUp = null;
691
+ let stopId = null;
692
+ let naturalStopped = false;
693
+ for (const rule of ROUTE_RULES) {
694
+ if (rule.lit && !context.lit) continue;
695
+ const hit = rule.match(context);
696
+ if (!hit) continue;
697
+ if (rule.stop) {
698
+ if (!winner && !stopId) {
699
+ if (rule.stop === "all") stopId = rule.id;
700
+ else naturalStopped = true;
701
+ }
702
+ continue;
703
+ }
704
+ const found = { route: hit.discipline, ruleId: typeof rule.id === "function" ? rule.id(hit) : rule.id };
705
+ if (!winner && !stopId && !(naturalStopped && rule.lit)) winner = found;
706
+ else if (!runnerUp && !rule.fallback && found.route !== (winner?.route ?? null)) runnerUp = found;
707
+ }
708
+ const setAside = withoutCode(withoutHostNotifications(prompt)) !== prompt.replace(/\r\n|\r/gu, "\n");
709
+ if (route !== null) return { route, ruleId: winner?.route === route ? winner.ruleId : "unattributed", runnerUp, inert: false };
710
+ if (winner) return { route, ruleId: "unattributed", runnerUp, inert: false };
711
+ const held = stopId ?? (naturalStopped ? "stop:start-work-words" : null);
712
+ return { route, ruleId: held ?? (setAside ? "inert:set-aside" : null), runnerUp, inert: held !== null || setAside };
713
+ };
714
+
715
+ export {
716
+ bareLitPattern,
717
+ containsSlashCommandMention,
718
+ findNaturalLitTrigger,
719
+ findWorkflowTrigger,
720
+ hasLitTrigger,
721
+ hasReviewModifier,
722
+ naturalLitCompanions,
723
+ normalizedTriggerText,
724
+ rawTriggerText,
725
+ restartLitPattern,
726
+ resumeLitPattern,
727
+ triggerByToken,
728
+ withoutCode,
729
+ };