@estiva-app/ui 0.28.0 → 0.29.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.
Files changed (44) hide show
  1. package/dist/gates/app-checks.d.ts.map +1 -1
  2. package/dist/gates/{chunk-XE6HC5MJ.js → chunk-JZE7TIQY.js} +9 -2
  3. package/dist/gates/chunk-JZE7TIQY.js.map +7 -0
  4. package/dist/gates/{chunk-I7CJLUPM.js → chunk-S75XIY3Z.js} +56 -6
  5. package/dist/gates/chunk-S75XIY3Z.js.map +7 -0
  6. package/dist/gates/chunk-YKZXKVR2.js +39 -0
  7. package/dist/gates/chunk-YKZXKVR2.js.map +7 -0
  8. package/dist/gates/cli.js +2 -1
  9. package/dist/gates/cli.js.map +1 -1
  10. package/dist/gates/create-app.d.ts.map +1 -1
  11. package/dist/gates/create-app.js +2 -1
  12. package/dist/gates/create-app.js.map +1 -1
  13. package/dist/gates/hook.d.ts +7 -1
  14. package/dist/gates/hook.d.ts.map +1 -1
  15. package/dist/gates/index.js +10 -3
  16. package/dist/gates/index.js.map +2 -2
  17. package/dist/registry/{chunk-6OH3TWGF.js → chunk-KMZIMB3G.js} +5 -2
  18. package/dist/registry/{chunk-6OH3TWGF.js.map → chunk-KMZIMB3G.js.map} +2 -2
  19. package/dist/registry/cli.js +187 -25
  20. package/dist/registry/cli.js.map +4 -4
  21. package/dist/registry/find.d.ts +5 -0
  22. package/dist/registry/find.d.ts.map +1 -1
  23. package/dist/registry/index.js +1 -1
  24. package/dist/registry/siblings.d.ts +21 -0
  25. package/dist/registry/siblings.d.ts.map +1 -0
  26. package/dist/registry/skill.d.ts +20 -0
  27. package/dist/registry/skill.d.ts.map +1 -0
  28. package/package.json +4 -2
  29. package/registry.json +1 -1
  30. package/skill/estiva-ui.md +126 -0
  31. package/src/gates/app-checks.ts +7 -1
  32. package/src/gates/create-app.test.ts +5 -1
  33. package/src/gates/create-app.ts +5 -0
  34. package/src/gates/gates.test.ts +25 -0
  35. package/src/gates/hook.ts +69 -5
  36. package/src/registry/app.test.ts +58 -1
  37. package/src/registry/cli.ts +60 -8
  38. package/src/registry/find.ts +10 -1
  39. package/src/registry/siblings.test.ts +85 -0
  40. package/src/registry/siblings.ts +96 -0
  41. package/src/registry/skill.test.ts +96 -0
  42. package/src/registry/skill.ts +117 -0
  43. package/dist/gates/chunk-I7CJLUPM.js.map +0 -7
  44. package/dist/gates/chunk-XE6HC5MJ.js.map +0 -7
