project-brain 0.46.0 → 0.48.0

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,369 @@
1
+ import { atom, read, update } from 'claude-code'
2
+ import type { Hook, Register } from 'claude-code'
3
+
4
+ import type { PreviewView } from '../types'
5
+ import {
6
+ LAUNCH_TIMEOUT_MS,
7
+ NVIM_TIMEOUT_MS,
8
+ READ_TIMEOUT_MS,
9
+ TEXT_PREVIEW_MAX_BYTES,
10
+ THUMB_TIMEOUT_MS,
11
+ absoluteOf,
12
+ baseName,
13
+ cacheKey,
14
+ checkContent,
15
+ checkTarget,
16
+ createBoundedCache,
17
+ createFailureMemo,
18
+ createLatest,
19
+ detectPaths,
20
+ editorArgv,
21
+ editorCommand,
22
+ floatExpr,
23
+ headLines,
24
+ isDefaultSocketName,
25
+ isForbiddenRoot,
26
+ isNvim,
27
+ isSecretName,
28
+ isTerminalEditor,
29
+ kindOf,
30
+ nvimExprArgv,
31
+ openExpr,
32
+ parseReadOnce,
33
+ pickServer,
34
+ privateDirArgv,
35
+ readOnceArgv,
36
+ readOnlyNvimArgv,
37
+ socketDirs,
38
+ splitRoots,
39
+ supacodeTabArgv,
40
+ thumbnailArgv,
41
+ toolTarget,
42
+ } from './core'
43
+ import type { Kind, Target } from './core'
44
+
45
+ type Api = Parameters<Hook<'ui.press'>>[0]
46
+
47
+ const PANE = 'file-preview'
48
+
49
+ const EMPTY: PreviewView = { id: 0, title: '', note: '', lines: [], image: '', generation: 0 }
50
+ const view = atom({ plugin: 'project-brain-file-preview', key: 'view' } as const, EMPTY, { shape: 'view-1' })
51
+
52
+ type Env = {
53
+ PB_EDITOR?: string
54
+ VISUAL?: string
55
+ EDITOR?: string
56
+ PB_NVIM_SERVER?: string
57
+ NVIM?: string
58
+ PB_PREVIEW_ROOTS?: string
59
+ PB_PREVIEW_IMAGES?: string
60
+ SUPACODE_SOCKET_PATH?: string
61
+ TMPDIR?: string
62
+ XDG_RUNTIME_DIR?: string
63
+ USER?: string
64
+ HOME?: string
65
+ }
66
+
67
+ const readEnv = async ($: Api): Promise<Env> => ({
68
+ PB_EDITOR: await $.env.get('PB_EDITOR'),
69
+ VISUAL: await $.env.get('VISUAL'),
70
+ EDITOR: await $.env.get('EDITOR'),
71
+ PB_NVIM_SERVER: await $.env.get('PB_NVIM_SERVER'),
72
+ NVIM: await $.env.get('NVIM'),
73
+ PB_PREVIEW_ROOTS: await $.env.get('PB_PREVIEW_ROOTS'),
74
+ PB_PREVIEW_IMAGES: await $.env.get('PB_PREVIEW_IMAGES'),
75
+ SUPACODE_SOCKET_PATH: await $.env.get('SUPACODE_SOCKET_PATH'),
76
+ TMPDIR: await $.env.get('TMPDIR'),
77
+ XDG_RUNTIME_DIR: await $.env.get('XDG_RUNTIME_DIR'),
78
+ USER: await $.env.get('USER'),
79
+ HOME: await $.env.get('HOME'),
80
+ })
81
+
82
+ /** `$.process.run` kills the child when `timeoutMs` passes and rejects; a rejection reads as no answer. */
83
+ const run = async ($: Api, argv: string[], timeoutMs: number) => {
84
+ try {
85
+ return await $.process.run(argv, { timeoutMs })
86
+ } catch {
87
+ return undefined
88
+ }
89
+ }
90
+
91
+ const realDir = async ($: Api, path: string): Promise<string | undefined> => {
92
+ const stat = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
93
+ return stat?.kind === 'dir' ? stat.realPath : undefined
94
+ }
95
+
96
+ const projectDirs = async ($: Api, env: Env): Promise<string[]> => {
97
+ const home = env.HOME === undefined ? undefined : await realDir($, env.HOME)
98
+ const spelled = [await $.session.cwd(), await $.session.root(), ...splitRoots(env.PB_PREVIEW_ROOTS)]
99
+ const resolved = await Promise.all(spelled.map(path => realDir($, path)))
100
+ return [...new Set(resolved.filter((path): path is string => path !== undefined && !isForbiddenRoot(path, home ?? env.HOME)))]
101
+ }
102
+
103
+ type Resolved = { real: string; size: number; mtimeMs: number; kind: Kind }
104
+
105
+ const resolveTarget = async ($: Api, env: Env, spelled: string): Promise<Resolved | string> => {
106
+ const roots = await projectDirs($, env)
107
+ const absolute = absoluteOf(spelled, await $.session.cwd())
108
+ const stat = await $.fs.stat(absolute, { resolve: true }).catch(() => undefined)
109
+ const verdict = checkTarget({ spelled: absolute, real: stat?.realPath, kind: stat?.kind, roots })
110
+ if (!verdict.ok) return verdict.reason
111
+ return { real: verdict.real, size: stat?.size ?? 0, mtimeMs: stat?.mtimeMs ?? 0, kind: kindOf(verdict.real) }
112
+ }
113
+
114
+ const tell = ($: Api, text: string) => $.ui.toast(`file preview: ${text}`)
115
+
116
+ const sockets = async ($: Api, env: Env): Promise<string[]> => {
117
+ const found: string[] = []
118
+ for (const { dir, nested } of socketDirs(env)) {
119
+ const entries = await $.fs.list(dir).catch(() => [])
120
+ if (!nested) {
121
+ for (const entry of entries) if (isDefaultSocketName(entry.name)) found.push(`${dir}/${entry.name}`)
122
+ continue
123
+ }
124
+ for (const sub of entries) {
125
+ if (sub.kind !== 'dir') continue
126
+ const inner = await $.fs.list(`${dir}/${sub.name}`).catch(() => [])
127
+ for (const entry of inner) if (isDefaultSocketName(entry.name)) found.push(`${dir}/${sub.name}/${entry.name}`)
128
+ }
129
+ }
130
+ return found
131
+ }
132
+
133
+ const failures = createFailureMemo()
134
+
135
+ const findServer = async ($: Api, env: Env): Promise<string | undefined> => {
136
+ const now = await $.clock.now()
137
+ return pickServer({
138
+ explicit: env.PB_NVIM_SERVER,
139
+ inherited: env.NVIM,
140
+ sockets: await sockets($, env),
141
+ projectDirs: await projectDirs($, env),
142
+ cwdOf: async server => {
143
+ if (failures.isSkipped(server, now)) return undefined
144
+ const answer = await run($, nvimExprArgv(server, 'getcwd()'), NVIM_TIMEOUT_MS)
145
+ if (answer?.exitCode !== 0) {
146
+ failures.fail(server, now)
147
+ return undefined
148
+ }
149
+ failures.ok(server)
150
+ return answer.stdout.trim()
151
+ },
152
+ })
153
+ }
154
+
155
+ const hasSupacode = (env: Env) => (env.SUPACODE_SOCKET_PATH ?? '') !== ''
156
+
157
+ type Checked = { ok: true; text: string; base64: string; truncated: boolean } | { ok: false; reason: string }
158
+
159
+ /** The one read of a preview's bytes; everything shown afterwards is these bytes, checked whole. */
160
+ const readChecked = async ($: Api, real: string): Promise<Checked> => {
161
+ const done = await run($, readOnceArgv(real), READ_TIMEOUT_MS)
162
+ if (done === undefined || done.exitCode !== 0) return { ok: false, reason: 'the file could not be read (perl is needed)' }
163
+ const read = parseReadOnce(done.stdout)
164
+ if (!read.ok) return read
165
+ const shown = checkContent(read.bytes, bytes => new TextDecoder().decode(bytes))
166
+ if (!shown.ok) return shown
167
+ return { ok: true, text: shown.text, base64: read.base64, truncated: read.truncated || read.size > TEXT_PREVIEW_MAX_BYTES }
168
+ }
169
+
170
+ const showPane = async ($: Api, next: Omit<PreviewView, 'id'>, id: number) => {
171
+ await update($, view, () => ({ ...next, id }))
172
+ await $.ui.open({ id: PANE, title: next.title })
173
+ }
174
+
175
+ let ownDir: string | undefined
176
+
177
+ /** The mod's own 0700 directory from `mktemp -d`, made once per load. */
178
+ const privateDir = async ($: Api, env: Env): Promise<string | undefined> => {
179
+ if (ownDir !== undefined) return ownDir
180
+ const made = await run($, privateDirArgv(env.TMPDIR), LAUNCH_TIMEOUT_MS)
181
+ const dir = made?.exitCode === 0 ? made.stdout.trim() : ''
182
+ if (!dir.startsWith('/') || /[\u0000-\u001f]/.test(dir)) return undefined
183
+ ownDir = dir
184
+ return dir
185
+ }
186
+
187
+ const thumbnail = async ($: Api, env: Env, target: Resolved, isCurrent: () => boolean): Promise<string | undefined> => {
188
+ if (target.kind === 'text') return undefined
189
+ const dir = await privateDir($, env)
190
+ if (dir === undefined) return undefined
191
+ const out = `${dir}/${cacheKey(target.real, target.size, target.mtimeMs)}.png`
192
+ if (await $.fs.exists(out).catch(() => false)) return out
193
+ if (!isCurrent()) return undefined
194
+ const made = await run($, thumbnailArgv(target.kind, target.real, out), THUMB_TIMEOUT_MS)
195
+ return made?.exitCode === 0 && (await $.fs.exists(out).catch(() => false)) ? out : undefined
196
+ }
197
+
198
+ const openWithSystem = async ($: Api, real: string): Promise<boolean> => {
199
+ const { platform } = await $.session.info()
200
+ if (platform !== 'macos') return false
201
+ return (await run($, ['open', real], LAUNCH_TIMEOUT_MS))?.exitCode === 0
202
+ }
203
+
204
+ let requests = 0
205
+ let latest: ReturnType<typeof createLatest> | undefined
206
+
207
+ const previewFile = async ($: Api, target: Target, surface: string): Promise<void> => {
208
+ latest ??= createLatest(ms => $.clock.sleep(ms))
209
+ const id = ++requests
210
+ await latest.run(async isCurrent => {
211
+ const env = await readEnv($)
212
+ const found = await resolveTarget($, env, target.path)
213
+ if (typeof found === 'string') return tell($, found)
214
+ const title = baseName(found.real)
215
+
216
+ if (found.kind !== 'text') {
217
+ if (env.PB_PREVIEW_IMAGES === '1' && surface === 'terminal') {
218
+ const png = await thumbnail($, env, found, isCurrent)
219
+ if (!isCurrent()) return
220
+ if (png !== undefined) return showPane($, { title, note: found.real, lines: [], image: png, generation: Math.floor(found.mtimeMs) }, id)
221
+ }
222
+ if (!(await openWithSystem($, found.real))) tell($, 'no viewer for this file here')
223
+ return
224
+ }
225
+
226
+ const checked = await readChecked($, found.real)
227
+ if (!checked.ok) return tell($, `not previewed: ${checked.reason}`)
228
+ if (!isCurrent()) return
229
+
230
+ const server = await findServer($, env)
231
+ if (!isCurrent()) return
232
+ if (server !== undefined) {
233
+ const shown = await run($, nvimExprArgv(server, floatExpr(found.real, checked.base64, target.line)), NVIM_TIMEOUT_MS)
234
+ if (shown?.exitCode === 0) return
235
+ }
236
+ const copy = hasSupacode(env) ? await privateDir($, env) : undefined
237
+ if (copy !== undefined) {
238
+ const file = `${copy}/${cacheKey(found.real, found.size, found.mtimeMs)}-${title}`
239
+ const written = await $.fs.write(file, checked.text).then(() => true, () => false)
240
+ const tab = written ? await run($, supacodeTabArgv(title, readOnlyNvimArgv(file, target.line), true), LAUNCH_TIMEOUT_MS) : undefined
241
+ if (tab?.exitCode === 0) return
242
+ }
243
+
244
+ const note = checked.truncated ? `${found.real} (the head only)` : found.real
245
+ return showPane($, { title, note, lines: headLines(checked.text), image: '', generation: 0 }, id)
246
+ })
247
+ }
248
+
249
+ const openFile = async ($: Api, target: Target): Promise<void> => {
250
+ const env = await readEnv($)
251
+ const found = await resolveTarget($, env, target.path)
252
+ if (typeof found === 'string') return tell($, found)
253
+ if (found.kind !== 'text') {
254
+ if (!(await openWithSystem($, found.real))) tell($, 'no viewer for this file here')
255
+ return
256
+ }
257
+ const editor = editorCommand(env)
258
+ if (isNvim(editor)) {
259
+ const server = await findServer($, env)
260
+ if (server !== undefined) {
261
+ const opened = await run($, nvimExprArgv(server, openExpr(found.real, target.line)), NVIM_TIMEOUT_MS)
262
+ if (opened?.exitCode === 0 && opened.stdout.trim() === '1') return tell($, `opened ${baseName(found.real)} in Neovim`)
263
+ }
264
+ }
265
+ const argv = editorArgv(editor, found.real, target.line)
266
+ if (isTerminalEditor(editor)) {
267
+ if (hasSupacode(env)) {
268
+ const tab = await run($, supacodeTabArgv(baseName(found.real), argv, false), LAUNCH_TIMEOUT_MS)
269
+ if (tab?.exitCode === 0) return
270
+ }
271
+ return tell($, 'no running Neovim for this project and no Supacode to open a tab in')
272
+ }
273
+ const launched = await run($, argv, LAUNCH_TIMEOUT_MS)
274
+ if (launched?.exitCode !== 0) tell($, `${editor[0]} did not start`)
275
+ }
276
+
277
+ const detected = createBoundedCache<Target[]>()
278
+
279
+ /** Shape only: no file system at render. The press runs every check. */
280
+ const replyTargets = (requestId: string, text: string): Target[] => {
281
+ const key = `${requestId}\u0000${text.length}`
282
+ const cached = detected.get(key)
283
+ if (cached !== undefined) return cached
284
+ const targets = detectPaths(text)
285
+ detected.set(key, targets)
286
+ return targets
287
+ }
288
+
289
+ export const register: Register = on => {
290
+ on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
291
+ const row = await next(e)
292
+ const target = toolTarget(e.props.tool, e.props.input)
293
+ if (target === undefined || isSecretName(target.path)) return row
294
+ const { Box, Text, Button } = $.ui.resolve(e)
295
+ return (
296
+ <Box flexDirection="column">
297
+ {row}
298
+ <Box flexDirection="row">
299
+ <Text dimColor> ↳ </Text>
300
+ <Button key={`pv:${e.requestId}`} plain dimColor onPress={press => void previewFile($, target, press.surface)}>
301
+ {baseName(target.path)}
302
+ </Button>
303
+ <Text dimColor> · </Text>
304
+ <Button key={`op:${e.requestId}`} plain dimColor onPress={() => void openFile($, target)}>
305
+ open
306
+ </Button>
307
+ </Box>
308
+ </Box>
309
+ )
310
+ })
311
+
312
+ on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
313
+ const row = await next(e)
314
+ const targets = replyTargets(e.requestId, e.props.text)
315
+ if (targets.length === 0) return row
316
+ const { Box, Text, Button } = $.ui.resolve(e)
317
+ return (
318
+ <Box flexDirection="column">
319
+ {row}
320
+ {targets.map((target, index) => (
321
+ <Box key={`row:${e.requestId}:${index}`} flexDirection="row">
322
+ <Text dimColor> ↳ </Text>
323
+ <Button key={`pv:${e.requestId}:${index}`} plain dimColor onPress={press => void previewFile($, target, press.surface)}>
324
+ {target.line > 0 ? `${target.path}:${target.line}` : target.path}
325
+ </Button>
326
+ <Text dimColor> · </Text>
327
+ <Button key={`op:${e.requestId}:${index}`} plain dimColor onPress={() => void openFile($, target)}>
328
+ open
329
+ </Button>
330
+ </Box>
331
+ ))}
332
+ </Box>
333
+ )
334
+ })
335
+
336
+ on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
337
+ const { Box, Text, Button } = $.ui.resolve(e)
338
+ const shown = await read($, view)
339
+ const header = (
340
+ <Box flexDirection="row">
341
+ <Text bold wrap="truncate-end">{shown.title || 'Preview'} </Text>
342
+ <Button key="close" plain dimColor onPress={() => void $.ui.close({ id: PANE })}>
343
+ close
344
+ </Button>
345
+ </Box>
346
+ )
347
+ if (shown.image !== '' && e.surface === 'terminal') {
348
+ const { Image } = $.ui.resolve(e)
349
+ const columns = Math.max(1, Math.min(255, e.props.bodyColumns))
350
+ const rows = Math.max(1, Math.min(255, e.props.scroll.bodyRows - 3))
351
+ return (
352
+ <Box flexDirection="column">
353
+ {header}
354
+ <Text dimColor wrap="truncate-end">{shown.note}</Text>
355
+ <Image key="picture" source={{ file: shown.image, format: 'png', generation: shown.generation }} columns={columns} rows={rows} alt={shown.title || ' '} />
356
+ </Box>
357
+ )
358
+ }
359
+ return (
360
+ <Box flexDirection="column">
361
+ {header}
362
+ <Text dimColor wrap="truncate-end">{shown.note}</Text>
363
+ {shown.lines.map(line => (
364
+ <Text wrap="truncate-end">{line === '' ? ' ' : line}</Text>
365
+ ))}
366
+ </Box>
367
+ )
368
+ })
369
+ }
@@ -0,0 +1,17 @@
1
+ /** What the preview pane draws: plain lines of a text file, or a cached PNG of an image or a video frame. */
2
+ export type PreviewView = {
3
+ id: number
4
+ title: string
5
+ note: string
6
+ lines: string[]
7
+ image: string
8
+ generation: number
9
+ }
10
+
11
+ declare module 'claude-code' {
12
+ interface PluginState {
13
+ 'project-brain-file-preview': {
14
+ view: Shaped<PreviewView>
15
+ }
16
+ }
17
+ }
@@ -0,0 +1,19 @@
1
+ -- The colour theme: tokyonight (maintained, covers every plugin LazyVim ships) re-pointed at the project-brain palette.
2
+ -- To change theme, change the palette; this spec and highlights.lua stay as they are.
3
+ return {
4
+ {
5
+ "folke/tokyonight.nvim",
6
+ opts = {
7
+ style = "night",
8
+ transparent = true,
9
+ styles = { sidebars = "transparent", floats = "dark" },
10
+ on_colors = function(colors)
11
+ require("project-brain.highlights").colors(colors, require("project-brain.palette"))
12
+ end,
13
+ on_highlights = function(highlights, colors)
14
+ require("project-brain.highlights").groups(highlights, colors, require("project-brain.palette"))
15
+ end,
16
+ },
17
+ },
18
+ { "LazyVim/LazyVim", opts = { colorscheme = "tokyonight-night" } },
19
+ }
@@ -0,0 +1,186 @@
1
+ -- Turns a theme palette (lua/project-brain/palette.lua) into highlight groups for tokyonight.
2
+ -- The palette changes per theme; this file does not: every role below is a palette colour or a blend of two.
3
+ local M = {}
4
+
5
+ -- Row tint of an added or deleted line, and the stronger tint of the words that changed inside it.
6
+ M.LINE_TINT = 0.12
7
+ M.WORD_TINT = 0.22
8
+ -- Green is the brightest accent, so its word tint stays lower to keep pink and purple code at 4.5:1 on it.
9
+ M.ADD_WORD_TINT = 0.20
10
+ -- A changed line stays below an added or deleted one: its changed words carry the meaning.
11
+ M.CHANGE_TINT = 0.06
12
+
13
+ local function channels(hex)
14
+ hex = hex:gsub("^#", "")
15
+ return tonumber(hex:sub(1, 2), 16), tonumber(hex:sub(3, 4), 16), tonumber(hex:sub(5, 6), 16)
16
+ end
17
+
18
+ --- `from` moved `share` (0..1) of the way towards `into`.
19
+ function M.blend(from, into, share)
20
+ local r1, g1, b1 = channels(from)
21
+ local r2, g2, b2 = channels(into)
22
+ local function mix(a, b)
23
+ return math.floor(a + (b - a) * share + 0.5)
24
+ end
25
+ return string.format("#%02x%02x%02x", mix(r1, r2), mix(g1, g2), mix(b1, b2))
26
+ end
27
+
28
+ --- Tokyonight's colour table, re-pointed at the palette. Runs as `on_colors`.
29
+ function M.colors(c, p)
30
+ local a = p.accents
31
+ c.bg, c.bg_dark, c.bg_sidebar, c.bg_statusline = p.background, p.background, p.background, p.background
32
+ c.bg_float = M.blend(p.background, p.selection, 0.5)
33
+ c.bg_highlight = M.blend(p.background, p.selection, 0.45)
34
+ c.bg_visual = p.selection
35
+ c.bg_popup = c.bg_float
36
+ c.fg, c.fg_dark, c.fg_float = p.foreground, M.blend(p.foreground, p.background, 0.15), p.foreground
37
+ c.fg_gutter = p.comment
38
+ c.comment = p.comment
39
+ c.dark3, c.dark5 = p.comment, M.blend(p.comment, p.foreground, 0.35)
40
+ c.terminal_black = p.ansi[1]
41
+ c.red, c.red1 = a.red, a.red
42
+ c.orange, c.yellow = a.orange, a.yellow
43
+ c.green, c.green1, c.green2 = a.green, a.green, a.green
44
+ c.cyan, c.teal, c.blue1, c.blue2, c.blue5, c.blue6 = a.cyan, a.cyan, a.cyan, a.cyan, a.cyan, a.cyan
45
+ c.blue, c.blue0, c.purple = a.purple, a.purple, a.purple
46
+ c.magenta, c.magenta2 = a.pink, a.pink
47
+ c.border, c.border_highlight = p.comment, a.purple
48
+ c.error, c.warning, c.info, c.hint = a.red, a.orange, a.cyan, a.purple
49
+ c.git = { add = a.green, change = a.orange, delete = a.red, ignore = p.comment }
50
+ c.gitSigns = { add = a.green, change = a.orange, delete = a.red }
51
+ c.diff = {
52
+ add = M.blend(p.background, a.green, M.LINE_TINT),
53
+ delete = M.blend(p.background, a.red, M.LINE_TINT),
54
+ change = M.blend(p.background, a.cyan, M.CHANGE_TINT),
55
+ text = M.blend(p.background, a.orange, M.WORD_TINT),
56
+ }
57
+ end
58
+
59
+ --- How code is painted, by role; the same table as `syntax` in src/themes/roles.ts.
60
+ function M.syntax(p)
61
+ local a = p.accents
62
+ return {
63
+ keyword = a.pink,
64
+ operator = a.pink,
65
+ ["function"] = a.green,
66
+ builtin = a.cyan,
67
+ type = a.cyan,
68
+ string = a.yellow,
69
+ escape = a.pink,
70
+ regexp = a.orange,
71
+ number = a.purple,
72
+ constant = a.purple,
73
+ parameter = a.orange,
74
+ variable = p.foreground,
75
+ comment = p.comment,
76
+ tag = a.pink,
77
+ tagDelimiter = p.comment,
78
+ attribute = a.green,
79
+ heading = a.purple,
80
+ link = a.cyan,
81
+ raw = a.green,
82
+ }
83
+ end
84
+
85
+ --- Highlight groups that follow how the theme paints code (pink keywords, green functions, yellow strings...) and
86
+ --- make diffs readable. Runs as `on_highlights`, after tokyonight's own groups, so it only needs to name what differs.
87
+ function M.groups(hl, c, p)
88
+ local a = p.accents
89
+ local bg, fg = p.background, p.foreground
90
+ local function tint(accent, share)
91
+ return M.blend(bg, accent, share)
92
+ end
93
+ local function set(name, spec)
94
+ hl[name] = spec
95
+ end
96
+
97
+ -- Diff: green is added, red is removed, a changed line is only faintly tinted so the changed words stand out.
98
+ set("DiffAdd", { bg = tint(a.green, M.LINE_TINT) })
99
+ set("DiffChange", { bg = tint(a.cyan, M.CHANGE_TINT) })
100
+ set("DiffDelete", { bg = tint(a.red, M.LINE_TINT), fg = M.blend(a.red, bg, 0.5) })
101
+ set("DiffText", { bg = tint(a.orange, M.WORD_TINT), bold = true })
102
+ set("DiffTextAdd", { bg = tint(a.green, M.ADD_WORD_TINT), bold = true })
103
+ set("diffAdded", { fg = a.green })
104
+ set("diffRemoved", { fg = a.red })
105
+ set("diffChanged", { fg = a.orange })
106
+ set("diffFile", { fg = a.purple, bold = true })
107
+ set("diffLine", { fg = a.cyan })
108
+ set("GitSignsAdd", { fg = a.green })
109
+ set("GitSignsChange", { fg = a.orange })
110
+ set("GitSignsDelete", { fg = a.red })
111
+ set("GitSignsAddInline", { bg = tint(a.green, M.ADD_WORD_TINT) })
112
+ set("GitSignsChangeInline", { bg = tint(a.orange, M.WORD_TINT) })
113
+ set("GitSignsDeleteInline", { bg = tint(a.red, M.WORD_TINT) })
114
+ set("GitSignsAddLn", { bg = tint(a.green, M.LINE_TINT) })
115
+ set("GitSignsChangeLn", { bg = tint(a.orange, 0.1) })
116
+ set("GitSignsDeleteLn", { bg = tint(a.red, M.LINE_TINT) })
117
+ set("GitSignsAddPreview", { bg = tint(a.green, M.LINE_TINT) })
118
+ set("GitSignsDeletePreview", { bg = tint(a.red, M.LINE_TINT) })
119
+
120
+ -- Syntax.
121
+ local function many(names, spec)
122
+ for _, name in ipairs(names) do
123
+ set(name, spec)
124
+ end
125
+ end
126
+ local sx = M.syntax(p)
127
+ set("Comment", { fg = sx.comment, italic = true })
128
+ set("@comment", { fg = sx.comment, italic = true })
129
+ many({ "Keyword", "Statement", "Conditional", "Repeat", "Exception", "Operator", "Include",
130
+ "@keyword", "@keyword.return", "@keyword.conditional", "@keyword.repeat", "@keyword.import",
131
+ "@keyword.exception", "@keyword.operator", "@keyword.modifier", "@keyword.coroutine", "@operator",
132
+ "@lsp.type.keyword", "@lsp.type.operator" }, { fg = sx.keyword })
133
+ many({ "Function", "@function", "@function.call", "@function.method", "@function.method.call",
134
+ "@lsp.type.function", "@lsp.type.method" }, { fg = sx["function"] })
135
+ many({ "@keyword.function" }, { fg = sx.keyword })
136
+ many({ "@function.builtin", "@variable.builtin" }, { fg = sx.builtin, italic = true })
137
+ many({ "Type", "Structure", "@type", "@constructor", "@lsp.type.class", "@lsp.type.interface",
138
+ "@lsp.type.enum", "@lsp.type.struct", "@lsp.type.type", "@lsp.type.typeParameter", "@module", "@namespace" },
139
+ { fg = sx.type })
140
+ many({ "@type.builtin" }, { fg = sx.builtin, italic = true })
141
+ many({ "String", "Character", "@string", "@character", "@lsp.type.string" }, { fg = sx.string })
142
+ many({ "@string.escape", "@string.special" }, { fg = sx.escape })
143
+ many({ "@string.regexp" }, { fg = sx.regexp })
144
+ many({ "Number", "Float", "Boolean", "Constant", "@number", "@number.float", "@boolean", "@constant",
145
+ "@constant.builtin", "@lsp.type.enumMember" }, { fg = sx.number })
146
+ many({ "@variable", "@variable.member", "@property", "@lsp.type.variable", "@lsp.type.property",
147
+ "@punctuation.delimiter", "@punctuation.bracket" }, { fg = sx.variable })
148
+ many({ "@variable.parameter", "@lsp.type.parameter" }, { fg = sx.parameter, italic = true })
149
+ many({ "@tag", "@tag.builtin" }, { fg = sx.tag })
150
+ many({ "@tag.attribute", "@attribute", "@lsp.type.decorator" }, { fg = sx.attribute })
151
+ many({ "@tag.delimiter" }, { fg = sx.tagDelimiter })
152
+ many({ "@markup.heading", "@markup.heading.1", "@markup.heading.2", "@markup.heading.3", "@markup.heading.4",
153
+ "@markup.heading.5", "@markup.heading.6" }, { fg = sx.heading, bold = true })
154
+ set("@markup.strong", { bold = true })
155
+ set("@markup.italic", { italic = true })
156
+ many({ "@markup.link", "@markup.link.url" }, { fg = sx.link, underline = true })
157
+ set("@markup.raw", { fg = sx.raw })
158
+
159
+ -- Diagnostics.
160
+ set("DiagnosticError", { fg = a.red })
161
+ set("DiagnosticWarn", { fg = a.orange })
162
+ set("DiagnosticInfo", { fg = a.cyan })
163
+ set("DiagnosticHint", { fg = a.purple })
164
+ set("DiagnosticUnderlineError", { undercurl = true, sp = a.red })
165
+ set("DiagnosticUnderlineWarn", { undercurl = true, sp = a.orange })
166
+ set("DiagnosticUnderlineInfo", { undercurl = true, sp = a.cyan })
167
+ set("DiagnosticUnderlineHint", { undercurl = true, sp = a.purple })
168
+
169
+ -- Editor chrome.
170
+ set("CursorLine", { bg = tint(p.selection, 0.45) })
171
+ set("CursorLineNr", { fg = a.orange, bold = true })
172
+ set("LineNr", { fg = p.comment })
173
+ set("Visual", { bg = p.selection })
174
+ set("Search", { bg = tint(a.orange, 0.35), fg = fg })
175
+ set("IncSearch", { bg = a.orange, fg = bg })
176
+ set("MatchParen", { fg = a.pink, bold = true })
177
+ set("WinSeparator", { fg = M.blend(p.comment, bg, 0.4) })
178
+ set("NonText", { fg = M.blend(p.comment, bg, 0.5) })
179
+ set("FloatBorder", { fg = p.comment, bg = c.bg_float })
180
+ set("NormalFloat", { fg = fg, bg = c.bg_float })
181
+ set("Pmenu", { fg = fg, bg = c.bg_float })
182
+ set("PmenuSel", { bg = p.selection })
183
+ set("PmenuBorder", { fg = p.comment, bg = c.bg_float })
184
+ end
185
+
186
+ return M
@@ -17,7 +17,7 @@ metadata:
17
17
 
