package file→ .shtukbase/packages/icons/actions/prompt.ts
actions/prompt.ts
138 lines, 9.1 KB.
- // shtuk run icons prompt <page.md> [--art] [--kind]: prints a ready prompt for an agent that gives a page its icon.
- // Tier-aware: for tier none or kind it says "do not add one"; for pick it asks for one emoji or a shared-set icon;
- // for bespoke it asks for a drawing by the contract and, when a style package supplies an IconStyle page, by the style.
- // --art asks for the large card picture (`art`); --kind on a collection page asks for the icon its records inherit.
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
- import { basename, join } from 'node:path';
- import { Icons, iconStyle, isSvgPath, ownIcons, rank } from '../lib/iconlib.ts';
- import { REUSE_RULES, loadSets, search } from '../lib/registry.ts';
- import { ELEMENT_NAMES } from '../lib/svg.ts';
- const args = process.argv.slice(2);
- const target = args.find((a) => !a.startsWith('-'));
- if (!target) {
- console.log('usage: shtuk run icons prompt <page.md> [--art] [--kind] (a page path from the project root)');
- process.exit(2);
- }
- const ic = new Icons();
- const p = ic.page(target);
- if (!existsSync(join(ic.root, p.id.slice(1)))) { console.error(`${p.id}: no such page`); process.exit(1); }
- const wantArt = args.includes('--art');
- const wantKind = args.includes('--kind');
- const fm = p.fm;
- const title = String(fm.title ?? basename(p.id, '.md'));
- const lock = existsSync(join(ic.root, '.shtukbase/packages.lock')) ? readFileSync(join(ic.root, '.shtukbase/packages.lock'), 'utf8') : '';
- const project = /^name:\s*"?(.*?)"?\s*$/m.exec(lock)?.[1] || basename(ic.root);
- const own = ownIcons(p);
- const today = new Date().toISOString().slice(0, 10);
- const L: string[] = [];
- // what the page is about: the description and the first lines of the text
- const body = readFileSync(join(ic.root, p.id.slice(1)), 'utf8').replace(/^---[\s\S]*?\n---\n?/, '');
- const gist = body.split('\n').map((l) => l.trim()).filter((l) => l && !l.startsWith('#') && !l.startsWith('|')).join(' ').slice(0, 500);
- const about = [fm.description, gist].filter(Boolean).join(' — ');
- const coll = p.coll ? ic.collections()[p.coll] : null;
- const kindTarget = wantKind && fm.type === 'Collection';
- const kindColl = kindTarget ? ic.collections()[p.id.slice(0, -3)] : null;
- const tier = kindTarget ? 'bespoke' : p.tier;
- const where = kindTarget ? `the icon every record of ${p.id.slice(0, -3)} inherits (icons.item)` : `${p.id}${p.coll ? ` (a record of ${p.coll})` : ''}`;
- L.push(`# Icon for ${where}: "${title}"`, '', `Project "${project}". Tier: ${tier} (${kindTarget ? 'a kind icon is shared by the whole collection' : p.why}).`);
- if (own.icon || own.art) L.push(`Now: icon ${own.icon || '—'}, art ${own.art || '—'}.`);
- L.push('');
- if (!kindTarget && rank(p.tier) <= rank('kind')) {
- const inherited = coll?.item || (typeof coll?.fm.icon === 'string' ? coll.fm.icon : '') || '📄';
- L.push(p.tier === 'none'
- ? 'This page shows no icon. Do not add icon or art: the check ICN-R02 refuses it.'
- : `This page shows the icon of its collection (${inherited}). Do not add icon or art: the check ICN-R02 refuses it.${coll?.item ? '' : ` To give the whole collection an icon: shtuk run icons prompt ${p.coll!.slice(1)}.md --kind`}`);
- console.log(L.join('\n'));
- process.exit(0);
- }
- // the icon registries: reuse before drawing (the convention /icons/conventions/icon-set.md)
- const { sets } = loadSets(ic.root, ic.s.sets);
- const query = [title, fm.description, basename(p.id, '.md').replace(/-/g, ' ')].filter(Boolean).join(' ');
- function registryBlock(drawing: boolean): void {
- if (!sets.length) return;
- L.push('## Reuse first: the icon registry', ...REUSE_RULES.map((r) => `- ${r}`));
- for (const set of sets) {
- const hits = search(set.registry, query, 8);
- L.push(`- Registry ${set.path} (${set.registry.icons.length} icons). ${hits.length ? 'Nearest by meaning:' : 'Nothing near by the words of this page; search it by meaning yourself.'}`);
- for (const h of hits) L.push(` - ${h.rec.name}: ${h.rec.description}. Use: ${h.rec.use}.${h.rec.avoid ? ` Avoid: ${h.rec.avoid}.` : ''} → \`icon: ${ic.s.set}/${h.rec.name}.svg\``);
- }
- if (drawing) L.push(`- Draw only when no record means the same thing. Then add a record to the registry (name, file, description, use, avoid, aliases, group, added) and say in \`added.why\` why the nearest ones did not fit.`);
- L.push('');
- }
- if ((!kindTarget && p.tier === 'pick') || (wantArt && rank(tier) < rank('bespoke'))) {
- registryBlock(false);
- if (wantArt) L.push('The tier does not allow a bespoke picture (art). Give an emoji instead.', '');
- const setDir = join(ic.root, ic.s.set.slice(1));
- const set = existsSync(setDir) ? readdirSync(setDir).filter((n) => n.endsWith('.svg')).sort() : [];
- L.push(
- 'Pick an icon; do not draw one. Choose ONE of:',
- `- one emoji that stands for what the page is about (not a letter, not a flag, not a face unless the page is about a person); write \`icon: "<emoji>"\` in the front matter;`,
- set.length ? `- an icon of the shared set ${ic.s.set}/: ${set.slice(0, 40).join(', ')}${set.length > 40 ? ', …' : ''}; write \`icon: ${ic.s.set}/<name>.svg\`.` : `- (the shared set ${ic.s.set}/ is empty).`,
- '', `About the page: ${about || '(no text)'}`, '',
- `Then run: shtuk check. Leave the rest of the page as it is.`,
- );
- console.log(L.join('\n'));
- process.exit(0);
- }
- // bespoke: a drawing
- const style = iconStyle(ic.root, ic.s);
- const vb = style?.rules.viewBox || '0 0 96 96';
- const stem = kindTarget ? `kinds/${String(kindColl?.fm.itemType ?? basename(p.id, '.md')).replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()}` : basename(p.id, '.md');
- let file = `${ic.s.folder}/${stem}.svg`;
- const users = (f: string) => ic.pages().filter((x) => { const o = ownIcons(x); return [o.icon, o.art].some((v) => v && isSvgPath(v) && ic.resolve(x.id, v) === f); }).map((x) => x.id);
- if (!kindTarget && existsSync(join(ic.root, file.slice(1))) && users(file).some((u) => u !== p.id)) file = `${ic.s.folder}/${(p.coll ?? 'page').split('/').pop()}-${stem}.svg`;
- const field = kindTarget ? 'icons.item (in the collection page, under icons:)' : wantArt ? 'art' : 'icon';
- const group = p.coll ?? '(pages outside collections)';
- if (!kindTarget) {
- const used = new Set<string>();
- for (const x of ic.pages()) if ((x.coll ?? '(pages outside collections)') === group && x.tier === 'bespoke') {
- const o = ownIcons(x);
- for (const v of [o.icon, o.art]) if (v && isSvgPath(v) && !ic.inSet(ic.resolve(x.id, v))) used.add(ic.resolve(x.id, v));
- }
- const max = coll?.max ?? ic.s.max;
- L.push(`Budget: ${used.size} of ${max} bespoke files in ${group} are used.${used.size >= max && !used.has(file) ? ' The budget is spent: stop and pick an emoji instead, or ask the owner to raise icons.max.' : ''}`, '');
- }
- const neighbours = new Set<string>();
- registryBlock(true);
- for (const x of ic.pages()) if (x.coll && x.coll === p.coll && x.id !== p.id) { const o = ownIcons(x); for (const v of [o.icon, o.art]) if (v && isSvgPath(v)) neighbours.add(ic.resolve(x.id, v)); }
- L.push(
- `Draw one SVG icon for ${kindTarget ? 'this kind of record' : 'this page'}: one recognisable thing that stands for it — a thing, not a letter, not a logo, not a scene.`,
- `About it: ${about || title}`, '',
- '## The contract (checked by ICN-R01; run `shtuk run icons validate <file>`)',
- `- One file, root \`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vb}">\`; the viewBox is square.`,
- `- At most ${ic.s.maxBytes} bytes. Elements only: ${ELEMENT_NAMES.join(', ')}.`,
- '- No text, no <style>, no script or event attributes, no <image>, no links out of the file (href only "#id"), no currentColor (it is black inside <img>); colours as hex.',
- '- It must read at 16 px (a list row) and look good at 108 px (a large card): 3–8 large simple shapes, no hairlines, keep a small margin inside the canvas.',
- '- It must work on a light and a dark background: no shape that is only black or only white.',
- `- Right after the opening <svg> tag, a provenance comment: \`<!-- icon: page=${p.id}; by=<your model>; date=${today}; licence=CC0-1.0 -->\`.`,
- '- Draw from scratch. Do not copy or trace icon sets, emoji artwork or logos.', '',
- );
- if (style) {
- L.push(`## The style: ${style.title} (${style.page})`);
- const pal = Object.entries(style.palette);
- if (pal.length) L.push(`- Colours only from this palette: ${pal.map(([k, v]) => `${k} ${v}`).join(', ')}.`);
- if (!style.rules.gradients) L.push('- Flat fills: no gradients.');
- for (const r of style.prompt) L.push(`- ${r}`);
- if (style.examples.length) L.push(`- Look at examples before drawing: ${style.examples.join(', ')}.`);
- L.push('');
- } else {
- L.push('## The style', '- No icon style is installed (a style package supplies a page with `type: IconStyle`). Use 2–4 flat, saturated colours, rounded corners, no outline.', '');
- }
- if (neighbours.size) L.push(`Neighbours in the same collection — keep the set consistent: ${[...neighbours].slice(0, 12).join(', ')}.`, '');
- L.push(
- '## Do',
- `1. Write the file ${file}.`,
- `2. Set ${field}: ${file} in the front matter of ${p.id}.${own.icon && !wantArt && !kindTarget ? ` (It replaces ${own.icon}.)` : ''}`,
- `3. Run: shtuk run icons validate ${file.slice(1)} — fix every error; then shtuk check.`,
- );
- console.log(L.join('\n'));