ShtukbaseStandard
файл пакета→ .shtukbase/packages/icons/actions/prompt.ts

actions/prompt.ts

138 строк, 9.1 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // shtuk run icons prompt <page.md> [--art] [--kind]: prints a ready prompt for an agent that gives a page its icon.
  2. // 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;
  3. // for bespoke it asks for a drawing by the contract and, when a style package supplies an IconStyle page, by the style.
  4. // --art asks for the large card picture (`art`); --kind on a collection page asks for the icon its records inherit.
  5. import { existsSync, readdirSync, readFileSync } from 'node:fs';
  6. import { basename, join } from 'node:path';
  7. import { Icons, iconStyle, isSvgPath, ownIcons, rank } from '../lib/iconlib.ts';
  8. import { REUSE_RULES, loadSets, search } from '../lib/registry.ts';
  9. import { ELEMENT_NAMES } from '../lib/svg.ts';
  10. const args = process.argv.slice(2);
  11. const target = args.find((a) => !a.startsWith('-'));
  12. if (!target) {
  13. console.log('usage: shtuk run icons prompt <page.md> [--art] [--kind] (a page path from the project root)');
  14. process.exit(2);
  15. }
  16. const ic = new Icons();
  17. const p = ic.page(target);
  18. if (!existsSync(join(ic.root, p.id.slice(1)))) { console.error(`${p.id}: no such page`); process.exit(1); }
  19. const wantArt = args.includes('--art');
  20. const wantKind = args.includes('--kind');
  21. const fm = p.fm;
  22. const title = String(fm.title ?? basename(p.id, '.md'));
  23. const lock = existsSync(join(ic.root, '.shtukbase/packages.lock')) ? readFileSync(join(ic.root, '.shtukbase/packages.lock'), 'utf8') : '';
  24. const project = /^name:\s*"?(.*?)"?\s*$/m.exec(lock)?.[1] || basename(ic.root);
  25. const own = ownIcons(p);
  26. const today = new Date().toISOString().slice(0, 10);
  27. const L: string[] = [];
  28. // what the page is about: the description and the first lines of the text
  29. const body = readFileSync(join(ic.root, p.id.slice(1)), 'utf8').replace(/^---[\s\S]*?\n---\n?/, '');
  30. const gist = body.split('\n').map((l) => l.trim()).filter((l) => l && !l.startsWith('#') && !l.startsWith('|')).join(' ').slice(0, 500);
  31. const about = [fm.description, gist].filter(Boolean).join(' — ');
  32. const coll = p.coll ? ic.collections()[p.coll] : null;
  33. const kindTarget = wantKind && fm.type === 'Collection';
  34. const kindColl = kindTarget ? ic.collections()[p.id.slice(0, -3)] : null;
  35. const tier = kindTarget ? 'bespoke' : p.tier;
  36. 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})` : ''}`;
  37. L.push(`# Icon for ${where}: "${title}"`, '', `Project "${project}". Tier: ${tier} (${kindTarget ? 'a kind icon is shared by the whole collection' : p.why}).`);
  38. if (own.icon || own.art) L.push(`Now: icon ${own.icon || '—'}, art ${own.art || '—'}.`);
  39. L.push('');
  40. if (!kindTarget && rank(p.tier) <= rank('kind')) {
  41. const inherited = coll?.item || (typeof coll?.fm.icon === 'string' ? coll.fm.icon : '') || '📄';
  42. L.push(p.tier === 'none'
  43. ? 'This page shows no icon. Do not add icon or art: the check ICN-R02 refuses it.'
  44. : `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`}`);
  45. console.log(L.join('\n'));
  46. process.exit(0);
  47. }
  48. // the icon registries: reuse before drawing (the convention /icons/conventions/icon-set.md)
  49. const { sets } = loadSets(ic.root, ic.s.sets);
  50. const query = [title, fm.description, basename(p.id, '.md').replace(/-/g, ' ')].filter(Boolean).join(' ');
  51. function registryBlock(drawing: boolean): void {
  52. if (!sets.length) return;
  53. L.push('## Reuse first: the icon registry', ...REUSE_RULES.map((r) => `- ${r}`));
  54. for (const set of sets) {
  55. const hits = search(set.registry, query, 8);
  56. 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.'}`);
  57. 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\``);
  58. }
  59. 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.`);
  60. L.push('');
  61. }
  62. if ((!kindTarget && p.tier === 'pick') || (wantArt && rank(tier) < rank('bespoke'))) {
  63. registryBlock(false);
  64. if (wantArt) L.push('The tier does not allow a bespoke picture (art). Give an emoji instead.', '');
  65. const setDir = join(ic.root, ic.s.set.slice(1));
  66. const set = existsSync(setDir) ? readdirSync(setDir).filter((n) => n.endsWith('.svg')).sort() : [];
  67. L.push(
  68. 'Pick an icon; do not draw one. Choose ONE of:',
  69. `- 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;`,
  70. 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).`,
  71. '', `About the page: ${about || '(no text)'}`, '',
  72. `Then run: shtuk check. Leave the rest of the page as it is.`,
  73. );
  74. console.log(L.join('\n'));
  75. process.exit(0);
  76. }
  77. // bespoke: a drawing
  78. const style = iconStyle(ic.root, ic.s);
  79. const vb = style?.rules.viewBox || '0 0 96 96';
  80. 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');
  81. let file = `${ic.s.folder}/${stem}.svg`;
  82. 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);
  83. 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`;
  84. const field = kindTarget ? 'icons.item (in the collection page, under icons:)' : wantArt ? 'art' : 'icon';
  85. const group = p.coll ?? '(pages outside collections)';
  86. if (!kindTarget) {
  87. const used = new Set<string>();
  88. for (const x of ic.pages()) if ((x.coll ?? '(pages outside collections)') === group && x.tier === 'bespoke') {
  89. const o = ownIcons(x);
  90. 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));
  91. }
  92. const max = coll?.max ?? ic.s.max;
  93. 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.' : ''}`, '');
  94. }
  95. const neighbours = new Set<string>();
  96. registryBlock(true);
  97. 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)); }
  98. L.push(
  99. `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.`,
  100. `About it: ${about || title}`, '',
  101. '## The contract (checked by ICN-R01; run `shtuk run icons validate <file>`)',
  102. `- One file, root \`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vb}">\`; the viewBox is square.`,
  103. `- At most ${ic.s.maxBytes} bytes. Elements only: ${ELEMENT_NAMES.join(', ')}.`,
  104. '- 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.',
  105. '- 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.',
  106. '- It must work on a light and a dark background: no shape that is only black or only white.',
  107. `- Right after the opening <svg> tag, a provenance comment: \`<!-- icon: page=${p.id}; by=<your model>; date=${today}; licence=CC0-1.0 -->\`.`,
  108. '- Draw from scratch. Do not copy or trace icon sets, emoji artwork or logos.', '',
  109. );
  110. if (style) {
  111. L.push(`## The style: ${style.title} (${style.page})`);
  112. const pal = Object.entries(style.palette);
  113. if (pal.length) L.push(`- Colours only from this palette: ${pal.map(([k, v]) => `${k} ${v}`).join(', ')}.`);
  114. if (!style.rules.gradients) L.push('- Flat fills: no gradients.');
  115. for (const r of style.prompt) L.push(`- ${r}`);
  116. if (style.examples.length) L.push(`- Look at examples before drawing: ${style.examples.join(', ')}.`);
  117. L.push('');
  118. } else {
  119. 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.', '');
  120. }
  121. if (neighbours.size) L.push(`Neighbours in the same collection — keep the set consistent: ${[...neighbours].slice(0, 12).join(', ')}.`, '');
  122. L.push(
  123. '## Do',
  124. `1. Write the file ${file}.`,
  125. `2. Set ${field}: ${file} in the front matter of ${p.id}.${own.icon && !wantArt && !kindTarget ? ` (It replaces ${own.icon}.)` : ''}`,
  126. `3. Run: shtuk run icons validate ${file.slice(1)} — fix every error; then shtuk check.`,
  127. );
  128. console.log(L.join('\n'));