18
18
  ## Activation Contract
19
19
 
20
- Use when a live or local UI must be judged on how it looks and feels, and the findings should be fixed. Report-only: use `brain-qa-only`. Whole-product MVP verdict: `mvp-ui-review`. Building new UI: `impeccable`.
20
+ Use when a live or local UI must be judged on how it looks and feels, and the findings should be fixed. Report-only: use `brain-qa-only`. Task flows, navigation and error recovery: `brain-ux-review`. Whole-product MVP verdict: `mvp-ui-review`. Building new UI: `impeccable`.
21
21
 
22
22
  ## Hard Rules
23
23
 
@@ -17,7 +17,7 @@ metadata:
17
17
 
18
18
  ## Activation Contract
19
19
 
20
- Use when the ask is to find and document bugs, not to fix them. Design judgment: `brain-design-review`. Every screen of a product and an MVP verdict: `mvp-ui-review`. Recording a demo: `brain-record`.
20
+ Use when the ask is to find and document bugs, not to fix them. Design judgment: `brain-design-review`. UX of whole tasks and flows: `brain-ux-review`. Every screen of a product and an MVP verdict: `mvp-ui-review`. Recording a demo: `brain-record`.
21
21
 
22
22
  ## Hard Rules
23
23
 
@@ -0,0 +1,65 @@
1
+ ---
2
+ name: brain-ux-review
3
+ description: "Trigger: UX review, mejorar la UX, usability audit, rediseña este flujo, revisa esta pantalla, UX research, redesign. Walks real tasks, diagnoses with evidence, redesigns and plans validation."
4
+ license: Apache-2.0
5
+ metadata:
6
+ author: jcsoftdev
7
+ version: "1.0"
8
+ generator: project-brain
9
+ ---
10
+
11
+ <!--
12
+ `generator: project-brain` is an ownership marker, not decoration.
13
+ `project-brain setup` overwrites this directory only when it finds that line;
14
+ without it, setup treats the directory as hand-written and leaves it alone.
15
+ Strip it and you pin this copy forever — no upgrade will ever reach it.
16
+ -->
17
+
18
+ ## Activation Contract
19
+
20
+ Use when the ask is to improve how a product works for its users: navigation, content layout, interaction, error recovery, accessibility, judged by walking real tasks. Visual polish only: `brain-design-review`. Bugs only: `brain-qa-only`. MVP go/no-go across every screen: `mvp-ui-review`.
21
+
22
+ ## Hard Rules
23
+
24
+ - Walk tasks, not screens. Each task is a user goal written without click paths, walked from a plausible entry point to an observable result, including the wrong-choice and failure paths.
25
+ - Every finding names screen, step and state, what the person was trying to do, the observed or expected consequence, and whether you reproduced it.
26
+ - Label every major decision with its backing: product observation, product data, external research, WCAG criterion, heuristic, or hypothesis. Cite the original source and say how its context matches ours.
27
+ - Never invent data, percentages or test results. An uncertain effect is a testable hypothesis.
28
+ - Missing context: state assumptions and continue with what you can inspect. Screenshots only: say which behaviors need a prototype or app access.
29
+ - Browser ladder: `chrome-devtools` first; `claude-in-chrome` only for a session the user said to reuse. Non-local targets are read-only; never type passwords. Close the tabs you opened.
30
+ - Reuse the product's design system: `DESIGN.md`, `:root` tokens, the component kit. A new component is proposed only for a pattern that repeats.
31
+
32
+ ## Decision Gates
33
+
34
+ | Situation | Action |
35
+ |-----------|--------|
36
+ | Scope: whole app | Map roles and areas, pick 3-5 tasks product-wide, one subagent per task with `references/delegation.md`; merge and dedupe |
37
+ | Scope: one feature | 3-5 tasks inside it plus its entry and exit points; delegate only when tasks share no state |
38
+ | Scope: one screen | Inline; the tasks that pass through it, every state of it |
39
+ | Mode: audit | Deliverables 1, 2, 4, 5 |
40
+ | Mode: redesign | All five deliverables, with before/after wireframes |
41
+ | Mode: implement | Redesign, then apply on a branch (clean tree, `brain-commit`, `brain-style`), re-walk each task from its usual entry point |
42
+ | Web and mobile both relevant | Walk both; mobile via `emulate` `375x812x3,mobile,touch` |
43
+ | Login you cannot do | Public flows first; ask the user to sign in |
44
+ | Code cause needed | `search_context` / `find_symbol`, not grep |
45
+
46
+ ## Execution Steps
47
+
48
+ 1. Fix the context: product and access, users and roles, priority tasks, product goal, design system, scope and mode. Write assumptions for anything missing.
49
+ 2. Pick 3-5 tasks by frequency, importance and cost of failure (`references/protocol.md`). Write each with user, entry point and success criterion.
50
+ 3. Walk each task on desktop and mobile when relevant: screens, decisions, state changes, alternate routes, completion signals; screenshot each step.
51
+ 4. Diagnose each flow on the four levels in `references/protocol.md`: information architecture, interaction, visual composition, accessibility and integration.
52
+ 5. Back the major findings with the sources in `references/protocol.md`; mark the rest as heuristic or hypothesis.
53
+ 6. Redesign the priority flows per `references/report.md`: current versus proposed journey, per-screen order, primary action, grouping, mobile, states, components and tokens.
54
+ 7. Write the validation plan: scenarios that hide the route, success criteria, metrics per flow, and how to get a baseline first.
55
+ 8. In implement mode, apply, re-walk, and record before/after evidence.
56
+
57
+ ## Output Contract
58
+
59
+ Report in `.ux-review/<date>/report.md` (git-excluded, never tracked), in the order of `references/report.md`: task map, findings table, proposed flows, validation plan, verification status. Show key screenshots inline with `Read`. State what was checked in the app, what needs user testing and what data is missing.
60
+
61
+ ## References
62
+
63
+ - `references/protocol.md` — task selection, four-level diagnosis, evidence types, sources.
64
+ - `references/report.md` — deliverables, findings table, redesign spec, validation plan, test scenarios.
65
+ - `references/delegation.md` — splitting by scope, subagent brief, merge rules.