Skip to content
suit Artifact [e370275f2f]
Login

Artifact [e370275f2f]

Artifact e370275f2f8245d724a1d76c05d39076fbd58bec8dae4c6ea146257ecf277b10:


// Runs the script of pages written by `suit curate` against a small stub of the
// document, with no browser, and checks what it computes (docs/curate.md): rows,
// suggestions and their reasons, the kind switch, the filters and their counts, the
// bulk actions, the keyboard, Limit refused, the outcome numbers and the choices
// text. It prints `ok NAME` and `FAIL NAME: why` lines, as the shell suites do.
//
// usage: node test/curate_page.js FIXTURE_PAGE NO_USAGE_PAGE LONG_WINDOW_PAGE
// FIXTURE_PAGE is test/curate.sh's fixture with a 30-day window on 2026-11-20.
'use strict';
const fs = require('fs');
const vm = require('vm');

let failed = 0;
function ok(name, cond, why) {
  if (cond) console.log('ok ' + name);
  else { failed++; console.log('FAIL ' + name + (why === undefined ? '' : ': ' + why)); }
}
const eq = (name, got, want) => ok(name, got === want, 'got ' + JSON.stringify(got) + ', want ' + JSON.stringify(want));

// A page with its script run against a stub document. Returns what the checks need.
function load(file) {
  const html = fs.readFileSync(file, 'utf8');
  const scripts = html.match(/<script>/g) || [];
  const m = html.match(/<script>([\s\S]*)<\/script>/);
  const hiddenAtStart = new Set((html.match(/id="[\w-]+"[^>]*\shidden/g) || []).map(s => s.match(/id="([\w-]+)"/)[1]));
  const els = {};
  const getEl = id => els[id] || (els[id] = {
    id, innerHTML: '', textContent: '', value: '', hidden: hiddenAtStart.has(id), listeners: {}, attrs: {}, focused: false, selected: false,
    addEventListener(t, f) { this.listeners[t] = f; },
    setAttribute(k, v) { this.attrs[k] = v; }, removeAttribute(k) { delete this.attrs[k]; },
    focus() { this.focused = true; }, select() { this.selected = true; }, scrollIntoView() {},
    querySelector() { return null; }, closest() { return null; },
  });
  const group = attr => (html.match(new RegExp('data-' + attr + '="(\\w+)"', 'g')) || []).map(s => {
    const v = s.match(/"(\w+)"/)[1];
    return Object.assign(getEl('data-' + attr + '-' + v), { dataset: {[attr]: v} });
  });
  const sortButtons = group('s'), bulkButtons = group('bulk');
  const doc = {
    listeners: {},
    getElementById: getEl,
    querySelectorAll(sel) { return sel === '[data-s]' ? sortButtons : sel === '[data-bulk]' ? bulkButtons : []; },
    addEventListener(t, f) { this.listeners[t] = f; },
    createElement() { const a = {click() { doc.clicked = a; }}; return a; },
    body: {appendChild() {}, removeChild() {}},
  };
  class FakeDate extends Date { constructor(...a) { if (a.length) super(...a); else super(2026, 11, 25, 12, 0, 0); } }
  const saved = {blobs: []};
  const sandbox = {
    document: doc, Date: FakeDate, setTimeout() {},
    navigator: {clipboard: {writeText(t) { saved.copied = t; return Promise.resolve(); }}},
    Blob: class { constructor(parts, opt) { this.text = parts.join(''); this.type = opt.type; saved.blobs.push(this); } },
    URL: {createObjectURL(b) { saved.url = b; return 'blob:stub'; }, revokeObjectURL() {}},
  };
  const ctx = vm.createContext(sandbox);
  vm.runInContext(m[1], ctx);
  const run = code => vm.runInContext(code, ctx);
  const key = (k, tag) => doc.listeners.keydown({key: k, target: {tagName: tag || 'BODY'}, preventDefault() {}});
  const click = (id, sel, dataset) => getEl(id).listeners.click({target: {closest: s => s === sel ? {dataset, disabled: false} : null}});
  const rows = () => (getEl('rows').innerHTML.match(/class="item /g) || []).length;
  return {html, scripts: scripts.length, getEl, doc, run, key, click, rows, saved, sandbox, sortButtons, bulkButtons};
}

// ---- the fixture page: a 30-day window on 2026-11-20 ----------------------------------------

const a = load(process.argv[2]);
eq('page has one script', a.scripts, 1);
ok('page loads nothing from anywhere', !/https?:|@import|fetch\(|XMLHttpRequest|localStorage| on[a-z]+="/.test(a.html));
const names = a.run('ASSETS.map(d => d.k + " " + d.n + (d.w === "side" ? "@side" : ""))');
eq('assets are in byte order of kind then name', names.join('|'),
  ['agent planner', 'agent reviewer', 'command bar', 'command foo', 'skill alpha', 'skill beta', 'skill bigfm', 'skill delta', 'skill emptyskill', 'skill gamma-one',
    'skill gamma-two', 'skill huge', 'skill idle', 'skill longdesc', 'skill loose-one', 'skill nodesc', 'skill nofile', 'skill nofm', 'skill nowhere', 'skill sidea@side', 'skill soloish', 'skill soloskill',
    'skill spacey', 'skill stored', 'skill twin', 'skill twin@side'].join('|'));

const want = {
  'agent planner': ['retire', 'already in the attic'],
  'agent reviewer': ['keep', '1 use · 1 project'],
  'command bar': ['retire', 'no uses in 30 days'],
  'command foo': ['keep', '2 uses · 2 projects'],
  'skill alpha': ['keep', '5 uses · all in ~/work/proj-one (not a known project)'],
  'skill beta': ['keep', '3 uses · 2 projects'],
  'skill bigfm': ['retire', 'no uses in 30 days'],
  'skill delta': ['retire', 'no uses in 30 days'],
  'skill emptyskill': ['retire', 'no uses in 30 days'],
  'skill gamma-one': ['keep', 'no uses yet · files changed recently'],
  'skill gamma-two': ['retire', 'no uses in 30 days'],
  'skill huge': ['retire', 'no uses in 30 days'],
  'skill idle': ['retire', 'already in the attic'],
  'skill longdesc': ['retire', 'no uses in 30 days'],
  'skill loose-one': ['retire', 'no uses in 30 days'],
  'skill nodesc': ['retire', 'no uses in 30 days'],
  'skill nofile': ['retire', 'no uses in 30 days'],
  'skill nofm': ['retire', 'no uses in 30 days'],
  'skill sidea@side': ['retire', 'no uses in 30 days'],
  'skill soloskill': ['keep', 'already limited to github.com/o/solo'],
  'skill spacey': ['keep', '3 uses · all in ~/work/my proj (not a known project)'],
  'skill soloish': ['limit', '3 uses · all in github.com/o/solo'],
  'skill nowhere': ['keep', '3 uses · all in - (not a known project)'],
  'skill stored': ['retire', 'already in the attic'],
  'skill twin': ['keep', '1 use · 1 project'],
  'skill twin@side': ['keep', '1 use · 1 project'],
};
const got = a.run('ASSETS.map(d => [d.k + " " + d.n + (d.w === "side" ? "@side" : ""), d.sug, d.why, d.choice])');
for (const [n, sug, why, choice] of got) {
  ok('suggestion of ' + n, want[n] && want[n][0] === sug && want[n][1] === why && choice === sug, JSON.stringify([sug, why, choice]));
}

// The kind switch, headline and filters.
const idx = n => names.indexOf(n);
eq('starts on skills', a.run('kind'), 'skill');
eq('skill rows', a.rows(), 22);
eq('skill headline', a.getEl('headline').textContent, '22 skills are in your wardrobes. 8 of them were used in the last 30 days.');
ok('no history note', a.getEl('history').hidden === true && a.getEl('history').textContent === '');
const kinds = a.getEl('kinds').innerHTML;
ok('kind switch counts', /Skills<span class="n">22<\/span>/.test(kinds) && /Agents<span class="n">2<\/span>/.test(kinds) && /Commands<span class="n">2<\/span>/.test(kinds), kinds);
const filters = a.getEl('filters').innerHTML;
const count = (id) => (filters.match(new RegExp('data-f="' + id + '"[^>]*>[^<]*<span class="n">(\\d+)<'))[1]);
eq('filter all', count('all'), '22');
eq('filter unused', count('unused'), '14');
eq('filter one project', count('one'), '7');
eq('filter attic', count('attic'), '2');
eq('filter changed', count('changed'), '0');
a.click('kinds', '[data-k]', {k: 'agent'});
eq('agent rows', a.rows(), 2);
eq('agent headline', a.getEl('headline').textContent, '2 agents are in your wardrobes. 1 of them was used in the last 30 days.');
a.click('kinds', '[data-k]', {k: 'command'});
eq('command rows', a.rows(), 2);
eq('command headline', a.getEl('headline').textContent, '2 commands are in your wardrobes. 1 of them was used in the last 30 days.');
a.click('kinds', '[data-k]', {k: 'skill'});
eq('column heading follows the kind', a.getEl('h-name').textContent, 'Skill');
eq('uses heading names the window', a.getEl('h-uses').textContent, 'Uses · 30 days');

// Rows: escaping, the attic tag, Limit disabled with its reason.
const rowsHtml = a.getEl('rows').innerHTML;
ok('a description with markup is escaped', rowsHtml.includes('&lt;img src=x onerror=alert(1)&gt; &amp; &lt;/script&gt;') && !rowsHtml.includes('<img'));
ok('the attic tag is on attic rows', (rowsHtml.match(/in the attic<\/span>/g) || []).length === 2);
ok('Limit is disabled for a folder that is not a project suit knows', rowsHtml.includes('disabled title="Used only in ~/work/proj-one, which is not a project suit knows: add it with suit project set to be able to limit to it"'));
ok('and for a folder with a space in it', rowsHtml.includes('disabled title="Used only in ~/work/my proj, which is not a project suit knows: add it with suit project set to be able to limit to it"'));
ok('and for sessions with no folder', rowsHtml.includes('disabled title="Used only in sessions with no folder, which is not a project suit knows"'));
eq('a key with a space that is not a folder is refused too', a.run('limitWhy({pn: 1, p: [["a b", 3]]})'), 'The project name has a space, which the choices file cannot hold');
eq('a known project can be limited', a.run('limitWhy({pn: 1, p: [["github.com/o/solo", 3]]})'), '');
ok('a name in two wardrobes is tagged with its wardrobe', rowsHtml.split('is in another wardrobe too">main</span>').length === 2 && rowsHtml.split('is in another wardrobe too">side</span>').length === 2);
ok('a unique name has no wardrobe tag', (rowsHtml.match(/another wardrobe too/g) || []).length === 2);
ok('the details always show the wardrobe', (rowsHtml.match(/<dt>Wardrobe<\/dt>/g) || []).length === 22);
ok('Limit is disabled when used in two projects', rowsHtml.includes('title="Used in more than one project"'));
ok('Limit is disabled when unused', rowsHtml.includes('title="Not used in the last 30 days, so there is no project to limit it to"'));
ok('a long description is cut and marked', rowsHtml.includes('a…</p>') && !rowsHtml.includes('a'.repeat(301)));
ok('a missing description says so', rowsHtml.includes('No description found in its SKILL.md.'));
ok('four-week bars in the title', rowsHtml.includes('title="1, 0, 1, 2 in the last four weeks, oldest first"'));

// The search box and the sort buttons.
a.getEl('q').listeners.input({target: {value: ' GAMMA '}});
eq('the filter box narrows by name', a.rows(), 2);
eq('the shown count', a.getEl('shown').textContent, '2 shown');
a.getEl('q').listeners.input({target: {value: 'nothing-matches'}});
ok('an empty list says what to do', a.getEl('rows').innerHTML.includes('No skill matches. Clear the filter to see all 22.'));
a.getEl('q').listeners.input({target: {value: ''}});
a.sortButtons.find(b => b.dataset.s === 'n').listeners.click();
ok('sort by name ascending', a.getEl('rows').innerHTML.indexOf('data-i="' + idx('skill alpha') + '"') < a.getEl('rows').innerHTML.indexOf('data-i="' + idx('skill beta') + '"'));
a.sortButtons.find(b => b.dataset.s === 'n').listeners.click();
ok('sort by name again reverses', a.getEl('rows').innerHTML.indexOf('data-i="' + idx('skill twin') + '"') < a.getEl('rows').innerHTML.indexOf('data-i="' + idx('skill alpha') + '"'));
a.sortButtons.find(b => b.dataset.s === 'l').listeners.click();
ok('sort by last used puts the newest first', a.getEl('rows').innerHTML.indexOf('data-i="' + idx('skill alpha') + '"') < a.getEl('rows').innerHTML.indexOf('data-i="' + idx('skill soloskill') + '"'));
a.sortButtons.find(b => b.dataset.s === 'u').listeners.click();
ok('sort by uses descending', a.run('sortKey') === 'u' && a.run('sortDir') === 'desc');

// The keyboard.
a.key('j');
eq('j goes to the first row', a.run('ASSETS[cur].n'), 'alpha');
a.key('ArrowDown');
eq('arrow down goes on', a.run('ASSETS[cur].n'), 'soloskill');
a.key('k');
eq('k goes back', a.run('ASSETS[cur].n'), 'alpha');
a.key('ArrowUp');
eq('arrow up stays at the top', a.run('ASSETS[cur].n'), 'alpha');
a.key('3');
eq('3 retires', a.run('ASSETS[' + idx('skill alpha') + '].choice'), 'retire');
eq('3 moves to the next row', a.run('ASSETS[cur].n'), 'soloskill');
a.key('2');
eq('2 limits when it applies', a.run('ASSETS[' + idx('skill soloskill') + '].choice'), 'limit');
eq('and moves to the next row', a.run('ASSETS[cur].n'), 'beta');
a.key('j'); a.key('j'); a.key('j');
eq('on a row whose project is a folder', a.run('ASSETS[cur].n'), 'spacey');
a.key('2');
eq('2 is refused when Limit does not apply', a.run('ASSETS[cur].choice'), 'keep');
eq('and the cursor stays', a.run('ASSETS[cur].n'), 'spacey');
a.key('Enter');
ok('Enter opens the details', a.getEl('rows').innerHTML.includes('class="item keep cur open" data-i="' + idx('skill spacey') + '"'));
a.key('Enter');
ok('Enter closes them', !a.getEl('rows').innerHTML.includes(' open"'));
a.key('/');
ok('slash focuses the filter', a.getEl('q').focused === true);
a.key('j', 'INPUT');
eq('keys in the filter box are left alone', a.run('ASSETS[cur].n'), 'spacey');
ok('the changed dot and filter', a.getEl('rows').innerHTML.includes('class="changed-dot"') && /data-f="changed"[^>]*>[^<]*<span class="n">2</.test(a.getEl('filters').innerHTML), a.getEl('filters').innerHTML);
a.click('rows', '[data-pick]', {pick: 'retire'});
ok('a click on a row without a button does nothing here', true);
eq('setChoice refuses Limit for a folder', a.run('setChoice(' + idx('skill alpha') + ', "limit")'), false);
eq('setChoice refuses Limit for two projects', a.run('setChoice(' + idx('skill beta') + ', "limit")'), false);
eq('setChoice accepts Keep', a.run('setChoice(' + idx('skill beta') + ', "keep")'), true);

// The outcome and the choices text after those choices.
const bytes = a.run('ASSETS.filter(d => d.k === "skill" && d.s !== "attic").reduce((s, d) => s + d.dl, 0)');
eq('today counts the bytes of the descriptions not in the attic', bytes, 2273);
ok('the meter says today and after', a.getEl('meter').innerHTML.includes('20 skills · 2.3k bytes') && a.getEl('meter').innerHTML.includes('6 skills · 147 bytes'), a.getEl('meter').innerHTML);
ok('the bar counts', a.getEl('legend').innerHTML.includes('<b>6</b> keep') && a.getEl('legend').innerHTML.includes('<b>2</b> limit') && a.getEl('legend').innerHTML.includes('<b>14</b> retire'), a.getEl('legend').innerHTML);
ok('a careful note when retiring something used', a.getEl('meternote').textContent === 'Careful: the skills you are retiring were used 5 times in the last 30 days.', a.getEl('meternote').textContent);
eq('the result bar counts every kind', a.getEl('sum').innerHTML.replace(/<[^>]*>/g, ''), '8 keep2 limit16 retire2 changed from the suggestion · all kinds');

// Bulk actions on the rows shown, and reset.
a.click('filters', '[data-f]', {f: 'unused'});
eq('unused rows', a.rows(), 14);
a.bulkButtons.find(b => b.dataset.bulk === 'keep').listeners.click();
eq('keep shown', a.run('ASSETS.filter(d => d.k === "skill" && d.u === 0 && d.choice === "keep").length'), 14);
eq('the note says how many', a.getEl('copied').textContent, '14 set to keep.');
eq('rows outside the filter are untouched', a.run('ASSETS[' + idx('skill alpha') + '].choice'), 'retire');
a.bulkButtons.find(b => b.dataset.bulk === 'retire').listeners.click();
eq('retire shown', a.run('ASSETS.filter(d => d.k === "skill" && d.u === 0 && d.choice === "retire").length'), 14);
a.click('filters', '[data-f]', {f: 'all'});
a.getEl('reset').listeners.click();
eq('reset goes back to the suggestions of the kind', a.run('ASSETS.filter(d => d.choice !== d.sug).length'), 0);
eq('and says so', a.getEl('copied').textContent, 'Back to the suggestions for skills.');

const text = [
  '# suit choices 1',
  '# made 2026-12-25 from a page of 2026-11-20, window 30 days',
  'retire agent main planner', 'keep agent main reviewer', 'retire command main bar', 'keep command main foo',
  'keep skill main alpha', 'keep skill main beta', 'retire skill main bigfm', 'retire skill main delta', 'retire skill main emptyskill',
  'keep skill main gamma-one', 'retire skill main gamma-two', 'retire skill main huge', 'retire skill main idle', 'retire skill main longdesc',
  'retire skill main loose-one', 'retire skill main nodesc', 'retire skill main nofile', 'retire skill main nofm', 'keep skill main nowhere',
  'retire skill side sidea', 'personal skill main soloish github.com/o/solo', 'keep skill main soloskill', 'keep skill main spacey',
  'retire skill main stored', 'keep skill main twin', 'keep skill side twin',
].join('\n') + '\n';
eq('the choices text is exact', a.getEl('out').value, text);
a.click('kinds', '[data-k]', {k: 'agent'});
eq('the choices text always covers every kind', a.getEl('out').value, text);
a.run('setChoice(' + idx('skill alpha') + ', "retire")');
ok('a change shows in the text', a.getEl('out').value.includes('\nretire skill main alpha\n'));

// Show, copy and save.
a.getEl('toggleout').listeners.click();
ok('the choices file opens', a.getEl('outwrap').hidden === false && a.getEl('toggleout').textContent === 'Hide choices file');
a.getEl('toggleout').listeners.click();
ok('and closes', a.getEl('outwrap').hidden === true && a.getEl('toggleout').textContent === 'Show choices file');

(async () => {
  a.getEl('copy').listeners.click();
  await Promise.resolve(); await Promise.resolve();
  eq('copy puts the text on the clipboard', a.saved.copied, a.getEl('out').value);
  eq('copy says how many', a.getEl('copied').textContent, 'Copied 26 choices.');
  a.sandbox.navigator.clipboard.writeText = () => Promise.reject(new Error('refused'));
  a.getEl('copy').listeners.click();
  await Promise.resolve(); await Promise.resolve(); await Promise.resolve();
  ok('a refused copy opens the text selected', a.getEl('outwrap').hidden === false && a.getEl('out').selected === true && a.getEl('copied').textContent.startsWith('Copy was refused'));
  const b = load(process.argv[2]);
  b.sandbox.navigator.clipboard = undefined;
  b.getEl('copy').listeners.click();
  ok('no clipboard opens the text selected', b.getEl('outwrap').hidden === false && b.getEl('out').selected === true);

  const c = load(process.argv[2]);
  c.getEl('save').listeners.click();
  eq('save makes a link named suit-choices.txt', c.doc.clicked && c.doc.clicked.download, 'suit-choices.txt');
  eq('save offers the text as a blob', c.saved.url && c.saved.url.text, c.getEl('out').value);
  eq('as plain text', c.saved.url.type, 'text/plain');
  eq('and says so', c.getEl('copied').textContent, 'Saved suit-choices.txt.');
  const d = load(process.argv[2]);
  d.sandbox.URL.createObjectURL = () => { throw new Error('refused'); };
  d.getEl('save').listeners.click();
  ok('a refused save opens the text selected', d.getEl('outwrap').hidden === false && d.getEl('out').selected === true && d.getEl('copied').textContent.startsWith('Saving was refused'));

  // ---- no usage at all in the tally ----------------------------------------------------------
  const n = load(process.argv[3]);
  eq('no usage: the headline says so plainly', n.getEl('headline').textContent,
    '22 skills are in your wardrobes. No usage has been recorded yet, so nothing worn or loose is suggested for retirement.');
  const sug = n.run('ASSETS.map(d => [d.s, d.sug, d.why])');
  ok('no usage: every suggestion is keep with its reason, except the attic', sug.every(([s, k, w]) => s === 'attic' ? k === 'retire' && w === 'already in the attic' : k === 'keep' && w === 'no usage recorded yet'), JSON.stringify(sug));
  eq('no usage: nothing is retired but the attic', n.run('ASSETS.filter(d => d.choice === "retire").length'), 3);
  ok('no usage: there is no history note', n.getEl('history').hidden === true);

  // ---- a window longer than the history ---------------------------------------------------------
  const l = load(process.argv[4]);
  eq('a short history is said plainly', l.getEl('history').textContent, 'The tally holds only 111 days of history (since 2026-08-01), so "the last 400 days" is shorter than it sounds.');
  eq('and shown', l.getEl('history').hidden, false);
  ok('the window is in the choices text', l.getEl('out').value.split('\n')[1].endsWith('window 400 days'));
  ok('singular words', l.run('days(1)') === '1 day' && l.run('plural(1, "skill")') === 'skill');

  console.log(failed === 0 ? 'curate_page.js: all checks passed' : 'curate_page.js: ' + failed + ' failed');
  process.exit(failed === 0 ? 0 : 1);
})();