@giamme/forge 0.19.0 → 0.21.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 (72) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +7 -0
  3. package/SKILL.md +3 -0
  4. package/VERSION +1 -1
  5. package/docs/README.md +1 -0
  6. package/docs/commands.md +137 -5
  7. package/docs/development.md +1 -1
  8. package/docs/forge-ui.md +70 -19
  9. package/forge +8 -2
  10. package/package.json +1 -1
  11. package/references/decompose.md +20 -8
  12. package/references/memory.md +30 -5
  13. package/scripts/forge-config.py +10 -9
  14. package/scripts/forge-control.py +51 -35
  15. package/scripts/forge-findings.py +675 -0
  16. package/scripts/forge-group.py +2 -1
  17. package/scripts/forge-guard.py +71 -33
  18. package/scripts/forge-handoff.py +14 -17
  19. package/scripts/forge-issues.py +233 -99
  20. package/scripts/forge-memory.sh +471 -19
  21. package/scripts/forge-parallel.sh +24 -14
  22. package/scripts/forge-planner.py +28 -2
  23. package/scripts/forge-pre-review.py +11 -4
  24. package/scripts/forge-ripwire.py +68 -22
  25. package/scripts/forge-route.py +10 -3
  26. package/scripts/forge-runs-compact.py +3 -2
  27. package/scripts/forge-runs-rm.py +14 -14
  28. package/scripts/forge-runtime.py +36 -19
  29. package/scripts/forge-schedule.py +135 -62
  30. package/scripts/forge-shadow.py +16 -9
  31. package/scripts/forge-summarize.py +7 -3
  32. package/scripts/forge-sweep.py +206 -46
  33. package/scripts/forge-ui.py +8 -13
  34. package/scripts/forge-verify.py +29 -23
  35. package/scripts/forge_brief/__init__.py +1 -1
  36. package/scripts/forge_brief/proposals.py +7 -2
  37. package/scripts/forge_decide/budget.py +6 -1
  38. package/scripts/forge_decide/replay.py +6 -1
  39. package/scripts/forge_findings/__init__.py +17 -0
  40. package/scripts/forge_findings/apply.py +442 -0
  41. package/scripts/forge_findings/status.py +43 -0
  42. package/scripts/forge_findings/store.py +595 -0
  43. package/scripts/forge_findings/tags.py +53 -0
  44. package/scripts/forge_findings/triage.py +594 -0
  45. package/scripts/forge_flock.py +87 -0
  46. package/scripts/forge_fractal/__init__.py +7 -3
  47. package/scripts/forge_fractal/cli.py +7 -2
  48. package/scripts/forge_fractal/execution.py +14 -14
  49. package/scripts/forge_fractal/invocation.py +3 -2
  50. package/scripts/forge_fractal/pipeline.py +2 -1
  51. package/scripts/forge_fractal/selection.py +2 -1
  52. package/scripts/forge_identity.py +328 -0
  53. package/scripts/forge_locations.py +14 -4
  54. package/scripts/forge_memory_list.py +7 -3
  55. package/scripts/forge_posix.py +108 -0
  56. package/scripts/forge_proc.py +399 -0
  57. package/scripts/forge_registry.py +15 -6
  58. package/scripts/forge_retro/__init__.py +8 -2
  59. package/scripts/forge_retro/issues.py +2 -1
  60. package/scripts/forge_side/__init__.py +232 -38
  61. package/scripts/forge_storage.py +11 -1
  62. package/ui/docs/api.md +130 -12
  63. package/ui/forge_ui/control.py +693 -17
  64. package/ui/forge_ui/export.py +1 -1
  65. package/ui/forge_ui/projects.py +209 -22
  66. package/ui/forge_ui/reader.py +18 -17
  67. package/ui/forge_ui/server.py +10 -1
  68. package/ui/forge_ui/static/findingsactions.js +201 -0
  69. package/ui/forge_ui/static/index.html +2 -0
  70. package/ui/forge_ui/static/projectsview.js +600 -45
  71. package/ui/forge_ui/static/style.css +59 -0
  72. package/ui/forge_ui/static/triageview.js +423 -0
@@ -3,7 +3,9 @@
3
3
  Routes: #/projects (the list) and #/projects/<id>[/runs|/findings|/memories]. The id is the run cloud's.
4
4
  Each tab reads its own endpoint when it opens, never on the page's poll; "Read again" asks the server to read