@@ -0,0 +1,126 @@
1
+ # Search before you build
2
+
3
+ Every screen here is built from parts: the package `@estiva-app/ui`, and each
4
+ app's own. Every reusable part has a Storybook page that says when to use it
5
+ and when not to. Most of what gets asked for already exists somewhere.
6
+
7
+ ## When this applies
8
+
9
+ - Building or changing a screen, panel, list, row, header, dialog or menu.
10
+ - Adding a component, or a new file that draws one.
11
+ - Changing how something looks: its size, spacing, colour or type.
12
+
13
+ ## Steps, in order
14
+
15
+ 1. **Search before creating anything.** Run
16
+ `npm run ui:find <what it does, in plain words>` in the repository you are
17
+ in. Do it yourself; never ask the person to. With nothing else typed it
18
+ searches the package and every app beside it, and prints a Storybook link
19
+ for each match. Show the person what it found, with the links.
20
+ - From a folder that holds several repositories, run it inside any one of
21
+ them (`npm --prefix <repo> run ui:find <words>`): each searches them all.
22
+ - Search again in other words before deciding nothing fits: "list column",
23
+ then "scrolling list"; "panel header", then "title row".
24
+ 2. **If something fits, read its page before using it:** the link, or the
25
+ `.mdx` beside its file. Read its opening line, **When** and **When not**.
26
+ *When not* names the part to use instead.
27
+ 3. **If nothing fits, say so and ask.** Do not invent a component. Do not copy
28
+ one from another app either: say which app has it, and ask whether it
29
+ should move into the package.
30
+ 4. **Never hand-roll what the package owns.** Its parts own their behaviour:
31
+ keys, focus, floating, closing, scrolling, truncation. The editor gate
32
+ refuses a raw element, a rebuilt behaviour or a restyled part, and its error
33
+ names the part to use.
34
+ 5. **An exception** carries `// @estiva-escape: <reason>` on the line above
35
+ it. Never `eslint-disable`.
36
+
37
+ ## Gotchas
38
+
39
+ The mistakes made here more than once, from the record (UIG-20 counted 542
40
+ recorded defects; these 24 cover the 111 that are screen work). Each says what
41
+ to do instead. Apps differ in frame and theme: never carry one app's layout,
42
+ sizes or colours into another; take them from tokens.
43
+
44
+ **Layout**
45
+
46
+ 1. **A header row drawn by hand** at the top of a column → `ContainerHeader`.
47
+ Its actions are `IconButton`s with tooltips. A whole list column is
48
+ `ListColumn`, which draws the bar; a field that adds to the list goes in its
49
+ `above`.
50
+ 2. **A list with no scroll container**, cut off at the fold (no lint sees a box
51
+ that was never built) → a list column is `ListColumn`, which scrolls its
52
+ rows; anything else that grows goes in a `ScrollArea`. Check with more rows
53
+ than fit.
54
+ 3. **`EmptyState` at the wrong level** → `scope="page"` only when the whole
55
+ page is empty, `scope="section"` for one part of it, placed inside the box
56
+ its rows live in. Never wrap it in a box of your own that places it.
57
+ 4. **`EditableText` rendering too large**: it has no size of its own and takes
58
+ the size around it → put the text size on your own element around it. The
59
+ same holds for `Person`, `Link`, `Card` and `SectionLabel`.
60
+ 5. **Flex rows that move things**: loose children of an `items-start` row float
61
+ at different heights; a scrolling flex column squashes rows → group them in
62
+ one `items-center` row; give your own rows in a scrolling column `shrink-0`.
63
+ 6. **A group heading drawn by hand** (a row holding a `SectionLabel`) →
64
+ `SectionHeader` (`hover="none"` when nothing acts on it); a group that folds
65
+ is `CollapsibleSection`.
66
+ 7. **A line drawn by hand** (`border-t`, `<hr>`, a gap) → `Divider`; between a
67
+ menu's groups, `MenuSeparator`, which brings its own room.
68
+
69
+ **Parts and props**
70
+
71
+ 8. **The browser's tooltip** (`title=`), or an icon button with none →
72
+ `WithTooltip` (`inline` inside text) or `IconButton`'s `tooltip`.
73
+ 9. **A row of icon buttons laid out by hand** → `Toolbar` with `ToolbarButton`
74
+ and `ToolbarLink` (they throw outside one). A row inside a `Popover` is a
75
+ `Toolbar` with `surface={false}`.
76
+ 10. **Fields sent by a hand-written Enter handler**, with no form → `Form`,
77
+ which owns the keys, `busy` and focus. Clear a field's `error` when it
78
+ changes, or the form will not send.
79
+ 11. **A link to an in-app page as a bare `href`**: every click reloads the app
80
+ → go through the app's router, as `NavItem` does.
81
+ 12. **Wrong loading and failure states**: an `EmptyState` while data is still
82
+ coming, a hand-made pulsing box → a skeleton shaped like what is coming
83
+ (`SkeletonList`, `SkeletonRow`, `SkeletonBar`). Say a failure in
84
+ words, never as "empty" and never in red; a failure toast or banner has
85
+ the `error` tone.
86
+ 13. **A floating panel mounted only while open** (`{open && <Popover…>}`), or
87
+ capped with a class → keep it mounted and drive `open`; cap a long list with
88
+ `Popover`'s `maxHeight`; never open a panel around an empty list.
89
+ 14. **Deleting a part without checking what else it carried** → read everything
90
+ the container holds first, and remove its imports, escapes and stories with it.
91
+
92
+ **Stories and usage pages**
93
+
94
+ 15. **A story that shows one branch**: something drawn behind `{prop && …}` that
95
+ no story passes, or data with no fixture → a story for every branch; one
96
+ fixture holding what the backend really sends. `estiva-ui check` refuses
97
+ the first.
98
+ 16. **A screen with no story** is where mistakes hide: every gate was green on
99
+ a page with eight → look at the running screen, or give it a story with
100
+ more rows than fit, an empty state and a loading state.
101
+ 17. **A story under a new heading, or named after its file** → use a heading
102
+ the Storybook already has, name the entry after its part, give each meta its
103
+ `component` (or the part's page a **Seen in** line).
104
+ 18. **`{…}` in a usage page's prose** (MDX reads it as code and the page will
105
+ not compile), or a description over two lines → backticks around braces; a
106
+ part's description is one line.
107
+
108
+ **Working in these repositories**
109
+
110
+ 19. **An escape with a false reason** ("no part does this" has been wrong
111
+ twice) → search for the thing first. Write the escape on the line above
112
+ the statement, never inside `eslint-disable`.
113
+ 20. **Classes the lint cannot see**: in a const not named `…_CLASSES` or
114
+ `…Styles`, or in an array that is `.join()`ed → keep classes in
115
+ `className` or `cn()`, or in a map with one of those names.
116
+ 21. **The editor gate and this skill need a session started at the repository's
117
+ top folder.** Started elsewhere, run the repository's `lint:rules` yourself
118
+ before committing.
119
+ 22. **`npm install` on Windows prunes Linux-only entries from the lockfile**, and
120
+ CI dies at `npm ci` → never commit a lockfile Windows rewrote; restore it and
121
+ bump only the package's own entry. Stop every dev server before `npm ci`.
122
+ 23. **Storybook shows old code after a package bump** → delete
123
+ `node_modules/.cache/storybook` and restart.
124
+ 24. **A local checkout lags `origin/main`, and a conflicting PR shows no CI** →
125
+ `git fetch` and read `origin/main`; when checks are missing, look for a
126
+ conflict first.
@@ -199,8 +199,14 @@ export function appChecks(h: GateHelpers, { app = '.', page, chain = { ref: 'UIG
199
199
  { what: "CI's job gate runs it", run: () => h.ciJob('gate', 'registry:check') },
200
200
  { what: 'the app keeps no copy of it in its own gates-checks.mjs', run: () => h.exists(at('scripts/gates-checks.mjs')) ? h.lacks(at('scripts/gates-checks.mjs'), '"When not"', 'the app checks no page sections itself') : h.PASS('the app has no gates-checks.mjs') },
201
201
  ]),
202
+ // The Claude skill (UIG-20): its text is the installed package's, read in by a
203
+ // loader `estiva-ui skill` writes; the app commits the loader and the settings.
202
204
  ticket('UIG-20', [
203
- { what: 'a committed skill runs ui:find', run: () => (h.listFiles('.claude/skills', (n) => n === 'SKILL.md').some((f) => h.read(f).includes('ui:find')) ? h.PASS('a skill runs ui:find') : h.FAIL('no skill in .claude/skills runs ui:find')) },
205
+ { what: "the skill's loader reads the installed package's text", run: () => h.contains('.claude/skills/estiva-ui/SKILL.md', `!\`cat "\${CLAUDE_PROJECT_DIR}/${at('node_modules/@estiva-app/ui/skill/estiva-ui.md')}"\``, 'the loader reads the package’s skill') },
206
+ { what: 'the search runs without a prompt', run: () => h.contains('.claude/settings.json', 'Bash(npm run ui:find *)', '.claude/settings.json allows npm run ui:find') },
207
+ { what: 'ui:find searches every app beside this one: it names none', run: () => h.lacks(at('package.json'), /"ui:find":[^\n]*--also/, 'ui:find names no neighbour, so it finds them all') },
208
+ ...(WEB ? [{ what: 'ui:find runs from the top folder too', run: () => h.contains('package.json', /"ui:find":/, 'the top folder has ui:find') }] : []),
209
+ { what: "CI's job gate refuses a loader that differs", run: () => (h.exists(at('node_modules/@estiva-app/ui/dist/registry/cli.js')) && /claude skill:/.test(h.read(at('node_modules/@estiva-app/ui/dist/registry/cli.js'))) ? h.ciJob('gate', 'registry:check') : h.FAIL('the installed package does not check the loader: take a version that does')) },
204
210
  ]),
205
211
  ticket('UIG-21', [
206
212
  { what: 'path-scoped instructions exist', run: () => (h.listFiles('.claude/rules', (n) => n.endsWith('.md')).some((f) => /^paths:/m.test(h.read(f))) ? h.PASS('.claude/rules has paths: instructions') : h.FAIL('no .claude/rules file with paths:')) },
@@ -30,7 +30,7 @@ describe('create-estiva-app', () => {
30
30
  it('makes the frame, the checks and the gates, each as a file that imports the package', () => {
31
31
  expect(Object.keys(files).sort()).toEqual(
32
32
  [
33
- '.claude/settings.json', '.env.example', '.gates-count.json', '.github/workflows/deploy.yml', '.gitignore', '.storybook/main.ts', '.storybook/preview.tsx',
33
+ '.claude/settings.json', '.claude/skills/estiva-ui/SKILL.md', '.env.example', '.gates-count.json', '.github/workflows/deploy.yml', '.gitignore', '.storybook/main.ts', '.storybook/preview.tsx',
34
34
  'CLAUDE.md', 'README.md', 'docs/GATES-DEBT.md', 'eslint.config.js', 'eslint.gates.config.js', 'eslint.tokens.config.js', 'index.html', 'package.json',
35
35
  'postcss.config.js', 'scripts/gates-checks.mjs', 'src/App.test.tsx', 'src/App.tsx', 'src/auth/AuthShell.tsx', 'src/auth/boot.ts', 'src/auth/estivaId.ts',
36
36
  'src/config.ts', 'src/index.css', 'src/main.tsx', 'src/pages/HomePage.stories.tsx', 'src/pages/HomePage.tsx',
@@ -41,6 +41,10 @@ describe('create-estiva-app', () => {
41
41
  expect(files['eslint.gates.config.js']).toContain("from '@estiva-app/ui/gates'")
42
42
  expect(files['scripts/gates-checks.mjs']).toContain("appChecks(h, { page: 'src/pages/HomePage.tsx' })")
43
43
  expect(JSON.parse(files['.claude/settings.json']).hooks.PreToolUse[0].hooks[0].command).toBe('node "$CLAUDE_PROJECT_DIR/node_modules/@estiva-app/ui/dist/gates/cli.js" hook')
44
+ // The skill loads from the package's one copy: the app holds its trigger and the line that reads it (UIG-20).
45
+ expect(JSON.parse(files['.claude/settings.json']).permissions.allow).toContain('Bash(npm run ui:find *)')
46
+ expect(files['.claude/skills/estiva-ui/SKILL.md']).toContain('!`cat "${CLAUDE_PROJECT_DIR}/node_modules/@estiva-app/ui/skill/estiva-ui.md"`')
47
+ expect(files['.claude/skills/estiva-ui/SKILL.md']).not.toContain('## Steps')
44
48
  })
45
49
 
46
50
  it('uses the sidebar frame and one theme, set on <html>', () => {
@@ -35,6 +35,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
35
35
  import { dirname, join, resolve } from 'node:path'
36
36
  import { fileURLToPath } from 'node:url'
37
37
  import { APP_RULE_IDS } from '../eslint/index'
38
+ import { loaderText, SEARCH_RULES } from '../registry/skill'
38
39
 
39
40
  interface PackageJson {
40
41
  version: string
@@ -292,8 +293,12 @@ export default gateConfig({ quiet: { 'react-hooks': reactHooks } })
292
293
  hooks: {
293
294
  PreToolUse: [{ matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'node "$CLAUDE_PROJECT_DIR/node_modules/@estiva-app/ui/dist/gates/cli.js" hook' }] }],
294
295
  },
296
+ permissions: { allow: SEARCH_RULES },
295
297
  }),
296
298
 
299
+ // The Claude skill (UIG-20): its trigger, and a line reading the installed package's text in.
300
+ '.claude/skills/estiva-ui/SKILL.md': loaderText(resolve('/app'), resolve('/app/node_modules/@estiva-app/ui')),
301
+
297
302
  'scripts/gates-checks.mjs': `import { appChecks } from '@estiva-app/ui/gates'
298
303
 
299
304
  /**
@@ -178,6 +178,31 @@ describe('runHook', () => {
178
178
  }
179
179
  })
180
180
 
181
+ it('stops a new part once with what already exists, then lets it through (UIG-20)', async () => {
182
+ const seen = mkdtempSync(join(scratch, 'seen-'))
183
+ const input = { ...write('src/PanelHeader.tsx', 'export function PanelHeader() {\n return <div>x</div>\n}\n'), session_id: 'one' }
184
+ const first = await runHook({ root: dir, input, seen })
185
+ expect(first.code).toBe(2)
186
+ expect(first.message).toContain('src/PanelHeader.tsx was not written yet: it adds a new part, PanelHeader.')
187
+ expect(first.message).toContain('What already exists for "panel header"')
188
+ expect(first.message).toContain('ContainerHeader')
189
+ expect((await runHook({ root: dir, input, seen })).code).toBe(0)
190
+ // Another session is asked again.
191
+ expect((await runHook({ root: dir, input: { ...input, session_id: 'two' }, seen })).code).toBe(2)
192
+ // The search reads every app beside this checkout: seconds on a machine that holds them all.
193
+ }, 60_000)
194
+
195
+ it('does not stop a file already there, a story, or a file that draws nothing', async () => {
196
+ const seen = mkdtempSync(join(scratch, 'seen-'))
197
+ for (const input of [
198
+ write('src/Page.tsx', 'export function Page() {\n return <div>y</div>\n}\n'),
199
+ write('src/Panel.stories.tsx', 'export const Default = () => <div>x</div>\n'),
200
+ write('src/format.tsx', 'export function formatDate(date: Date) {\n return date.toISOString()\n}\n'),
201
+ ]) {
202
+ expect((await runHook({ root: dir, input, seen })).code).toBe(0)
203
+ }
204
+ })
205
+
181
206
  it('finds the app in a folder of its own, as Ship keeps it in web/', async () => {
182
207
  const top = join(scratch, 'top')
183
208
  mkdirSync(top, { recursive: true })
package/src/gates/hook.ts CHANGED
@@ -22,13 +22,24 @@
22
22
  * `replace_all` for Edit. An Edit carries no whole file, so the edit is applied
23
23
  * to the file on disk here. Anything it cannot read passes, and the tool itself
24
24
  * reports its own failure.
25
+ *
26
+ * **Search first** (UIG-20). A Write that would create a new file drawing a new
27
+ * part, and that the gate lets through, is stopped once: the hook runs
28
+ * `estiva-ui find` on the part's name and hands the matches back, so a session
29
+ * sees what already exists before it adds another. The same file written again
30
+ * in the same session goes through. The skill asks for the search; this makes
31
+ * sure it happened. A search that cannot run stops nothing.
25
32
  */
26
- import { existsSync, readFileSync } from 'node:fs'
33
+ import { spawnSync } from 'node:child_process'
34
+ import { createHash } from 'node:crypto'
35
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
27
36
  import { createRequire } from 'node:module'
28
- import { isAbsolute, join, relative, resolve, sep } from 'node:path'
29
- import { pathToFileURL } from 'node:url'
37
+ import { tmpdir } from 'node:os'
38
+ import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path'
39
+ import { fileURLToPath, pathToFileURL } from 'node:url'
30
40
  import type { ESLint as ESLintClass } from 'eslint'
31
41
  import { countGates } from '../eslint/index'
42
+ import { repositoryOf } from '../registry/skill'
32
43
 
33
44
  export interface HookOptions {
34
45
  /** The repository's top folder. Defaults to `$CLAUDE_PROJECT_DIR`, then the tool call's `cwd`. */
@@ -39,6 +50,8 @@ export interface HookOptions {
39
50
  audience?: 'app' | 'package'
40
51
  /** The hook's input, when not read from stdin (tests). */
41
52
  input?: unknown
53
+ /** Where a session's searches are remembered. Defaults to a folder in the system's temp. */
54
+ seen?: string
42
55
  }
43
56
 
44
57
  export interface HookResult {
@@ -50,13 +63,14 @@ export interface HookResult {
50
63
 
51
64
  interface ToolCall {
52
65
  tool_name?: string
66
+ session_id?: string
53
67
  cwd?: string
54
68
  tool_input?: { file_path?: unknown; content?: unknown; old_string?: unknown; new_string?: unknown; replace_all?: unknown }
55
69
  }
56
70
 
57
71
  const PASS: HookResult = { code: 0, message: '' }
58
72
 
59
- export async function runHook({ root, app = '.', audience = 'app', input }: HookOptions = {}): Promise<HookResult> {
73
+ export async function runHook({ root, app = '.', audience = 'app', input, seen }: HookOptions = {}): Promise<HookResult> {
60
74
  let call: ToolCall
61
75
  try {
62
76
  call = (input ?? JSON.parse(readFileSync(0, 'utf8'))) as ToolCall
@@ -86,7 +100,7 @@ export async function runHook({ root, app = '.', audience = 'app', input }: Hook
86
100
  // the typecheck's to judge; the gate looks again at the edit that completes it.
87
101
  const errors = results.flatMap((r) => r.messages.filter((m) => m.severity === 2 && m.ruleId))
88
102
  const { disabled } = countGates(results)
89
- if (errors.length === 0 && disabled.length === 0) return PASS
103
+ if (errors.length === 0 && disabled.length === 0) return searchFirst(call, file, text, appDir, top, seen) ?? PASS
90
104
 
91
105
  const shown = (p: string) => relative(top, p).split(sep).join('/')
92
106
  const lines = [`${shown(file)} was not written: the UI Guardrails refuse it (${shown(config)}).`]
@@ -96,6 +110,56 @@ export async function runHook({ root, app = '.', audience = 'app', input }: Hook
96
110
  return { code: 2, message: `${lines.join('\n')}\n` }
97
111
  }
98
112
 
113
+ /** The part a Write would add in a new file, or null: a capitalised export, in a file that draws. */
114
+ export function newPart(tool: string | undefined, file: string, text: string): string | null {
115
+ if (tool !== 'Write' || existsSync(file) || !file.endsWith('.tsx') || /\.stories\.tsx$/.test(file)) return null
116
+ if (!/<\/[A-Za-z]|\/>/.test(text)) return null
117
+ const named = /export\s+(?:default\s+)?(?:async\s+)?(?:function|const|class)\s+([A-Z][A-Za-z0-9]*)/.exec(text)?.[1]
118
+ if (named) return named
119
+ return /export\s+default\s+function\s*\(/.test(text) ? basename(file, '.tsx') : null
120
+ }
121
+
122
+ /** `PanelHeader` → `panel header`: the words the search is asked. */
123
+ export const wordsOf = (name: string) => name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/([A-Z])([A-Z][a-z])/g, '$1 $2').toLowerCase()
124
+
125
+ /** The catalogue command: beside this file once built, or the built one from source (tests). */
126
+ function findCommand(): string | null {
127
+ for (const at of ['../registry/cli.js', '../../dist/registry/cli.js']) {
128
+ const path = fileURLToPath(new URL(at, import.meta.url))
129
+ if (existsSync(path)) return path
130
+ }
131
+ return null
132
+ }
133
+
134
+ /** Stop a new part's first Write with what already exists; null lets it through. */
135
+ function searchFirst(call: ToolCall, file: string, text: string, appDir: string, top: string, seen?: string): HookResult | null {
136
+ const part = newPart(call.tool_name, file, text)
137
+ const command = findCommand()
138
+ if (!part || !command) return null
139
+ const folder = seen ?? join(tmpdir(), 'estiva-ui-search-first')
140
+ const mark = join(folder, createHash('sha1').update(`${call.session_id ?? ''}\n${resolve(file)}`).digest('hex'))
141
+ if (existsSync(mark)) return null
142
+ const words = wordsOf(part)
143
+ const repo = basename(repositoryOf(appDir))
144
+ const run = spawnSync(process.execPath, [command, 'find', ...words.split(' '), '--root', appDir, '--repo', repo, '--limit', '5'], { encoding: 'utf8', timeout: 60_000 })
145
+ if (run.status !== 0 || !run.stdout.trim()) return null
146
+ try {
147
+ mkdirSync(folder, { recursive: true })
148
+ writeFileSync(mark, '')
149
+ } catch {
150
+ return null
151
+ }
152
+ const shown = relative(top, file).split(sep).join('/')
153
+ return {
154
+ code: 2,
155
+ message:
156
+ `${shown} was not written yet: it adds a new part, ${part}. Search before building (UIG-20). What already exists for "${words}":\n\n` +
157
+ `${run.stdout.trim()}\n\n` +
158
+ `If one of these does the job, use it, and read its page first. If the words were wrong, run \`npm run ui:find <other words>\`. ` +
159
+ `If nothing fits, tell the person, then write the file again: it goes through.\n`,
160
+ }
161
+ }
162
+
99
163
  /** The file as it will be after this tool call, or null when that cannot be known. */
100
164
  function proposed(tool: string | undefined, args: NonNullable<ToolCall['tool_input']>, file: string): string | null {
101
165
  if (tool === 'Write') return typeof args.content === 'string' ? args.content : null
@@ -526,6 +526,25 @@ describe('one search over the package and the apps', () => {
526
526
  expect(found.indexOf('estiva-ui:EmptyState')).toBeLessThan(found.indexOf('fixture:EmptyState'))
527
527
  })
528
528
 
529
+ it("puts a package part whose name carries a word before an app's part answering as many (UIG-20)", () => {
530
+ // "panel header" put an app's own `Header` above the package's `ContainerHeader`: its whole name is one of the words.
531
+ const header = buildAppRegistry({
532
+ root: app({ 'src/Header.tsx': '/** The top row of a panel: its title and its buttons. */\nexport function Header() {\n return <header />\n}\n' }),
533
+ repo: 'fixture',
534
+ })
535
+ const found = findInRegistries([packageRegistry, header], 'panel header', { limit: 5 }).map((f) => `${f.entry.repo}:${f.entry.name}`)
536
+ expect(found[0]).toBe('estiva-ui:ContainerHeader')
537
+ expect(found).toContain('fixture:Header')
538
+ })
539
+
540
+ it("does not let a package part the words reach only through its notes bury the app's answer", () => {
541
+ const composer = buildAppRegistry({
542
+ root: app({ 'src/Composer.tsx': '/** Where a comment is written and sent. */\nexport function Composer() {\n return <form />\n}\n' }),
543
+ repo: 'fixture',
544
+ })
545
+ expect(findInRegistries([packageRegistry, composer], 'comment composer')[0].entry).toMatchObject({ repo: 'fixture', name: 'Composer' })
546
+ })
547
+
529
548
  it('says which apps hand a package part on, and how a default is imported', () => {
530
549
  const text = formatFindings([packageRegistry, registry], findInRegistries([packageRegistry, registry], 'Button', { limit: 1 }), 'Button')
531
550
  expect(text).toContain('fixture hands it on from @/components/ui/Button')
@@ -554,10 +573,48 @@ describe.skipIf(!existsSync(cli))('estiva-ui in an app', () => {
554
573
  }
555
574
  expect(failed.stdout).toMatch(/^fixture: 17 parts in 15 files \(2 more hold none\)/)
556
575
  expect(failed.stderr).toContain('Timeline (reusable, src/components/Timeline.tsx) has no usage page: write src/components/Timeline.mdx')
557
- const one = app({ 'src/One.tsx': '/** One, drawn once. */\nexport function One() {\n return <i />\n}\n' })
576
+ const one = app({ 'src/One.tsx': '/** One, drawn once. */\nexport function One() {\n return <i />\n}\n', 'node_modules/@estiva-app/ui/skill/estiva-ui.md': '# The skill\n' })
577
+ run(['skill'], one)
558
578
  expect(run(['check'], one)).toContain('usage pages: all 0 reusable parts keep the contract')
559
579
  })
560
580
 
581
+ it('skill writes a loader that reads the installed package, and check fails when it is missing or differs (UIG-20)', () => {
582
+ const two = app({ 'src/Two.tsx': '/** Two, drawn once. */\nexport function Two() {\n return <i />\n}\n', 'node_modules/@estiva-app/ui/skill/estiva-ui.md': '# The skill\n' })
583
+ const failure = (cwd: string) => {
584
+ try {
585
+ run(['check'], cwd)
586
+ } catch (error) {
587
+ return (error as { stderr?: string }).stderr ?? ''
588
+ }
589
+ return ''
590
+ }
591
+ expect(failure(two)).toContain('.claude/skills/estiva-ui/SKILL.md is missing: run "estiva-ui skill" and commit it')
592
+ run(['skill'], two)
593
+ const loader = readFileSync(join(two, '.claude', 'skills', 'estiva-ui', 'SKILL.md'), 'utf8')
594
+ expect(loader).toMatch(/^---\nname: estiva-ui\ndescription: "Use before building/)
595
+ expect(loader).toContain('!`cat "${CLAUDE_PROJECT_DIR}/node_modules/@estiva-app/ui/skill/estiva-ui.md"`')
596
+ expect(JSON.parse(readFileSync(join(two, '.claude', 'settings.json'), 'utf8')).permissions.allow).toContain('Bash(npm run ui:find *)')
597
+ // Its text is the package's, never a copy.
598
+ expect(loader).not.toContain('# The skill')
599
+ expect(run(['check'], two)).toContain('claude skill: the loader reads the package’s text')
600
+ writeFileSync(join(two, '.claude', 'skills', 'estiva-ui', 'SKILL.md'), `${loader}\nA line of our own.\n`)
601
+ expect(failure(two)).toContain('SKILL.md is not what the package writes')
602
+ })
603
+
604
+ it('skill --out writes a loader for a folder that holds the repositories, reading an app inside it', () => {
605
+ const holder = mkdtempSync(join(tmpdir(), 'uig20-holder-'))
606
+ made.push(holder)
607
+ mkdirSync(join(holder, 'one', 'node_modules', '@estiva-app', 'ui', 'skill'), { recursive: true })
608
+ writeFileSync(join(holder, 'one', 'package.json'), JSON.stringify({ name: 'one' }))
609
+ writeFileSync(join(holder, 'one', 'node_modules', '@estiva-app', 'ui', 'skill', 'estiva-ui.md'), '# The skill\n')
610
+ run(['skill', '--out', '..'], join(holder, 'one'))
611
+ const loader = readFileSync(join(holder, '.claude', 'skills', 'estiva-ui', 'SKILL.md'), 'utf8')
612
+ expect(loader).toContain('!`cat "${CLAUDE_PROJECT_DIR}/one/node_modules/@estiva-app/ui/skill/estiva-ui.md"`')
613
+ // Claude Code refuses a path that climbs out with `..`, so a folder that does not hold the app is refused here.
614
+ const elsewhere = app({ 'node_modules/@estiva-app/ui/skill/estiva-ui.md': '# The skill\n' })
615
+ expect(() => run(['skill', '--out', holder], elsewhere)).toThrow(/does not hold/)
616
+ })
617
+
561
618
  it("find searches the app and the package, and never takes an app's own registry.json for the package's", () => {
562
619
  // What `estiva-ui build` leaves behind in an app, and git ignores.
563
620
  run(['build'], root)
@@ -3,9 +3,10 @@
3
3
  * `estiva-ui` — the catalogue as a command (UIG-12, UIG-13; docs/GATES.md §23
4
4
  * for why it ships in the package rather than as a script pasted into each repo).
5
5
  *
6
- * estiva-ui find <words…> [--also [name=]<folder>]… [--json] [--limit n]
6
+ * estiva-ui find <words…> [--here | --also [name=]<folder>…] [--json] [--limit n]
7
7
  * estiva-ui build [--out <path>]
8
8
  * estiva-ui check
9
+ * estiva-ui skill [--out <folder>]
9
10
  *
10
11
  * Every command takes `--root <folder>` (the library it reads; default: here)
11
12
  * and `--repo <name>` (what an app's entries are called; default: its package name).
@@ -21,15 +22,23 @@
21
22
  *
22
23
  * `find` searches the package's catalogue — the one shipped inside the installed
23
24
  * package, or this repo's own in the package — plus, in an app, the app's own,
24
- * built fresh, plus each `--also` app that sits beside it.
25
+ * built fresh, plus every app beside it (UIG-20, `./siblings`): found, not
26
+ * named, so one command answers the same from any repository, or from the
27
+ * folder that holds them. `--here` searches no neighbour; `--also` names them.
28
+ *
29
+ * `skill` writes the repository's Claude skill loader (UIG-20, `./skill`), or
30
+ * the one for `--out <folder>`; `check` fails when the repository's is missing
31
+ * or differs.
25
32
  */
26
33
  import { spawnSync } from 'node:child_process'
27
- import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
34
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
28
35
  import { tmpdir } from 'node:os'
29
- import { basename, join, resolve } from 'node:path'
36
+ import { basename, dirname, join, relative, resolve } from 'node:path'
30
37
  import { fileURLToPath } from 'node:url'
31
38
  import { CONTRACT_KINDS, contractProblems, linkProblems } from './contract'
32
39
  import { findInRegistries, formatFindings } from './find'
40
+ import { findSiblings, workspaceOf } from './siblings'
41
+ import { loaderPath, loaderProblem, loaderText, repositoryOf, settingsPath, settingsWithSearch } from './skill'
33
42
  import { CLASSES, validateRegistry, type Registry } from './schema'
34
43
 
35
44
  /**
@@ -91,6 +100,20 @@ function readPackageRegistry(): Registry {
91
100
  return registry
92
101
  }
93
102
 
103
+ /** The installed package whose skill text a loader reads: this repo in the package, else the app's install. */
104
+ const packageRoot = () => (isPackage ? root : resolve(root, 'node_modules', '@estiva-app', 'ui'))
105
+
106
+ /** The Claude skill loader (UIG-20): reports, and says whether it passed. */
107
+ function checkLoader(): boolean {
108
+ const problem = loaderProblem(repositoryOf(root), packageRoot())
109
+ if (problem) {
110
+ process.stderr.write(`claude skill: ${problem}\n`)
111
+ return false
112
+ }
113
+ process.stdout.write('claude skill: the loader reads the package’s text\n')
114
+ return true
115
+ }
116
+
94
117
  async function buildApp(folder: string, repo: string | undefined): Promise<Registry> {
95
118
  const { buildAppRegistry } = await appBuilder()
96
119
  const registry = buildAppRegistry({ root: folder, repo })
@@ -179,7 +202,13 @@ async function main(): Promise<number> {
179
202
  process.stderr.write(`not searched: ${first}${more.length ? `\n${more.slice(0, 3).join('\n')}${more.length > 3 ? `\n …and ${more.length - 3} more — run "estiva-ui check" there` : ''}` : ''}\n`)
180
203
  }
181
204
  }
182
- if (!isPackage) await add(root, value('repo'))
205
+ // The folder it runs in is searched when it is an app; the folder that
206
+ // holds the repositories is not one, and only its neighbours answer.
207
+ const here = !isPackage && existsSync(resolve(root, 'package.json')) ? (manifestAt(root).name ?? basename(root)) : null
208
+ if (here) await add(root, value('repo'))
209
+ if (!values('also').length && !flag('here')) {
210
+ for (const sibling of findSiblings(workspaceOf(root), { skip: here ? [here] : [] })) await add(sibling.folder, sibling.name)
211
+ }
183
212
  for (const also of values('also')) {
184
213
  const [name, folder] = also.includes('=') ? [also.slice(0, also.indexOf('=')), also.slice(also.indexOf('=') + 1)] : [undefined, also]
185
214
  const at = resolve(root, folder)
@@ -236,7 +265,8 @@ async function main(): Promise<number> {
236
265
  }
237
266
  const linked = checkLinks(registry, root)
238
267
  const shown = await checkGated(registry, root)
239
- return broken.length || !linked || !shown ? 1 : 0
268
+ const loaded = checkLoader()
269
+ return broken.length || !linked || !shown || !loaded ? 1 : 0
240
270
  }
241
271
  const { buildRegistry, serializeRegistry } = await packageBuilder()
242
272
  const path = packageRegistryPath()
@@ -259,11 +289,33 @@ async function main(): Promise<number> {
259
289
  process.stdout.write(`${path}: current, ${built.entries.length} entries from ${built.builtFrom.exports} exports\n`)
260
290
  const linked = checkLinks(built, root)
261
291
  const shown = await checkGated(built, root, ['component'])
262
- return linked && shown ? 0 : 1
292
+ const loaded = checkLoader()
293
+ return linked && shown && loaded ? 0 : 1
294
+ }
295
+
296
+ case 'skill': {
297
+ const out = value('out')
298
+ const folder = out ? resolve(out) : repositoryOf(root)
299
+ // The loader's path starts where the session does and cannot climb out:
300
+ // Claude Code refuses a `..` in it.
301
+ if (relative(folder, packageRoot()).startsWith('..')) {
302
+ process.stderr.write(`${folder} does not hold ${packageRoot()}: a loader there could not reach the skill's text\n`)
303
+ return 1
304
+ }
305
+ const path = loaderPath(folder)
306
+ mkdirSync(dirname(path), { recursive: true })
307
+ writeFileSync(path, loaderText(folder, packageRoot()), 'utf8')
308
+ process.stdout.write(`${path}: the Claude skill, read from ${packageRoot()}\n`)
309
+ const settings = settingsWithSearch(folder)
310
+ if (settings) {
311
+ writeFileSync(settingsPath(folder), settings, 'utf8')
312
+ process.stdout.write(`${settingsPath(folder)}: the search allowed without a prompt\n`)
313
+ }
314
+ return 0
263
315
  }
264
316
 
265
317
  default:
266
- process.stderr.write('estiva-ui <find | build | check>\n')
318
+ process.stderr.write('estiva-ui <find | build | check | skill>\n')
267
319
  return 1
268
320
  }
269
321
  }
@@ -96,6 +96,11 @@ export function findInRegistry(registry: Registry, query: string, { limit = 5 }:
96
96
  * An app's pass-on is not a result of its own — it is the package's part, and
97
97
  * the package's entry answers for it, saying which apps hand it on. At the
98
98
  * same strength the package's part comes first: it is the one to reach for.
99
+ * And a package part whose name carries one of the words comes before an app's
100
+ * part answering as many words, whatever each scored: "panel header" put an
101
+ * app's own `Header`, whose whole name is one of the words, above the package's
102
+ * `ContainerHeader` (UIG-20). Only by name: a package part the words reach
103
+ * through its notes alone would bury the app part that is the answer.
99
104
  */
100
105
  export function findInRegistries(registries: Registry[], query: string, { limit = 5 }: { limit?: number } = {}): Finding[] {
101
106
  const all = words(query)
@@ -162,7 +167,11 @@ export function findInRegistries(registries: Registry[], query: string, { limit
162
167
  }
163
168
 
164
169
  const fromPackage = (finding: Finding) => (finding.entry.app === null ? 0 : 1)
165
- findings.sort((a, b) => b.matched - a.matched || b.score - a.score || fromPackage(a) - fromPackage(b) || a.entry.name.localeCompare(b.entry.name))
170
+ const namedInPackage = (finding: Finding) => (finding.entry.app === null && finding.where.includes('name') ? 0 : 1)
171
+ findings.sort(
172
+ (a, b) =>
173
+ b.matched - a.matched || namedInPackage(a) - namedInPackage(b) || b.score - a.score || fromPackage(a) - fromPackage(b) || a.entry.name.localeCompare(b.entry.name),
174
+ )
166
175
  return findings.slice(0, limit)
167
176
  }
168
177