5
5
  everything again. A redraw keeps filters, scroll and a selection (#115). Finding and memory texts are untrusted
6
- and only ever enter the page as text. The pure helpers are tested in ui/tests/js/projectsview.test.js.
6
+ and only ever enter the page as text. With writes on, Memories can edit or add a learning (confirm first);
7
+ read-only, the row shows the forge memory command to copy. The pure helpers are tested in
8
+ ui/tests/js/projectsview.test.js and ui/tests/js/memoriesedit.test.js.
7
9
  ctx = { id?, tab?, runs() (the page's run list), runHref(key), tablePrefs?(id), saveTablePrefs?(id, prefs) }. */
8
10
  (function (root, factory) {
9
11
  'use strict';
@@ -14,22 +16,29 @@
14
16
  'use strict';
15
17
 
16
18
  const list = v => Array.isArray(v) ? v : [];
19
+ const A = root.ForgeFindingsActions || (typeof require === 'function' ? require('./findingsactions.js') : null);
20
+ const T = root.ForgeTriage || (typeof require === 'function' ? require('./triageview.js') : null);
17
21
  const SEVERITIES = ['P0', 'P1', 'P2', 'P3'];
18
- const STATUSES = ['open', 'filed', 'fixed', 'swept', 'dismissed', 'superseded'];
22
+ const STATUSES = ['open', 'to-file', 'filed', 'fixed', 'swept', 'dismissed', 'duplicate', 'shadow', 'unlabelled', 'superseded'];
23
+ const LAMPS = { open: 'lamp-off', 'to-file': 'lamp-route', filed: 'fnd-amber', fixed: 'st-pass', swept: 'st-pass', dismissed: 'lamp-off', duplicate: 'lamp-off',
24
+ shadow: 'st-outdated', unlabelled: 'st-unknown', superseded: 'st-outdated' };
25
+ const OPEN = ['open', 'to-file']; // the filter `open` shows both: a finding marked to file is still open work
19
26
  const STATES = { in_memory: 'in memory', waiting: 'waiting for a second run', stale: 'dropped: stale', capped: 'dropped: trimmed by the cap',
20
27
  muted: 'not injected (curated out)', dropped: 'dropped', gone: 'from a checkout that is gone' };
21
28
  const TABS = ['runs', 'findings', 'memories'];
22
29
  const ROLES_NOTE = 'planner and dwarf get Verify, Known traps and Recurring QA findings; QA gets the last two';
23
30
 
24
31
  /* ---------- pure ---------- */
25
- // filter = { severity: 'all' | P0..P3, status: 'all' | 'open' (default) | STATUSES, run: '' | run id, reviewer: '', path: '' (substring),
26
- // since: 0 (days, 0 = any), shadow: false }
32
+ // filter = { severity: 'all' | P0..P3, status: 'all' | 'open' (default: open and to-file) | STATUSES, tag: '' | a tag, run: '' | run id,
33
+ // reviewer: '', path: '' (substring), since: 0 (days, 0 = any), shadow: false, fp: '' (one finding, by its record key; set by a triage card) }
27
34
  function filterFindings(rows, filter, now) {
28
35
  const f = filter || {}, sev = f.severity || 'all', status = f.status || 'open', path = String(f.path || '').toLowerCase();
29
36
  const since = Number(f.since) > 0 ? (now || Date.now() / 1000) - Number(f.since) * 86400 : null;
30
- return list(rows).filter(r => (f.shadow || r.kind !== 'shadow')
31
- && (sev === 'all' || r.severity === sev) && (status === 'all' || r.status === status)
32
- && (!f.run || r.run_id === f.run) && (!f.reviewer || r.reviewer === f.reviewer)
37
+ return list(rows).filter(r => (f.shadow || r.kind !== 'shadow' || status === 'shadow')
38
+ && (sev === 'all' || r.severity === sev)
39
+ && (status === 'all' || (status === 'open' ? OPEN.includes(r.status) : r.status === status))
40
+ && (!f.tag || list(r.tags).includes(f.tag))
41
+ && (!f.run || r.run_id === f.run) && (!f.reviewer || r.reviewer === f.reviewer) && (!f.fp || r.record_fp === f.fp)
33
42
  && (!path || String(r.location || '').toLowerCase().includes(path))
34
43
  && (since === null || (Number.isFinite(r.at) && r.at >= since)));
35
44
  }
@@ -114,6 +123,88 @@
114
123
  if (!list(data.learnings).length && !list(data.sources).some(s => s.memory)) return 'No memories yet: forge has recorded no learning for this repository.';
115
124
  return null;
116
125
  }
126
+ const MEMORY_CATEGORIES = ['verify', 'trap', 'finding'];
127
+ const MEMORY_TEXT_MAX = 300;
128
+ const MEMORY_PATH_MAX = 300;
129
+ const MEMORY_PATHS_MAX = 20;
130
+ const MEMORY_KEY_MAX = 256;
131
+ const MEMORY_KEY_RE = /^[^:\s-][^:]*:.+$/;
132
+ const MEMORY_CONTROL_RE = /[\u0000-\u001f\u007f]/;
133
+ function memoryTextError(text) {
134
+ if (typeof text !== 'string' || MEMORY_CONTROL_RE.test(text) || text.length < 1 || text.length > MEMORY_TEXT_MAX)
135
+ return 'text must be one line of 1 to 300 characters';
136
+ return '';
137
+ }
138
+ function memoryPathError(path) {
139
+ if (typeof path !== 'string' || !path || path.length > MEMORY_PATH_MAX) return 'a path is at most 300 characters';
140
+ if (MEMORY_CONTROL_RE.test(path) || /[,[\]]/.test(path)) return 'a path must not contain a comma, a bracket or a control character';
141
+ if (path.startsWith('/') || path.startsWith('\\')) return 'a path must be relative';
142
+ if (path.split(/[\\/]/).includes('..')) return 'a path must not contain ..';
143
+ return '';
144
+ }
145
+ // `value` is a list or a comma-separated line. Empty means no paths.
146
+ function memoryPaths(value) {
147
+ if (value == null || value === '') return { paths: [] };
148
+ let items = value;
149
+ if (typeof value === 'string') items = value.split(',').map(part => part.trim()).filter(Boolean);
150
+ if (!Array.isArray(items)) return { error: 'paths must be a list of relative paths' };
151
+ if (items.length > MEMORY_PATHS_MAX) return { error: 'at most 20 paths' };
152
+ const paths = [];
153
+ for (const item of items) {
154
+ const path = typeof item === 'string' ? item.trim() : item;
155
+ const error = memoryPathError(path);
156
+ if (error) return { error };
157
+ if (!paths.includes(path)) paths.push(path);
158
+ }
159
+ return { paths };
160
+ }
161
+ // The POST body for memories/add: {body} or {error}. `input` is {category, text, paths?, path?}.
162
+ function memoryAddBody(input) {
163
+ const o = input || {};
164
+ const category = typeof o.category === 'string' ? o.category : '';
165
+ if (!MEMORY_CATEGORIES.includes(category)) return { error: 'category must be verify, trap or finding' };
166
+ const textError = memoryTextError(o.text);
167
+ if (textError) return { error: textError };
168
+ const parsed = memoryPaths(o.paths);
169
+ if (parsed.error) return { error: parsed.error };
170
+ const body = { category, text: o.text };
171
+ if (parsed.paths.length) body.paths = parsed.paths;
172
+ if (typeof o.path === 'string' && o.path) body.path = o.path;
173
+ return { body };
174
+ }
175
+ // The POST body for memories/edit: {body} or {error}. The checkout path, when there is one, is added by the page.
176
+ function memoryEditBody(key, text) {
177
+ if (typeof key !== 'string' || !key || key.length > MEMORY_KEY_MAX || MEMORY_CONTROL_RE.test(key) || !MEMORY_KEY_RE.test(key))
178
+ return { error: 'key must be category:key' };
179
+ const textError = memoryTextError(text);
180
+ if (textError) return { error: textError };
181
+ return { body: { key, text } };
182
+ }
183
+ // One argument for a POSIX shell. A safe word stays bare; quotes and `$` stay literal inside single quotes.
184
+ function shellQuote(value) {
185
+ const text = value == null ? '' : String(value);
186
+ if (text !== '' && /^[A-Za-z0-9_@%+=:,./-]+$/.test(text) && !text.startsWith('-')) return text;
187
+ return "'" + text.replace(/'/g, "'\\''") + "'";
188
+ }
189
+ // `forge memory add|edit <checkout> …`, shell-quoted, for a person to copy. Not the argv the server runs.
190
+ function memoryCommand(op, checkout, input) {
191
+ const o = input || {};
192
+ const head = ['forge memory', op, shellQuote(checkout == null ? '' : checkout)];
193
+ if (op === 'edit') {
194
+ head.push(shellQuote(o.key == null ? 'category:key' : o.key), '--text', shellQuote(o.text == null ? 'TEXT' : o.text));
195
+ } else {
196
+ head.push('--category', shellQuote(o.category || 'verify'), '--text', shellQuote(o.text == null ? 'TEXT' : o.text));
197
+ for (const path of list(o.paths)) head.push('--path', shellQuote(path));
198
+ }
199
+ return head.join(' ');
200
+ }
201
+ // `manual` is set when a person wrote a row. The projects answer keeps each row's role and may omit the flag;
202
+ // forge sets the flag for exactly the role `person`.
203
+ function learningManual(row) {
204
+ if (!row) return false;
205
+ if (row.manual === true) return true;
206
+ return list(row.rows).some(item => item && item.role === 'person');
207
+ }
117
208
  // A summary without what its own columns show: the bullet, the [P1][CONFIRMED] tags and a leading location.
118
209
  function cleanSummary(text, location) {
119
210
  let s = String(text || '').replace(/^\s*(?:[-*+•]|\d+[.)])\s*/, '').replace(/\*\*/g, '');
@@ -133,9 +224,10 @@
133
224
  const when = t => Number.isFinite(t) ? new Date(t * 1000).toLocaleString() : '—';
134
225
  const guard = (region, draw) => { if (UI.guard) UI.guard(region, draw); else draw(); };
135
226
  const s = { id: ctx.id || null, tab: TABS.includes(ctx.tab) ? ctx.tab : 'runs', list: null, detail: null, findings: null, memories: null,
136
- ffilter: { severity: 'all', status: 'open', run: '', reviewer: '', path: '', since: 0, shadow: false },
227
+ ffilter: { severity: 'all', status: 'open', tag: '', run: '', reviewer: '', path: '', since: 0, shadow: false },
137
228
  mfilter: { category: 'all', state: 'all', text: '' }, source: null, checkout: '', error: null, seq: 0, timer: null,
138
- writes: false, picked: new Set(), forgetNote: null, forgetting: false, forgetEpoch: 0, forgetHost: null };
229
+ writes: false, picked: new Set(), forgetNote: null, forgetting: false, forgetEpoch: 0, forgetHost: null,
230
+ fsel: new Set(), acting: false, actEpoch: 0, actHost: null, actResult: null, triage: {}, triagePanel: null };
139
231
  const tablePrefs = id => ctx.tablePrefs ? ctx.tablePrefs(id) : null, savePrefs = id => p => ctx.saveTablePrefs && ctx.saveTablePrefs(id, p);
140
232
 
141
233
  function table(parent, id, label, columns, rows, extra) {
@@ -161,7 +253,24 @@
161
253
  }
162
254
  }
163
255
  }
256
+ // The same for a finding action (a confirm, or the drafts being made for File selected).
257
+ function abandonAct() {
258
+ if (!s.acting) return;
259
+ const host = s.actHost;
260
+ s.acting = false;
261
+ s.actEpoch += 1;
262
+ s.actHost = null;
263
+ dismissConfirm(host);
264
+ }
265
+ // The triage panel's polling and its confirm end with the draw that made it.
266
+ function abandonTriage() {
267
+ const panel = s.triagePanel;
268
+ s.triagePanel = null;
269
+ if (panel) panel.stop();
270
+ }
164
271
  function abandonForget() {
272
+ abandonTriage();
273
+ abandonAct();
165
274
  if (!s.forgetting) return;
166
275
  const host = s.forgetHost;
167
276
  s.forgetting = false;
@@ -261,12 +370,27 @@
261
370
  }
262
371
 
263
372
  /* Findings */
373
+ function copyButton(command) {
374
+ const b = el('button', 'Copy', 'fnd-copy'); b.type = 'button'; b.setAttribute('aria-label', 'Copy: ' + command);
375
+ b.addEventListener('click', async () => {
376
+ try { await navigator.clipboard.writeText(command); b.textContent = 'Copied'; } catch (_) { b.textContent = 'Copy failed: select it'; }
377
+ setTimeout(() => { b.textContent = 'Copy'; }, 2500);
378
+ });
379
+ return b;
380
+ }
264
381
  function drawFindings(body, note) {
265
382
  abandonForget();
266
383
  const d = s.findings;
267
384
  if (!d) { fill(note, []); body.replaceChildren(el('p', s.ferror ? `Could not read the findings (${s.ferror}).` : 'Reading every review of every run… the first read parses each reply, so it can take a few seconds.', s.ferror ? 'warn' : 'muted')); return; }
268
- fill(note, list(d.notes).concat(d.dataset_runs ? [`${d.dataset_runs} run(s) whose directory is gone are read from the dataset: their findings link to no run page or diff.`] : []));
385
+ const lines = list(d.notes).concat(d.dataset_runs ? [`${d.dataset_runs} run(s) whose directory is gone are read from the dataset: their findings link to no run page or diff.`] : []);
386
+ if (d.issues_online && Number.isFinite(d.issues_read_at)) lines.push(`issue states read from GitHub at ${when(d.issues_read_at)}`);
387
+ else if (!d.issues_online && !lines.some(n => /GitHub/.test(String(n)))) lines.push('issue states were not read from GitHub (offline): filed findings may show as open');
388
+ fill(note, lines);
269
389
  const rows = list(d.rows);
390
+ const have = new Set(rows.map(r => r.record_fp));
391
+ for (const fp of [...s.fsel]) if (!have.has(fp)) s.fsel.delete(fp);
392
+ const tags = A.tagsIn(rows);
393
+ if (s.ffilter.tag && !tags.includes(s.ffilter.tag)) s.ffilter.tag = '';
270
394
  const bar = el('div', undefined, 'prj-filters');
271
395
  const select = (name, text, options) => {
272
396
  const l = el('label', undefined, 'fnd-field'), sel = el('select'); sel.dataset.filter = name;
@@ -276,7 +400,9 @@
276
400
  l.append(el('span', text, 'plate'), sel); bar.append(l);
277
401
  };
278
402
  const counts = {}; for (const r of rows) counts[r.status] = (counts[r.status] || 0) + 1;
279
- select('status', 'Status', [['all', 'all']].concat(STATUSES.map(x => [x, `${x} (${counts[x] || 0})`])));
403
+ const countOf = x => x === 'open' ? OPEN.reduce((n, k) => n + (counts[k] || 0), 0) : counts[x] || 0;
404
+ select('status', 'Status', [['all', 'all']].concat(STATUSES.map(x => [x, `${x} (${countOf(x)})`])));
405
+ select('tag', 'Tag', [['', 'all']].concat(tags.map(t => [t, t])));
280
406
  select('severity', 'Severity', [['all', 'all']].concat(SEVERITIES.map(x => [x, x])));
281
407
  select('run', 'Run', [['', 'all']].concat(Array.from(new Set(rows.map(r => r.run_id).filter(Boolean))).sort().map(x => [x, x])));
282
408
  select('reviewer', 'Reviewer', [['', 'all']].concat(Array.from(new Set(rows.map(r => r.reviewer).filter(Boolean))).sort().map(x => [x, x])));
@@ -290,34 +416,278 @@
290
416
  const again = readAgain(() => loadTab(true));
291
417
  bar.append(again);
292
418
  const count = el('p', '', 'muted prj-count'), tableHost = el('div', undefined, 'prj-table');
293
- body.replaceChildren(bar, count, tableHost);
419
+ const formHost = el('div', undefined, 'fnd-form'), actHost = el('div', undefined, 'fnd-confirm'), noteHost = el('div', undefined, 'fnd-result');
420
+ s.actHost = actHost;
421
+ const triageHost = el('div', undefined, 'triage-host');
422
+ if (T) {
423
+ s.triagePanel = T.render(triageHost, {
424
+ id: s.id, root: s.detail && s.detail.root, writes: s.writes, store: s.triage, reload: () => { if (s.tab === 'findings') loadTab(true); },
425
+ openCount: () => rows.filter(r => OPEN.includes(r.status) && r.kind !== 'shadow').length,
426
+ rows: () => rows,
427
+ show: fp => { s.ffilter = { severity: 'all', status: 'all', tag: '', run: '', reviewer: '', path: '', since: 0, shadow: true, fp }; drawFindings(body, note); },
428
+ });
429
+ }
430
+ if (s.actResult) { UI.outcome(noteHost, s.actResult.res, s.actResult.text, { silent: true }); s.actResult = null; } // shown once
431
+ const shownNow = () => filterFindings(rows, s.ffilter);
432
+ const selectedNow = () => A.selectedRows(shownNow(), s.fsel);
433
+
434
+ /* the write controls */
435
+ let allBox = null, picked = null;
436
+ const opButtons = {};
437
+ function syncBar() {
438
+ if (!picked) return;
439
+ const sel = selectedNow(), ok = A.allowed(sel);
440
+ picked.textContent = ok.why || `${ok.count} selected`;
441
+ for (const [op, b] of Object.entries(opButtons)) b.disabled = s.acting || !ok[op];
442
+ const shown = shownNow().filter(A.selectable);
443
+ allBox.checked = shown.length > 0 && shown.every(r => s.fsel.has(r.record_fp));
444
+ allBox.disabled = !shown.length;
445
+ }
446
+ const closeForm = () => formHost.replaceChildren();
447
+ // Confirm, post, and show what the route said. Copies forgetSelected's guard: a redraw (Read again, another tab)
448
+ // drops this strip, so its epoch is retired, the controls are usable again, and a request already sent keeps its result.
449
+ async function perform(op, fps, request) {
450
+ if (s.acting) { UI.outcome(noteHost, { ok: false, status: 409, error: 'busy', detail: 'another action is waiting for its confirm' }); return; }
451
+ const epoch = s.actEpoch, host = actHost, current = () => epoch === s.actEpoch && host.isConnected;
452
+ s.acting = true; s.actResult = null; s.actHost = host; syncBar();
453
+ noteHost.replaceChildren();
454
+ for (const child of [...host.children]) child.remove();
455
+ try {
456
+ const yes = await UI.confirmInline(host, A.confirmText(op, fps.length, request), {});
457
+ if (!current() || !yes) return;
458
+ const res = await UI.post(A.pathOf(s.id, op), request);
459
+ s.actResult = { res, text: `${fps.length} finding${fps.length === 1 ? '' : 's'} ${A.PAST[op]}` };
460
+ if (res && res.ok) for (const fp of fps) s.fsel.delete(fp);
461
+ if (!current()) { if (s.tab === 'findings') await loadTab(true); return; }
462
+ if (!res || !res.ok) { s.actResult = null; UI.outcome(noteHost, res); return; } // shown here, not again on a redraw
463
+ closeForm();
464
+ s.acting = false;
465
+ await loadTab(true);
466
+ } finally {
467
+ if (epoch === s.actEpoch) { s.acting = false; if (host.isConnected) syncBar(); }
468
+ }
469
+ }
470
+ const textInput = (ph, max) => { const i = el('input'); i.type = 'text'; i.placeholder = ph; if (max) i.maxLength = max; return i; };
471
+ const field = (label, input) => { const l = el('label', undefined, 'fnd-field'); l.append(el('span', label, 'plate'), input); return l; };
472
+ function openForm(op, row) {
473
+ const fpsNow = () => row ? [row.record_fp] : A.fpsOf(selectedNow());
474
+ if (op === 'reopen') { const fps = fpsNow(), built = A.bodyFor(op, fps, {}); if (built.error) UI.outcome(noteHost, { ok: false, error: built.error }); else perform(op, fps, built.body); return; }
475
+ closeForm();
476
+ let collect = () => ({}), first = null;
477
+ const parts = [], heading = el('p', undefined, 'fnd-form-title');
478
+ if (op === 'fix') {
479
+ const c = textInput('7 to 40 hex characters'), r = textInput('why (optional with a commit)', 500); first = c;
480
+ parts.push(field('Commit', c), field('Reason', r)); collect = () => ({ commit: c.value, reason: r.value });
481
+ heading.textContent = 'Mark fixed: give a commit, a reason, or both';
482
+ } else if (op === 'dismiss') {
483
+ const r = textInput('why it needs no work', 500); first = r;
484
+ parts.push(field('Reason (required)', r)); collect = () => ({ reason: r.value });
485
+ heading.textContent = 'Dismiss: say why';
486
+ } else if (op === 'to-file') {
487
+ const t = textInput('issue title (optional)', 200); first = t;
488
+ parts.push(field('Title', t)); collect = () => ({ title: t.value });
489
+ heading.textContent = 'Mark to file: keep a draft issue for these findings';
490
+ } else if (op === 'dup') {
491
+ const sel = el('select'); first = sel;
492
+ const mine = fpsNow()[0];
493
+ for (const r of shownNow().filter(x => A.selectable(x) && x.record_fp !== mine)) {
494
+ const o = el('option', `${r.severity || '—'} ${cleanSummary(r.summary, r.location).slice(0, 90)} · ${r.record_fp}`); o.value = r.record_fp; sel.append(o);
495
+ }
496
+ if (!sel.children.length) parts.push(el('p', 'No other finding is shown: widen the filters to pick the original.', 'muted'));
497
+ else { parts.push(field('Duplicate of', sel)); collect = () => ({ of: sel.value }); }
498
+ heading.textContent = 'Mark duplicate: pick the finding it repeats';
499
+ } else if (op === 'tag') {
500
+ const t = textInput('tags, comma separated'), m = el('select'); first = t;
501
+ for (const [v, x] of [['add', 'Add'], ['remove', 'Remove']]) { const o = el('option', x); o.value = v; m.append(o); }
502
+ parts.push(field('Tags', t), field('Action', m)); collect = () => ({ tags: t.value, remove: m.value === 'remove' });
503
+ heading.textContent = 'Tags: lowercase, digits and dashes, at most 8';
504
+ } else if (op === 'note') {
505
+ const t = el('textarea'); t.rows = 3; t.maxLength = 2000; t.placeholder = 'a note (empty clears it)'; t.value = row && row.record && row.record.note || ''; first = t;
506
+ parts.push(field('Note', t)); collect = () => ({ text: t.value });
507
+ heading.textContent = 'Note on ' + (row ? cleanSummary(row.summary, row.location).slice(0, 80) : 'the finding');
508
+ } else if (op === 'edit') {
509
+ const sv = el('select'), t = el('textarea'); first = sv; t.rows = 4; t.maxLength = 4000;
510
+ const was = row && row.record && row.record.edit && row.record.edit.text || (row && (row.text || row.summary)) || '';
511
+ t.value = was;
512
+ for (const v of [''].concat(SEVERITIES)) { const o = el('option', v || 'keep'); o.value = v; sv.append(o); }
513
+ sv.value = '';
514
+ parts.push(field('Severity', sv), field('Text', t));
515
+ collect = () => ({ severity: sv.value, text: t.value === was ? undefined : t.value });
516
+ heading.textContent = 'Edit ' + (row ? cleanSummary(row.summary, row.location).slice(0, 80) : 'the finding') + (row && row.severity ? ` (now ${row.severity})` : '');
517
+ }
518
+ const msg = el('p', undefined, 'warn fnd-form-msg');
519
+ const apply = () => {
520
+ const fps = fpsNow(), built = A.bodyFor(op, fps, collect());
521
+ if (built.error) { msg.textContent = built.error; return; }
522
+ msg.textContent = '';
523
+ perform(op, fps, built.body);
524
+ };
525
+ const go = el('button', 'Apply', 'primary'); go.type = 'button'; go.addEventListener('click', apply);
526
+ const cancel = el('button', 'Cancel'); cancel.type = 'button'; cancel.addEventListener('click', closeForm);
527
+ const wrap = el('div', undefined, 'fnd-form-body');
528
+ wrap.append(...parts, go, cancel);
529
+ wrap.addEventListener('keydown', e => {
530
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeForm(); }
531
+ else if (e.key === 'Enter' && e.target && e.target.tagName === 'INPUT') { e.preventDefault(); apply(); }
532
+ });
533
+ formHost.append(heading, wrap, msg);
534
+ if (first && first.focus) first.focus();
535
+ }
536
+ // File selected: drafts for exactly the chosen findings, a dialog, and the POST only after its confirm.
537
+ async function fileSelected() {
538
+ const FF = root.ForgeFindings;
539
+ if (s.acting || !FF) return;
540
+ const sel = selectedNow(), fps = A.fileableFps(sel), key = A.fileRun(sel);
541
+ if (!fps.length || !key) return;
542
+ const epoch = s.actEpoch;
543
+ s.acting = true; s.actResult = null; s.actHost = actHost; noteHost.replaceChildren(); syncBar();
544
+ let res;
545
+ try { res = await UI.get(FF.issuesUrl(key, { scope: 'repo', offline: false, plausible: true, only: fps })); }
546
+ finally { if (epoch === s.actEpoch) { s.acting = false; if (actHost.isConnected) syncBar(); } }
547
+ if (!res || !res.ok) {
548
+ if (epoch === s.actEpoch && actHost.isConnected) UI.outcome(noteHost, res); else s.actResult = { res };
549
+ return;
550
+ }
551
+ fileDialog(FF, key, fps, list(res.data && res.data.drafts));
552
+ }
553
+ function fileDialog(FF, key, fps, drafts) {
554
+ const dlg = el('dialog', undefined, 'fnd-dialog'); dlg.setAttribute('aria-label', 'File issues on GitHub');
555
+ document.body.append(dlg);
556
+ let posting = false;
557
+ const cleanup = () => { dlg.remove(); };
558
+ const shut = () => { if (typeof dlg.close === 'function') dlg.close(); else cleanup(); };
559
+ dlg.addEventListener('close', cleanup);
560
+ dlg.addEventListener('click', e => { if (e.target === dlg && !posting) shut(); });
561
+ dlg.addEventListener('cancel', e => { if (posting) e.preventDefault(); });
562
+ dlg.append(el('h2', 'File issues on GitHub'));
563
+ const warn = el('p', undefined, 'fnd-warn');
564
+ warn.append(el('i', undefined, 'lamp st-running'), el('span', `This creates ${drafts.length} issue${drafts.length === 1 ? '' : 's'} on this repository's GitHub project, from your gh login, and cannot be undone from here.`));
565
+ dlg.append(warn);
566
+ if (!drafts.length) dlg.append(el('p', 'forge has no draft for this selection (its findings may be filed already).', 'muted'));
567
+ for (const dr of drafts) {
568
+ const art = el('article', undefined, 'fnd-draft'), h = el('h3', undefined, 'fnd-draft-title');
569
+ h.append(el('span', dr.severity || '—', 'chip sev-chip sev-' + (SEVERITIES.includes(dr.severity) ? dr.severity : 'none')), el('span', dr.title || 'untitled'));
570
+ art.append(h);
571
+ if (dr.same_title) {
572
+ const url = FF.safeUrl(dr.same_title), p = el('p', undefined, 'fnd-same');
573
+ p.append(el('i', undefined, 'lamp fnd-amber'), el('span', 'An open issue with this title exists already: '));
574
+ if (url) { const a = el('a', url); a.href = url; a.target = '_blank'; a.rel = 'noopener noreferrer'; p.append(a); } else p.append(el('span', String(dr.same_title)));
575
+ p.append(el('span', '. forge skips it.')); art.append(p);
576
+ }
577
+ art.append(el('pre', dr.body || '', 'fnd-body')); dlg.append(art);
578
+ }
579
+ const labels = el('input'); labels.type = 'text'; labels.placeholder = 'bug, forge (optional, comma separated)';
580
+ const labelNote = el('p', undefined, 'warn fnd-label-note'); labelNote.hidden = true;
581
+ const results = el('div', undefined, 'fnd-results');
582
+ const go = el('button', 'File on GitHub', 'primary'), cancel = el('button', 'Cancel'); go.type = 'button'; cancel.type = 'button';
583
+ go.disabled = !drafts.length;
584
+ cancel.addEventListener('click', shut);
585
+ go.addEventListener('click', async () => {
586
+ const parsed = FF.parseLabels(labels.value);
587
+ labelNote.hidden = !parsed.error; labelNote.textContent = parsed.error || '';
588
+ if (parsed.error) return;
589
+ go.disabled = true; cancel.disabled = true; labels.disabled = true; results.replaceChildren(); posting = true;
590
+ const res = await UI.post(FF.issuesPath(key), FF.fileBody('repo', fps, true, parsed.labels));
591
+ posting = false;
592
+ if (!res || !res.ok) { go.disabled = false; cancel.disabled = false; labels.disabled = false; UI.outcome(results, res); return; }
593
+ const made = FF.resultLines(res.data.created), ul = el('ul', undefined, 'fnd-created');
594
+ for (const ln of made) {
595
+ const li = el('li', undefined, 'fnd-created-' + ln.kind), url = FF.safeUrl(ln.url);
596
+ li.append(el('i', undefined, 'lamp ' + (ln.kind === 'created' ? 'st-pass' : 'fnd-amber')));
597
+ if (url) { const a = el('a', ln.text); a.href = url; a.target = '_blank'; a.rel = 'noopener noreferrer'; li.append(a); } else li.append(el('span', ln.text));
598
+ ul.append(li);
599
+ }
600
+ results.replaceChildren(el('p', `${made.filter(l => l.kind === 'created').length} created`, 'fnd-done'), ul);
601
+ for (const n of FF.emptyNotes(res.data.created, res.data.notes)) results.append(el('p', n, 'muted fnd-result-note'));
602
+ go.remove(); cancel.textContent = 'Close'; cancel.disabled = false;
603
+ for (const r of list(s.findings && s.findings.rows)) if (fps.includes(r.record_fp)) s.fsel.delete(r.record_fp);
604
+ if (s.tab === 'findings') loadTab(true);
605
+ });
606
+ const actions = el('div', undefined, 'fnd-dialog-actions'); actions.append(cancel, go);
607
+ const labelField = el('label', undefined, 'fnd-field'); labelField.append(el('span', 'Labels', 'plate'), labels);
608
+ dlg.append(labelField, labelNote, results, actions);
609
+ if (typeof dlg.showModal === 'function') dlg.showModal(); else dlg.setAttribute('open', '');
610
+ (drafts.length ? go : cancel).focus();
611
+ }
612
+
613
+ if (s.writes) {
614
+ const abar = el('div', undefined, 'fnd-actions prj-actions');
615
+ const lab = el('label', undefined, 'fnd-toggle');
616
+ allBox = el('input'); allBox.type = 'checkbox'; allBox.setAttribute('aria-label', 'Select all shown findings');
617
+ lab.append(allBox, el('span', 'Select all'));
618
+ picked = el('span', '0 selected', 'muted fnd-picked');
619
+ allBox.addEventListener('change', () => {
620
+ for (const r of shownNow()) { if (!A.selectable(r)) continue; if (allBox.checked) s.fsel.add(r.record_fp); else s.fsel.delete(r.record_fp); }
621
+ drawTable();
622
+ });
623
+ abar.append(lab, picked);
624
+ for (const [op, text] of [['fix', 'Mark fixed'], ['dismiss', 'Dismiss'], ['reopen', 'Reopen'], ['to-file', 'Mark to file'], ['dup', 'Duplicate of…'], ['tag', 'Tags…']]) {
625
+ const b = el('button', text); b.type = 'button'; b.dataset.op = op; b.disabled = true;
626
+ b.addEventListener('click', () => openForm(op)); opButtons[op] = b; abar.append(b);
627
+ }
628
+ const fileKey = el('button', 'File selected', 'primary'); fileKey.type = 'button'; fileKey.dataset.op = 'file'; fileKey.disabled = true;
629
+ fileKey.title = 'creates GitHub issues for the selected findings that forge issues can file (at most ' + A.MAX_FILE + ')';
630
+ fileKey.addEventListener('click', () => { fileSelected(); }); opButtons.file = fileKey; abar.append(fileKey);
631
+ body.replaceChildren(triageHost, bar, abar, formHost, actHost, noteHost, count, tableHost);
632
+ } else body.replaceChildren(triageHost, bar, count, tableHost);
633
+
634
+ /* the table */
294
635
  const summaryCell = r => {
295
636
  const wrap = el('div', undefined, 'fnd-summary'), line = el('div', undefined, 'fnd-summary-line');
296
637
  const more = el('button', undefined, 'fnd-more'); more.type = 'button'; more.setAttribute('aria-expanded', 'false'); more.setAttribute('aria-label', 'Show the full text');
297
638
  more.append(el('span', '▸', 'fnd-caret'));
298
639
  const detail = el('div', undefined, 'fnd-detail'); detail.hidden = true;
299
640
  detail.append(el('pre', r.text || r.summary || '', 'fnd-text'));
641
+ const rec = r.record || {};
642
+ for (const [k, label] of [['reason', 'reason'], ['commit', 'fixed by'], ['duplicate_of', 'duplicate of'], ['issue', 'issue'], ['note', 'note']]) {
643
+ if (rec[k] != null && String(rec[k]) !== '') detail.append(el('p', `${label}: ${rec[k]}`, 'fnd-rec'));
644
+ }
300
645
  if (list(r.occurrences).length > 1) {
301
646
  const ul = el('ul', undefined, 'prj-occ');
302
647
  for (const o of r.occurrences) { const li = el('li'); const t = `${o.run_id || '—'} · ${o.task || 'final review'} · attempt ${o.attempt == null ? '—' : o.attempt} · ${o.reviewer || '—'} · ${when(o.at)}`; if (o.href) { const a = el('a', t); a.href = o.href; li.append(a); } else li.append(el('span', t)); ul.append(li); }
303
648
  detail.append(el('p', `Seen ${r.count} times, the newest first in the row:`, 'muted'), ul);
304
649
  }
650
+ if (!s.writes) {
651
+ const cmds = A.commandsFor(s.detail && s.detail.root, r), cbox = el('div', undefined, 'fnd-cmds');
652
+ if (!cmds.length) cbox.append(el('p', 'This finding has no record key, so forge cannot change it.', 'muted'));
653
+ else {
654
+ cbox.append(el('p', 'This page is read-only. Change this finding from a terminal:', 'muted'));
655
+ for (const c of cmds) { const rowEl = el('div', undefined, 'fnd-cmd'), code = el('code', c.command, 'mono'); code.tabIndex = 0; code.title = c.label; rowEl.append(code, copyButton(c.command)); cbox.append(rowEl); }
656
+ }
657
+ detail.append(cbox);
658
+ }
305
659
  more.addEventListener('click', () => { const open = detail.hidden; detail.hidden = !open; more.setAttribute('aria-expanded', String(open)); more.firstChild.textContent = open ? '▾' : '▸'; });
306
660
  line.append(more, el('span', cleanSummary(r.summary, r.location) || '—', 'prj-summary'));
307
661
  if (r.count > 1) line.append(el('span', `×${r.count}`, 'chip prj-count-chip'));
308
- wrap.append(line, detail); return wrap;
662
+ wrap.append(line);
663
+ if (list(r.tags).length) {
664
+ const chips = el('div', undefined, 'fnd-tags'), derived = A.derivedTags(r);
665
+ for (const t of r.tags) {
666
+ const c = el('span', t, 'fnd-tag' + (derived ? ' fnd-tag-derived' : '')); if (derived) c.title = 'derived from the path';
667
+ chips.append(c);
668
+ }
669
+ wrap.append(chips);
670
+ }
671
+ wrap.append(detail); return wrap;
309
672
  };
310
673
  const statusCell = r => {
311
674
  const b = el('span', undefined, 'fnd-status fnd-' + r.status);
312
- b.append(el('i', undefined, 'lamp ' + (r.status === 'open' ? 'lamp-off' : r.status === 'filed' ? 'fnd-amber' : r.status === 'superseded' ? 'st-outdated' : r.status === 'dismissed' ? 'lamp-off' : 'st-pass')), el('span', r.status));
675
+ b.append(el('i', undefined, 'lamp fnd-lamp-' + r.status + ' ' + (LAMPS[r.status] || 'lamp-off')), el('span', r.status));
313
676
  if (r.status === 'superseded') b.title = 'a later review of the same task passed; that does not say this finding was fixed';
677
+ else if (r.status === 'to-file') b.title = 'marked to file as a GitHub issue: still open work';
678
+ else if (r.status === 'unlabelled') b.title = 'the finding has no usable label, so forge cannot say what it is';
314
679
  return b;
315
680
  };
316
681
  const whereCell = r => {
317
682
  if (r.source === 'dataset') { const x = el('span', 'from the dataset', 'chip st-unknown'); x.title = 'its run directory is gone: no run page or diff to open'; return x; }
318
683
  const box = el('span', undefined, 'prj-where');
319
684
  if (r.href) { const a = el('a', 'diff'); a.href = r.href; a.title = 'open the diff at this finding'; box.append(a); }
320
- if (r.fileable && s.writes) { const f = el('a', 'file or dismiss'); f.href = '#/runs/' + encodeURIComponent(r.run) + '/findings'; f.title = 'on the run\'s Open findings page, through forge issues'; box.append(document.createTextNode(' · '), f); }
685
+ if (s.writes && A.selectable(r)) {
686
+ for (const op of ['note', 'edit']) {
687
+ const b = el('button', op === 'note' ? 'Note' : 'Edit', 'fnd-rowbtn'); b.type = 'button'; b.dataset.op = op; b.title = op === 'note' ? 'add or change a note' : 'change the severity or the text';
688
+ b.addEventListener('click', () => openForm(op, r)); box.append(document.createTextNode(' '), b);
689
+ }
690
+ }
321
691
  return box;
322
692
  };
323
693
  const runCell = r => { if (!r.run) return r.run_id || '—'; const a = el('a', r.run_id || r.run, 'mono'); a.href = ctx.runHref(r.run); return a; };
@@ -334,9 +704,21 @@
334
704
  { id: 'status', label: 'Status', value: r => STATUSES.indexOf(r.status), cell: statusCell },
335
705
  { id: 'open', label: 'Open', sortable: false, cell: whereCell },
336
706
  ];
707
+ if (s.writes) columns.unshift({ id: 'pick', label: '', title: 'Select', sortable: false, hideable: false, cell: r => {
708
+ if (!A.selectable(r)) { const n = el('span', '—', 'muted'); n.title = 'this finding has no record key: forge cannot change it'; return n; }
709
+ const cb = el('input'); cb.type = 'checkbox'; cb.checked = s.fsel.has(r.record_fp); cb.setAttribute('aria-label', 'Select finding ' + r.record_fp);
710
+ cb.addEventListener('change', () => { if (cb.checked) s.fsel.add(r.record_fp); else s.fsel.delete(r.record_fp); syncBar(); });
711
+ return cb;
712
+ } });
337
713
  function drawTable() {
338
- const shown = filterFindings(rows, s.ffilter);
714
+ const shown = shownNow();
339
715
  count.textContent = `${shown.length} of ${rows.length} findings`;
716
+ if (s.ffilter.fp) {
717
+ const all = el('button', 'Show all findings'); all.type = 'button'; all.dataset.op = 'clear-fp';
718
+ all.addEventListener('click', () => { s.ffilter = { severity: 'all', status: 'open', tag: '', run: '', reviewer: '', path: '', since: 0, shadow: false, fp: '' }; drawFindings(body, note); });
719
+ count.append(document.createTextNode(` · only ${s.ffilter.fp} `), all);
720
+ }
721
+ syncBar();
340
722
  if (!shown.length) { tableHost.replaceChildren(el('p', rows.length ? 'No findings match these filters.' : 'No review of this repository wrote a finding.', 'muted')); return; }
341
723
  table(tableHost, 'project-findings', 'Findings', columns, shown, { className: 'fnd-grid prj-findings' });
342
724
  }
@@ -360,8 +742,193 @@
360
742
  }
361
743
  bar.append(readAgain(() => loadTab(true)));
362
744
  const parts = [bar];
745
+ const learnings = list(d.learnings);
746
+ const shownNow = () => filterLearnings(learnings, s.mfilter, s.source);
747
+ let allBox = null, forget = null, addButton = null, saveEdit = null, editButtons = [];
748
+ const faction = el('div'), noteHost = el('div'); faction.append(noteHost);
749
+ s.forgetHost = faction;
750
+ const editHost = el('div', undefined, 'prj-edit');
751
+ const lcount = el('p', '', 'muted prj-count'), lhost = el('div', undefined, 'prj-table');
752
+ const checkoutOf = () => s.source || (s.detail && s.detail.root) || '';
753
+ const writeCheckouts = () => s.source ? [s.source] : list(d.sources).map(item => item && item.path).filter(Boolean);
754
+ const whereText = targets => targets.length ? targets.join(', ') : 'every checkout of this project';
755
+ function commandLine(command) {
756
+ const rowEl = el('div', undefined, 'fnd-cmd'), code = el('code', command, 'mono');
757
+ code.tabIndex = 0; rowEl.append(code, copyButton(command)); return rowEl;
758
+ }
759
+ function terminalBox(intro, commands) {
760
+ const box = el('div', undefined, 'fnd-cmds');
761
+ box.append(el('p', intro, 'muted'));
762
+ for (const command of commands) box.append(commandLine(command));
763
+ return box;
764
+ }
765
+ function paintNote() { noteHost.replaceChildren(...list(s.forgetNote).map(line => el('p', line, 'muted'))); }
766
+ // Forget, Edit and Add share s.forgetting, so one confirm is the only write in flight.
767
+ function syncForget() {
768
+ const busy = s.forgetting;
769
+ if (forget) {
770
+ const keys = forgetKeys(shownNow(), s.picked);
771
+ forget.textContent = `Forget selected (${keys.length})`;
772
+ forget.disabled = busy || keys.length === 0;
773
+ if (allBox) {
774
+ const selectable = shownNow().map(learningKey).filter(Boolean);
775
+ allBox.checked = selectable.length > 0 && selectable.every(key => s.picked.has(key));
776
+ allBox.disabled = busy || selectable.length === 0;
777
+ }
778
+ }
779
+ if (addButton) addButton.disabled = busy;
780
+ if (saveEdit) saveEdit.disabled = busy;
781
+ for (const b of editButtons) b.disabled = busy || !b.dataset.key;
782
+ }
783
+ function memoryResultLines(op, res) {
784
+ const data = forgetData(res), verb = op === 'add' ? 'added' : 'edited';
785
+ if (!data) return [verb];
786
+ const lines = [];
787
+ for (const checkout of list(data.checkouts)) {
788
+ const where = checkout && checkout.path ? String(checkout.path) : 'checkout';
789
+ const result = checkout && checkout.result;
790
+ if (!result || result.ok === false) {
791
+ const err = checkout && checkout.error;
792
+ const why = typeof err === 'string' ? err : err && (err.detail || err.error);
793
+ lines.push(where + ': ' + (why || 'failed'));
794
+ continue;
795
+ }
796
+ lines.push(where + ': ' + verb + (result.key ? ' ' + result.key : ''));
797
+ }
798
+ return lines.length ? lines : [verb];
799
+ }
800
+ function memoryFailLine(op, res) {
801
+ return (op === 'add' ? 'Could not add: ' : 'Could not edit: ') + ((res && (res.detail || res.error)) || 'no answer');
802
+ }
803
+ // Same epoch guard as forgetSelected: a redraw retires this attempt, the new controls stay usable,
804
+ // and a request already sent keeps its result line.
805
+ async function commitMemory(op, request, sentence) {
806
+ if (s.forgetting) return;
807
+ const epoch = s.forgetEpoch, host = faction;
808
+ const current = () => epoch === s.forgetEpoch && host.isConnected;
809
+ s.forgetting = true; s.forgetNote = null; syncForget(); paintNote();
810
+ for (const child of [...host.children]) if (child !== noteHost) child.remove();
811
+ try {
812
+ const yes = await UI.confirmInline(host, sentence, {});
813
+ if (!current() || !yes) return;
814
+ const res = await UI.post('/api/projects/' + encodeURIComponent(s.id) + '/memories/' + op, request);
815
+ if (!current()) {
816
+ s.forgetNote = res && res.ok ? memoryResultLines(op, res) : [memoryFailLine(op, res)];
817
+ if (s.tab === 'memories') await loadTab(true);
818
+ return;
819
+ }
820
+ if (!res || !res.ok) { UI.outcome(host, res); return; }
821
+ s.forgetNote = memoryResultLines(op, res);
822
+ s.forgetting = false;
823
+ await loadTab(true);
824
+ } finally {
825
+ if (epoch !== s.forgetEpoch) return;
826
+ s.forgetting = false;
827
+ if (host.isConnected) syncForget();
828
+ }
829
+ }
830
+ function countedField(label, value, field) {
831
+ const input = el('input'); input.type = 'text'; input.value = value || ''; input.dataset.field = field;
832
+ input.setAttribute('aria-label', label);
833
+ const count = el('span', '', 'muted'); count.dataset.field = field + '-count';
834
+ const sync = () => {
835
+ const n = String(input.value || '').length;
836
+ count.textContent = n + '/300';
837
+ count.className = n > MEMORY_TEXT_MAX ? 'warn' : 'muted';
838
+ };
839
+ input.addEventListener('input', sync); sync();
840
+ const wrap = el('label', undefined, 'fnd-field');
841
+ wrap.append(el('span', label, 'plate'), input, count);
842
+ return { wrap, input };
843
+ }
844
+ function addConfirm(body, targets) {
845
+ const lines = ['Add this learning to ' + whereText(targets) + '?', body.category + ': ' + body.text];
846
+ if (body.paths && body.paths.length) lines.push('paths: ' + body.paths.join(', '));
847
+ return lines.join('\n');
848
+ }
849
+ function editConfirm(key, before, after, targets) {
850
+ return 'Change ' + key + ' in ' + whereText(targets) + '?\n' + before + ' → ' + after;
851
+ }
852
+ function buildAddForm() {
853
+ const form = el('div', undefined, 'prj-add');
854
+ form.append(el('h3', 'Add learning'));
855
+ const cat = el('select'); cat.dataset.field = 'add-category'; cat.setAttribute('aria-label', 'Category');
856
+ for (const name of MEMORY_CATEGORIES) { const o = el('option', name); o.value = name; cat.append(o); }
857
+ cat.value = 'verify';
858
+ const catLabel = el('label', undefined, 'fnd-field'); catLabel.append(el('span', 'Category', 'plate'), cat);
859
+ const text = countedField('Text', '', 'add-text');
860
+ const paths = el('input'); paths.type = 'text'; paths.placeholder = 'optional paths, comma separated';
861
+ paths.dataset.field = 'add-paths'; paths.setAttribute('aria-label', 'Paths');
862
+ const pathsLabel = el('label', undefined, 'fnd-field'); pathsLabel.append(el('span', 'Paths', 'plate'), paths);
863
+ const msg = el('p', '', 'warn');
864
+ addButton = el('button', 'Add learning', 'primary'); addButton.type = 'button';
865
+ const submit = () => {
866
+ if (s.forgetting) return;
867
+ const built = memoryAddBody({ category: cat.value, text: text.input.value, paths: paths.value, path: s.source || undefined });
868
+ if (built.error) { msg.textContent = built.error; return; }
869
+ msg.textContent = '';
870
+ commitMemory('add', built.body, addConfirm(built.body, writeCheckouts()));
871
+ };
872
+ addButton.addEventListener('click', submit);
873
+ const onEnter = e => { if (e.key === 'Enter') { e.preventDefault(); submit(); } };
874
+ text.input.addEventListener('keydown', onEnter);
875
+ paths.addEventListener('keydown', onEnter);
876
+ form.append(catLabel, text.wrap, pathsLabel, addButton, msg);
877
+ return form;
878
+ }
879
+ function openEdit(row) {
880
+ if (s.forgetting) return;
881
+ const key = learningKey(row);
882
+ if (!key) return;
883
+ const before = row.text == null ? '' : String(row.text);
884
+ editHost.replaceChildren();
885
+ const text = countedField('Text', before, 'edit-text');
886
+ const msg = el('p', '', 'warn');
887
+ saveEdit = el('button', 'Save', 'primary'); saveEdit.type = 'button';
888
+ const cancel = el('button', 'Cancel'); cancel.type = 'button'; cancel.setAttribute('aria-label', 'Cancel edit');
889
+ const close = () => { saveEdit = null; editHost.replaceChildren(); };
890
+ cancel.addEventListener('click', close);
891
+ const apply = () => {
892
+ if (s.forgetting) return;
893
+ const built = memoryEditBody(key, text.input.value);
894
+ if (built.error) { msg.textContent = built.error; return; }
895
+ if (s.source) built.body.path = s.source;
896
+ msg.textContent = '';
897
+ commitMemory('edit', built.body, editConfirm(key, before, built.body.text, writeCheckouts()));
898
+ };
899
+ saveEdit.addEventListener('click', apply);
900
+ text.input.addEventListener('keydown', e => {
901
+ if (e.key === 'Enter') { e.preventDefault(); apply(); }
902
+ else if (e.key === 'Escape') { e.preventDefault(); close(); }
903
+ });
904
+ editHost.append(el('p', 'Edit ' + key), text.wrap, saveEdit, cancel, msg);
905
+ if (text.input.focus) text.input.focus();
906
+ }
907
+ function rowCommands(r) {
908
+ const checkout = checkoutOf(), text = r.text == null ? '' : String(r.text), commands = [];
909
+ const key = learningKey(r);
910
+ if (key) commands.push(memoryCommand('edit', checkout, { key, text }));
911
+ if (MEMORY_CATEGORIES.includes(r.category)) commands.push(memoryCommand('add', checkout, { category: r.category, text }));
912
+ return commands.length ? terminalBox('This page is read-only. From a terminal:', commands) : null;
913
+ }
914
+ function learningCell(r) {
915
+ const box = el('div', undefined, 'prj-learning'), line = el('div');
916
+ line.append(el('span', r.text == null ? '' : String(r.text)));
917
+ if (learningManual(r)) { line.append(document.createTextNode(' '), el('span', 'added by a person', 'chip prj-manual')); }
918
+ box.append(line);
919
+ if (!s.writes) { const commands = rowCommands(r); if (commands) box.append(commands); }
920
+ return box;
921
+ }
363
922
  const empty = memoryEmpty(d);
364
- if (empty) { parts.push(el('p', empty, 'muted prj-empty')); body.replaceChildren(...parts); return; }
923
+ if (empty) {
924
+ parts.push(el('p', empty, 'muted prj-empty'));
925
+ paintNote();
926
+ if (s.writes) parts.push(buildAddForm());
927
+ else parts.push(terminalBox('This page is read-only. Add a learning from a terminal:', [memoryCommand('add', checkoutOf(), {})]));
928
+ parts.push(faction);
929
+ body.replaceChildren(...parts);
930
+ return;
931
+ }
365
932
  if (d.differs) parts.push(el('p', 'The checkouts\' memory.md files differ: pick a checkout to see what its runs are told.', 'warn prj-differs'));
366
933
  const src = sources.find(x => x.path === s.source);
367
934
  const given = el('section', undefined, 'prj-given');
@@ -384,9 +951,6 @@
384
951
  lsel('state', 'State', [['all', 'all']].concat(Object.entries(STATES).map(([k, v]) => [k, v])));
385
952
  const tl = el('label', undefined, 'fnd-field'), tx = el('input'); tx.type = 'search'; tx.placeholder = 'text contains…'; tx.value = s.mfilter.text; tx.dataset.filter = 'm-text';
386
953
  tx.addEventListener('input', () => { s.mfilter.text = tx.value; drawLearnings(); }); tl.append(el('span', 'Text', 'plate'), tx); lbar.append(tl);
387
- let allBox = null, forget = null;
388
- const faction = el('div'), noteHost = el('div'); faction.append(noteHost);
389
- s.forgetHost = faction;
390
954
  if (s.writes) {
391
955
  const lab = el('label', undefined, 'fnd-toggle');
392
956
  allBox = el('input'); allBox.type = 'checkbox'; allBox.setAttribute('aria-label', 'Select all shown learnings');
@@ -394,7 +958,7 @@
394
958
  forget = el('button', 'Forget selected (0)', 'ui-danger'); forget.type = 'button';
395
959
  forget.addEventListener('click', () => { forgetSelected(); });
396
960
  allBox.addEventListener('change', () => {
397
- const shown = filterLearnings(learnings, s.mfilter, s.source);
961
+ const shown = shownNow();
398
962
  for (const row of shown) {
399
963
  const key = learningKey(row);
400
964
  if (!key) continue;
@@ -403,26 +967,10 @@
403
967
  drawLearnings();
404
968
  });
405
969
  lbar.append(lab, forget);
406
- }
407
- const lcount = el('p', '', 'muted prj-count'), lhost = el('div', undefined, 'prj-table');
408
- all.append(lbar, faction, lcount, lhost); parts.push(all);
970
+ all.append(lbar, buildAddForm(), editHost, faction, lcount, lhost);
971
+ } else all.append(lbar, faction, lcount, lhost);
972
+ parts.push(all);
409
973
  body.replaceChildren(...parts);
410
- const learnings = list(d.learnings);
411
- const shownNow = () => filterLearnings(learnings, s.mfilter, s.source);
412
- function syncForget() {
413
- if (!forget) return;
414
- const keys = forgetKeys(shownNow(), s.picked);
415
- forget.textContent = `Forget selected (${keys.length})`;
416
- forget.disabled = s.forgetting || keys.length === 0;
417
- if (allBox) {
418
- const selectable = shownNow().map(learningKey).filter(Boolean);
419
- allBox.checked = selectable.length > 0 && selectable.every(key => s.picked.has(key));
420
- allBox.disabled = s.forgetting || selectable.length === 0;
421
- }
422
- }
423
- function paintNote() {
424
- noteHost.replaceChildren(...list(s.forgetNote).map(line => el('p', line, 'muted')));
425
- }
426
974
  async function forgetSelected() {
427
975
  if (s.forgetting) return;
428
976
  const keys = forgetKeys(shownNow(), s.picked);
@@ -468,11 +1016,12 @@
468
1016
  function drawLearnings() {
469
1017
  const shown = shownNow();
470
1018
  lcount.textContent = `${shown.length} of ${learnings.length} learnings`;
471
- paintNote(); syncForget();
472
- if (!shown.length) { lhost.replaceChildren(el('p', 'No learnings match these filters.', 'muted')); return; }
1019
+ paintNote();
1020
+ editButtons = [];
1021
+ if (!shown.length) { lhost.replaceChildren(el('p', 'No learnings match these filters.', 'muted')); syncForget(); return; }
473
1022
  const columns = [
474
1023
  { id: 'category', label: 'Category', value: r => r.category, cell: r => r.category },
475
- { id: 'text', label: 'Learning', value: r => r.text, cell: r => el('span', r.text, 'prj-learning') },
1024
+ { id: 'text', label: 'Learning', value: r => r.text, cell: r => learningCell(r) },
476
1025
  { id: 'state', label: 'State', value: r => stateFor(r, s.source).state, cell: r => { const st = stateFor(r, s.source), b = el('span', STATES[st.state] || st.state); if (st.from && st.from !== 'dataset') b.title = 'from ' + st.from + ', not this checkout\'s ledger'; return b; } },
477
1026
  { id: 'count', label: 'Runs', title: 'distinct runs that emitted it', value: r => r.count, cell: r => String(r.count || '—') },
478
1027
  { id: 'run', label: 'Last run', value: r => (list(r.rows).slice(-1)[0] || {}).run_id, mono: true, cell: r => (list(r.rows).slice(-1)[0] || {}).run_id || '—' },
@@ -488,7 +1037,13 @@
488
1037
  box.addEventListener('change', () => { if (!key) return; if (box.checked) s.picked.add(key); else s.picked.delete(key); syncForget(); });
489
1038
  return box;
490
1039
  } });
1040
+ if (s.writes) columns.push({ id: 'edit', label: '', title: 'Edit', sortable: false, hideable: false, cell: r => {
1041
+ const key = learningKey(r), b = el('button', 'Edit'); b.type = 'button'; b.dataset.key = key;
1042
+ b.disabled = s.forgetting || !key; b.setAttribute('aria-label', 'Edit ' + (key || 'learning'));
1043
+ b.addEventListener('click', () => openEdit(r)); editButtons.push(b); return b;
1044
+ } });
491
1045
  table(lhost, 'project-learnings', 'Learnings', columns, shown);
1046
+ syncForget();
492
1047
  }
493
1048
  drawLearnings();
494
1049
  }
@@ -533,7 +1088,7 @@
533
1088
  if (id === s.id && t === s.tab) return; // the page's own refresh: nothing changed here
534
1089
  const same = id === s.id;
535
1090
  s.id = id || null; s.tab = t;
536
- if (!same) { s.detail = s.findings = s.memories = null; s.source = null; s.checkout = ''; s.picked = new Set(); s.forgetNote = null; }
1091
+ if (!same) { s.detail = s.findings = s.memories = null; s.source = null; s.checkout = ''; s.picked = new Set(); s.forgetNote = null; s.fsel = new Set(); s.actResult = null; abandonTriage(); s.triage = {}; }
537
1092
  if (same && s.id) { redraw = drawProject(); redraw(); if (t === 'runs') loadDetail(); else if (!(t === 'findings' ? s.findings : s.memories)) loadTab(false); }
538
1093
  else open();
539
1094
  },
@@ -547,5 +1102,5 @@
547
1102
  };
548
1103
  }
549
1104
 
550
- return { render, cleanSummary, filterFindings, filterLearnings, stateFor, memoryEmpty, routeOf, forgetKeys, STATUSES, STATES };
1105
+ return { render, cleanSummary, filterFindings, filterLearnings, stateFor, memoryEmpty, routeOf, forgetKeys, memoryAddBody, memoryEditBody, memoryCommand, STATUSES, STATES };
551
1106
  });