@giamme/forge 0.17.0 → 0.19.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 (110) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +32 -5
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +33 -1
  6. package/docs/commands.md +147 -16
  7. package/docs/dataset.md +5 -0
  8. package/docs/decomposed-runs.md +122 -1
  9. package/docs/development.md +2 -1
  10. package/docs/forge-ui.md +98 -8
  11. package/docs/memory.md +27 -4
  12. package/docs/models.md +8 -0
  13. package/docs/reviews.md +122 -0
  14. package/docs/safety.md +8 -0
  15. package/forge +44 -4
  16. package/package.json +2 -1
  17. package/references/dataset.md +39 -1
  18. package/references/decompose.md +737 -16
  19. package/references/harnesses.md +18 -3
  20. package/references/planning.md +43 -14
  21. package/references/solo.md +2 -1
  22. package/references/ui.md +56 -6
  23. package/registry.tsv +8 -3
  24. package/scripts/forge-artifact.sh +14 -0
  25. package/scripts/forge-brief.py +217 -0
  26. package/scripts/forge-compare.py +13 -2
  27. package/scripts/forge-config.py +176 -9
  28. package/scripts/forge-contract.py +246 -28
  29. package/scripts/forge-control.py +200 -15
  30. package/scripts/forge-dispatch.sh +48 -15
  31. package/scripts/forge-du.py +167 -0
  32. package/scripts/forge-group.py +496 -0
  33. package/scripts/forge-groups.py +89 -0
  34. package/scripts/forge-handoff.py +1128 -0
  35. package/scripts/forge-lib-adopt.sh +1 -0
  36. package/scripts/forge-lib-group.sh +641 -0
  37. package/scripts/forge-lib-plans.sh +343 -4
  38. package/scripts/forge-lib-review.sh +29 -1
  39. package/scripts/forge-lib-task.sh +197 -4
  40. package/scripts/forge-memory.sh +245 -3
  41. package/scripts/forge-metrics.sh +7 -3
  42. package/scripts/forge-parallel-options.sh +4 -0
  43. package/scripts/forge-parallel.sh +1216 -41
  44. package/scripts/forge-planner.py +104 -8
  45. package/scripts/forge-prompt.py +120 -0
  46. package/scripts/forge-retro.py +115 -0
  47. package/scripts/forge-route.py +190 -12
  48. package/scripts/forge-runs-compact.py +443 -0
  49. package/scripts/forge-runs-rm.py +2 -0
  50. package/scripts/forge-runs.py +27 -8
  51. package/scripts/forge-schedule.py +633 -49
  52. package/scripts/forge-shadow.py +7 -1
  53. package/scripts/forge-solo.sh +4 -0
  54. package/scripts/forge-summarize.py +698 -0
  55. package/scripts/forge-ui-options.sh +10 -0
  56. package/scripts/forge-worktrees.py +243 -0
  57. package/scripts/forge_brief/__init__.py +831 -0
  58. package/scripts/forge_brief/answers.py +506 -0
  59. package/scripts/forge_brief/proposals.py +1630 -0
  60. package/scripts/forge_dataset/__init__.py +10 -0
  61. package/scripts/forge_dataset/efforts.py +4 -3
  62. package/scripts/forge_dataset/export.py +36 -10
  63. package/scripts/forge_dataset/facts.py +8 -4
  64. package/scripts/forge_dataset/forecast.py +8 -18
  65. package/scripts/forge_dataset/harvest.py +241 -12
  66. package/scripts/forge_dataset/history.py +13 -6
  67. package/scripts/forge_dataset/importer.py +65 -1
  68. package/scripts/forge_dataset/names.py +66 -0
  69. package/scripts/forge_dataset/reviewers.py +5 -2
  70. package/scripts/forge_dataset/risk.py +6 -3
  71. package/scripts/forge_dataset/routing.py +6 -1
  72. package/scripts/forge_decide/__init__.py +11 -1
  73. package/scripts/forge_groups/__init__.py +308 -0
  74. package/scripts/forge_groups/attribute.py +289 -0
  75. package/scripts/forge_groups/review.py +286 -0
  76. package/scripts/forge_locations.py +366 -0
  77. package/scripts/forge_owner.py +152 -0
  78. package/scripts/forge_registry.py +19 -0
  79. package/scripts/forge_retro/__init__.py +417 -0
  80. package/scripts/forge_retro/issues.py +1193 -0
  81. package/scripts/forge_retro/report.py +671 -0
  82. package/scripts/forge_side/__init__.py +482 -0
  83. package/scripts/forge_storage.py +515 -0
  84. package/ui/README.md +68 -8
  85. package/ui/docs/api.md +375 -31
  86. package/ui/forge_ui/control.py +451 -11
  87. package/ui/forge_ui/executions.py +8 -1
  88. package/ui/forge_ui/export.py +53 -7
  89. package/ui/forge_ui/groups.py +264 -0
  90. package/ui/forge_ui/links.py +337 -0
  91. package/ui/forge_ui/models.py +125 -10
  92. package/ui/forge_ui/projects.py +4 -1
  93. package/ui/forge_ui/reader.py +919 -45
  94. package/ui/forge_ui/server.py +4 -0
  95. package/ui/forge_ui/static/app.js +173 -11
  96. package/ui/forge_ui/static/briefview.js +605 -0
  97. package/ui/forge_ui/static/checksview.js +6 -2
  98. package/ui/forge_ui/static/controls.js +5 -0
  99. package/ui/forge_ui/static/diffview.js +86 -1
  100. package/ui/forge_ui/static/groupsview.js +332 -0
  101. package/ui/forge_ui/static/index.html +4 -0
  102. package/ui/forge_ui/static/panel.js +394 -8
  103. package/ui/forge_ui/static/projectsview.js +189 -10
  104. package/ui/forge_ui/static/runmodel.js +27 -4
  105. package/ui/forge_ui/static/storageview.js +352 -0
  106. package/ui/forge_ui/static/style.css +176 -6
  107. package/ui/forge_ui/static/worktreesview.js +235 -14
  108. package/ui/forge_ui/storage.py +150 -0
  109. package/ui/forge_ui/transcripts.py +35 -10
  110. package/ui/forge_ui/worktrees.py +154 -13
@@ -1,9 +1,10 @@
1
- /* forge-ui Worktrees screen (#125): every worktree forge created, in any repository, with its state and the command
2
- that removes it safely (window.ForgeWorktrees, and a CommonJS module under node:test). Route #/worktrees, optionally
3
- narrowed to one repository (#/worktrees/repo/<root>) or one run (#/worktrees/runs/<key>).
4
- The commands come from the server, are only ever copied, and never include --force: the page runs nothing, so it
5
- works with --read-only too. Paths, branches and commit subjects enter the page as text.
6
- The pure helpers (filters, totals, sizes) are tested in ui/tests/js/worktreesview.test.js.
1
+ /* forge-ui Worktrees screen (#125, removals #147): every worktree forge created, in any repository, with its state
2
+ and the command that removes it (window.ForgeWorktrees, and a CommonJS module under node:test). Route #/worktrees,
3
+ optionally narrowed to one repository (#/worktrees/repo/<root>) or one run (#/worktrees/runs/<key>).
4
+ With write controls the page removes worktrees through POST /api/worktrees/remove (`forge worktrees rm`): a dry run,
5
+ then a confirmation, then the real call. Under read-only, or with no token, it only copies the commands.
6
+ Paths, branches, reasons and commit subjects enter the page as text.
7
+ The pure helpers (filters, totals, sizes, which rows can be removed) are tested in ui/tests/js/worktreesview.test.js.
7
8
  ctx = { filter?: {repo, run}, runHref(key), tablePrefs?(id), saveTablePrefs?(id, prefs) }. */
8
9
  (function (root, factory) {
9
10
  'use strict';
@@ -52,12 +53,78 @@
52
53
  const repoName = p => typeof p === 'string' && p ? p.replace(/\/+$/, '').split('/').pop() : '—';
53
54
  const label = status => LABEL[status] || status || '—';
54
55
 
56
+ // A removal is the command the server offers: failed or finished, or an unknown folder git has already dropped.
57
+ const BLOCK = {
58
+ in_use: 'its run is active',
59
+ dirty: 'uncommitted changes',
60
+ locked: 'locked by git',
61
+ needed: 'its run still needs it',
62
+ missing: 'already gone (prune)',
63
+ foreign: "not forge's",
64
+ removed: 'already removed',
65
+ unknown: 'not a leftover',
66
+ };
67
+ function removable(row) {
68
+ if (!row || typeof row !== 'object') return false;
69
+ if (row.status === 'failed' || row.status === 'finished') return true;
70
+ return row.status === 'unknown' && row.leftover === true;
71
+ }
72
+ function blockReason(row) {
73
+ if (!row || typeof row !== 'object' || removable(row)) return null;
74
+ if (Object.prototype.hasOwnProperty.call(BLOCK, row.status)) return BLOCK[row.status];
75
+ return row.status ? String(row.status) : 'cannot remove';
76
+ }
77
+ // Paths of the removable rows in the current filtered view, in that view's order.
78
+ function selectable(rows, filter) {
79
+ return filterRows(rows, filter).filter(removable).map(r => r.path).filter(p => typeof p === 'string');
80
+ }
81
+ function answerRows(answer) {
82
+ return list(answer && answer.rows).filter(r => r && typeof r === 'object');
83
+ }
84
+ function rowBit(r) {
85
+ const path = r.path == null ? '' : String(r.path);
86
+ const reason = r.reason == null || r.reason === '' ? '' : String(r.reason);
87
+ return reason ? path + ' (' + reason + ')' : path;
88
+ }
89
+ // One sentence for the dry run: how many would go, then each skip (and any failure) with its reason.
90
+ function summaryText(answer) {
91
+ const rows = answerRows(answer);
92
+ const n = rows.filter(r => r.status === 'would-remove').length;
93
+ let text = (n === 1 ? '1 worktree' : n + ' worktrees') + ' would be removed.';
94
+ const skipped = rows.filter(r => r.status === 'skipped');
95
+ const failed = rows.filter(r => r.status === 'failed');
96
+ if (skipped.length) text += ' Skipped: ' + skipped.map(rowBit).join('; ') + '.';
97
+ if (failed.length) text += ' Failed: ' + failed.map(rowBit).join('; ') + '.';
98
+ return text;
99
+ }
100
+ function resultLines(answer) {
101
+ return answerRows(answer).map(r => ({
102
+ path: r.path == null ? '' : String(r.path),
103
+ status: r.status == null ? '' : String(r.status),
104
+ reason: r.reason == null ? '' : String(r.reason),
105
+ }));
106
+ }
107
+ // The line shown for one result row: "removed", "skipped (reason)", "failed (reason)".
108
+ function resultPhrase(line) {
109
+ const reason = line && line.reason ? ' (' + line.reason + ')' : '';
110
+ if (!line) return '';
111
+ if (line.status === 'removed') return 'removed';
112
+ if (line.status === 'skipped') return 'skipped' + reason;
113
+ if (line.status === 'failed') return 'failed' + reason;
114
+ return (line.status || '') + reason;
115
+ }
116
+ const confirmQuestion = n => 'Remove ' + n + ' worktrees?';
117
+
55
118
  /* ---------- DOM ---------- */
56
119
  function render(host, ctx) {
57
120
  const UI = root.ForgeUI;
58
121
  const el = (tag, text, cls) => UI.el(tag, text, cls);
59
122
  const start = ctx.filter || {};
60
- const s = { data: null, error: null, filter: { repo: start.repo || '', run: start.run || '', status: 'all', kind: 'all' }, timer: null, seq: 0, loading: false };
123
+ const s = { data: null, error: null, filter: { repo: start.repo || '', run: start.run || '', status: 'disk', kind: 'all' }, timer: null, seq: 0, loading: false,
124
+ controls: false, selected: new Set(), branches: false, busy: false };
125
+ // Table roots whose replaceWith remounts the select-all. ForgeTable keeps the root private and swaps it on redraw.
126
+ const armedTables = new WeakSet();
127
+ const LEDE_COPY = 'Every worktree forge created, in any repository it knows, with what state it is in and the command that removes it safely. Commands are only copied: this page runs nothing.';
61
128
 
62
129
  const head = el('div', undefined, 'wt-head');
63
130
  const refreshKey = el('button', 'Read again'); refreshKey.type = 'button';
@@ -65,7 +132,7 @@
65
132
  refreshKey.addEventListener('click', () => load(true));
66
133
  const stamp = el('span', '', 'muted wt-stamp');
67
134
  head.append(el('h1', 'Worktrees', 'module-title'), refreshKey, stamp);
68
- const lede = el('p', 'Every worktree forge created, in any repository it knows, with what state it is in and the command that removes it safely. Commands are only copied: this page runs nothing.', 'muted wt-lede');
135
+ const lede = el('p', LEDE_COPY, 'muted wt-lede');
69
136
  const notes = el('div', undefined, 'wt-notes muted');
70
137
  const sums = el('p', undefined, 'wt-totals'); sums.setAttribute('role', 'status');
71
138
  const filters = el('div', undefined, 'wt-filters');
@@ -150,8 +217,32 @@
150
217
  return box;
151
218
  };
152
219
  const pathCell = r => { const n = el('span', shortPath(r.path), 'mono'); n.title = r.path; return n; };
220
+ function selectCell(r) {
221
+ const wrap = el('span');
222
+ const box = el('input'); box.type = 'checkbox';
223
+ if (removable(r)) {
224
+ box.checked = s.selected.has(r.path);
225
+ box.disabled = s.busy;
226
+ box._path = r.path;
227
+ box.setAttribute('aria-label', 'Select ' + String(r.path));
228
+ box.addEventListener('change', () => {
229
+ if (box.checked) s.selected.add(r.path); else s.selected.delete(r.path);
230
+ syncSelectAll(); syncBar();
231
+ });
232
+ const go = el('button', 'Remove'); go.type = 'button'; go.disabled = s.busy;
233
+ go.addEventListener('click', () => removePaths([r.path]));
234
+ wrap.append(box, go);
235
+ } else {
236
+ const why = blockReason(r) || 'cannot remove';
237
+ box.disabled = true; box.title = why;
238
+ box.setAttribute('aria-label', why);
239
+ wrap.append(box, el('span', why, 'muted wt-note'));
240
+ }
241
+ return wrap;
242
+ }
243
+ const selectColumn = { id: 'select', label: 'Select', sortable: false, hideable: false, cls: 'wt-command-col', cell: selectCell };
153
244
  const columns = [
154
- { id: 'status', label: 'Status', value: r => STATUSES.indexOf(r.status), cell: statusCell },
245
+ { id: 'status', label: 'Status', hideable: false, value: r => STATUSES.indexOf(r.status), cell: statusCell },
155
246
  { id: 'run', label: 'Run', value: r => r.run_id, cell: runCell },
156
247
  { id: 'task', label: 'Task', value: r => r.task, mono: true, cell: r => r.task || (r.kind && r.kind !== 'task' ? r.kind : '—') },
157
248
  { id: 'command', label: 'Command', sortable: false, cls: 'wt-command-col', cell: commandCell },
@@ -180,8 +271,8 @@
180
271
  notes.replaceChildren(...out);
181
272
  }
182
273
  function drawTotals(rows) {
183
- const t = totals(rows);
184
- sums.replaceChildren(el('strong', `${t.onDisk} on disk`), el('span', ` · ${humanBytes(t.bytes)}${t.pending ? ` so far, ${t.pending} still being measured` : ''} · ${t.count - t.onDisk} removed or missing · ${t.count} listed`));
274
+ const t = totals(rows), hidden = list(s.data && s.data.rows).length - list(rows).length;
275
+ sums.replaceChildren(el('strong', `${t.onDisk} on disk`), el('span', ` · ${humanBytes(t.bytes)}${t.pending ? ` so far, ${t.pending} still being measured` : ''} · ${t.count - t.onDisk} removed or missing · ${t.count} listed${hidden > 0 ? ` · ${hidden} more hidden by the filters` : ''}`));
185
276
  }
186
277
  function drawGroups() {
187
278
  const items = list(s.data && s.data.runs).filter(g => g.command && (!s.filter.run || g.key === s.filter.run) && (!s.filter.repo || g.repo === s.filter.repo));
@@ -197,20 +288,80 @@
197
288
  }
198
289
  groups.replaceChildren(d);
199
290
  }
291
+ function shownPaths() { return selectable(list(s.data && s.data.rows), s.filter); }
292
+ function chosenPaths() { return shownPaths().filter(p => s.selected.has(p)); }
293
+ function pruneSelection() {
294
+ if (!s.data) return;
295
+ const live = new Set(selectable(s.data.rows, { status: 'all', kind: 'all' }));
296
+ for (const p of [...s.selected]) if (!live.has(p)) s.selected.delete(p);
297
+ }
298
+ function syncBar() {
299
+ if (!removeSel) return;
300
+ const n = chosenPaths().length;
301
+ removeSel.textContent = 'Remove selected (' + n + ')';
302
+ removeSel.disabled = n === 0 || s.busy;
303
+ if (branchesBox) branchesBox.disabled = s.busy;
304
+ for (const b of tableHost.querySelectorAll('tbody button')) if (b.textContent === 'Remove') b.disabled = s.busy;
305
+ }
306
+ function syncSelectAll() {
307
+ const box = tableHost.querySelector('th[data-col="select"] input');
308
+ if (!box) return;
309
+ const paths = shownPaths(), n = paths.filter(p => s.selected.has(p)).length;
310
+ box.indeterminate = n > 0 && n < paths.length;
311
+ box.checked = paths.length > 0 && n === paths.length;
312
+ box.disabled = paths.length === 0 || s.busy;
313
+ }
314
+ function mountSelectAll() {
315
+ const text = tableHost.querySelector('th[data-col="select"] .th-text');
316
+ if (!text) return;
317
+ const box = el('input'); box.type = 'checkbox';
318
+ box.setAttribute('aria-label', 'Select all removable worktrees');
319
+ box.addEventListener('dragstart', e => e.preventDefault());
320
+ box.addEventListener('change', () => {
321
+ const paths = shownPaths();
322
+ if (box.checked) for (const p of paths) s.selected.add(p);
323
+ else for (const p of paths) s.selected.delete(p);
324
+ for (const input of tableHost.querySelectorAll('tbody input')) {
325
+ if (typeof input._path === 'string' && paths.includes(input._path)) input.checked = s.selected.has(input._path);
326
+ }
327
+ syncSelectAll(); syncBar();
328
+ });
329
+ text.replaceChildren(box);
330
+ syncSelectAll();
331
+ }
332
+ // Sort, drag, Alt+arrow, the Columns menu and Reset all rebuild the header from `c.label` and swap the table root
333
+ // with replaceWith. Nothing tells us, so the box mounted after render would vanish until the next full draw.
334
+ function armRedraw(node) {
335
+ if (!node || armedTables.has(node) || typeof node.replaceWith !== 'function') return;
336
+ const orig = node.replaceWith;
337
+ armedTables.add(node);
338
+ node.replaceWith = function (...nodes) {
339
+ const out = orig.apply(this, nodes);
340
+ for (const next of nodes) armRedraw(next);
341
+ if (s.controls && host.isConnected) mountSelectAll();
342
+ return out;
343
+ };
344
+ }
200
345
  function drawNow() {
346
+ pruneSelection();
201
347
  syncFilters(); drawNotes();
202
348
  const d = s.data;
203
349
  if (!d) { tableHost.replaceChildren(el('p', s.error ? '' : 'Reading every repository\'s worktrees… the first read runs git status in each, so it can take a few seconds.', 'muted')); sums.replaceChildren(); return; }
204
350
  const rows = filterRows(d.rows, s.filter);
205
351
  drawTotals(rows);
206
352
  UI.keepOpen(groups, drawGroups);
207
- if (!rows.length) { tableHost.replaceChildren(el('p', list(d.rows).length ? `No worktrees match these filters (${list(d.rows).length} hidden).` : 'forge has no worktrees on record.', 'muted')); return; }
353
+ if (!rows.length) {
354
+ tableHost.replaceChildren(el('p', list(d.rows).length ? `No worktrees match these filters (${list(d.rows).length} hidden).` : 'forge has no worktrees on record.', 'muted'));
355
+ syncBar(); return;
356
+ }
208
357
  const id = 'worktrees';
358
+ const cols = s.controls ? [selectColumn].concat(columns) : columns;
209
359
  tableHost.replaceChildren();
210
- root.ForgeTable.render(tableHost, { id, label: 'Worktrees', columns, rows, className: 'wt-grid', rowClass: r => 'wt-row-' + r.status,
360
+ const table = root.ForgeTable.render(tableHost, { id, label: 'Worktrees', columns: cols, rows, className: 'wt-grid', rowClass: r => 'wt-row-' + r.status,
211
361
  // a cell cut short by its width says the whole of itself on hover
212
362
  onRow: (_row, tr) => { for (const td of tr.children) if (!td.classList.contains('wt-command-col') && !td.title) td.title = td.textContent; },
213
363
  prefs: ctx.tablePrefs ? ctx.tablePrefs(id) : null, savePrefs: p => ctx.saveTablePrefs && ctx.saveTablePrefs(id, p) });
364
+ if (s.controls) { armRedraw(table); mountSelectAll(); syncBar(); }
214
365
  }
215
366
  // A redraw never pulls a command out from under someone selecting or copying it (#115).
216
367
  const draw = () => { if (UI.guard) UI.guard(host, drawNow); else drawNow(); };
@@ -234,8 +385,78 @@
234
385
  const pending = s.data && s.data.sizes_pending > 0;
235
386
  s.timer = setTimeout(() => { if (host.isConnected && document.visibilityState === 'visible') load(false); else schedule(); }, pending ? SIZE_POLL_MS : POLL_MS);
236
387
  }
388
+
389
+ let branchesBox = null, removeSel = null, outcomeHost = null;
390
+ function showFailure(res) {
391
+ const text = res && res.status === 409 ? 'busy: another removal is running' : UI.outcomeText(res).text;
392
+ const line = el('p', text, 'warn'); line.setAttribute('role', 'status');
393
+ outcomeHost.replaceChildren(line);
394
+ }
395
+ function showLines(lines) {
396
+ const ul = el('ul');
397
+ for (const line of lines) {
398
+ const li = el('li');
399
+ li.append(el('span', line.path, 'mono'), el('span', ' ' + resultPhrase(line)));
400
+ ul.append(li);
401
+ }
402
+ outcomeHost.replaceChildren(ul);
403
+ }
404
+ // Nothing is removed on the first click: dry run, the summary, confirm, then the real call.
405
+ async function removePaths(paths) {
406
+ const wanted = list(paths).filter(p => typeof p === 'string' && p);
407
+ if (s.busy || !wanted.length || !outcomeHost) return;
408
+ const branches = !!s.branches;
409
+ const body = dryRun => ({ paths: wanted.slice(), branches, dry_run: dryRun });
410
+ s.busy = true; syncBar(); syncSelectAll();
411
+ try {
412
+ const dry = await UI.post('/api/worktrees/remove', body(true)) || { ok: false };
413
+ if (!host.isConnected) return;
414
+ if (!dry.ok) { showFailure(dry); return; }
415
+ const data = dry.data || {};
416
+ const n = answerRows(data).filter(r => r.status === 'would-remove').length;
417
+ outcomeHost.replaceChildren(el('p', summaryText(data)));
418
+ // Nothing would be removed: the summary is the answer. Do not ask, and do not send the real call.
419
+ if (n === 0) return;
420
+ const yes = await UI.confirmInline(outcomeHost, confirmQuestion(n), { danger: true });
421
+ if (!yes || !host.isConnected) return;
422
+ const real = await UI.post('/api/worktrees/remove', body(false)) || { ok: false };
423
+ if (!host.isConnected) return;
424
+ if (!real.ok) { showFailure(real); return; }
425
+ const lines = resultLines(real.data);
426
+ showLines(lines);
427
+ for (const line of lines) if (line.status === 'removed') s.selected.delete(line.path);
428
+ s.busy = false; // the refresh draws the checkboxes; they must not stay disabled
429
+ await load(true);
430
+ } finally {
431
+ s.busy = false;
432
+ if (host.isConnected) { syncBar(); syncSelectAll(); }
433
+ }
434
+ }
435
+ function enableControls() {
436
+ if (s.controls) return;
437
+ const bar = el('div', undefined, 'wt-filters');
438
+ bar.setAttribute('role', 'group'); bar.setAttribute('aria-label', 'Remove worktrees');
439
+ branchesBox = el('input'); branchesBox.type = 'checkbox';
440
+ const branchesLabel = el('label');
441
+ branchesLabel.append(branchesBox, el('span', 'Delete merged branches too'));
442
+ branchesBox.addEventListener('change', () => { s.branches = branchesBox.checked; });
443
+ removeSel = el('button', 'Remove selected (0)'); removeSel.type = 'button'; removeSel.disabled = true;
444
+ removeSel.addEventListener('click', () => removePaths(chosenPaths()));
445
+ bar.append(branchesLabel, removeSel);
446
+ outcomeHost = el('div', undefined, 'wt-notes'); outcomeHost.setAttribute('role', 'status');
447
+ host.insertBefore(bar, tableHost);
448
+ host.insertBefore(outcomeHost, tableHost);
449
+ s.controls = true;
450
+ lede.textContent = 'Every worktree forge created, in any repository it knows, with what state it is in and the command that removes it safely. A removal runs through forge worktrees rm after a dry run and a confirmation. Commands can still be copied.';
451
+ }
452
+
237
453
  drawNow();
238
454
  load(false);
455
+ UI.controlsEnabled().then(on => {
456
+ if (!on || !host.isConnected) return;
457
+ enableControls();
458
+ draw();
459
+ });
239
460
  return {
240
461
  setFilter(f) {
241
462
  const repo = (f && f.repo) || '', run = (f && f.run) || '';
@@ -246,5 +467,5 @@
246
467
  };
247
468
  }
248
469
 
249
- return { render, filterRows, totals, humanBytes, repoName, shortPath, label, STATUSES, LABEL };
470
+ return { render, filterRows, totals, humanBytes, repoName, shortPath, label, removable, blockReason, selectable, summaryText, resultLines, STATUSES, LABEL };
250
471
  });
@@ -0,0 +1,150 @@
1
+ """The Disk screen (#139): what forge takes on disk, in every repository it has runs for, and the command that
2
+ takes each part back. The same report as `forge du --all`, from the same rules (scripts/forge_storage.py,
3
+ loaded read-only the way worktrees.py loads forge_worktrees.py), never a second rule.
4
+
5
+ Read-only: the commands are text to copy, never run, so the screen works with --read-only too.
6
+
7
+ Cost: measuring visits every file of every run dir (tens of seconds for tens of GB), so none of it happens
8
+ on the normal poll. The screen asks /api/storage when it opens; the first ask starts one background
9
+ measurement and answers `measuring` until it is done. The answer is kept for CACHE_S; ?refresh=1 measures
10
+ again. Nothing is written: the footprint the storage.warn-gb check reads is `forge du`'s and the background
11
+ compaction's to keep.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import importlib.machinery
16
+ import importlib.util
17
+ from pathlib import Path
18
+ import shlex
19
+ import threading
20
+ import time
21
+
22
+ RULES = Path(__file__).resolve().parents[2] / 'scripts' / 'forge_storage.py'
23
+ CACHE_S = 600
24
+ _STATE = {}
25
+ _LOCK = threading.Lock()
26
+
27
+
28
+ class _ReadOnlyLoader(importlib.machinery.SourceFileLoader):
29
+ def set_data(self, *args, **kwargs):
30
+ pass # no .pyc beside forge's scripts
31
+
32
+
33
+ def rules():
34
+ """forge's storage rule module (scripts/forge_storage.py), or None when it cannot be loaded."""
35
+ with _LOCK:
36
+ if 'rules' not in _STATE:
37
+ try:
38
+ spec = importlib.util.spec_from_file_location(
39
+ 'forge_storage_for_ui', RULES, loader=_ReadOnlyLoader('forge_storage_for_ui', str(RULES)))
40
+ module = importlib.util.module_from_spec(spec)
41
+ spec.loader.exec_module(module)
42
+ if not (callable(module.report) and callable(module.scan)):
43
+ raise TypeError('not the forge storage module')
44
+ _STATE['rules'] = module
45
+ except Exception:
46
+ _STATE['rules'] = None
47
+ return _STATE['rules']
48
+
49
+
50
+ def data_home():
51
+ """forge's data home, as the dataset resolves it; None when the dataset package cannot be loaded."""
52
+ try:
53
+ import sys
54
+ scripts = str(RULES.parent)
55
+ if scripts not in sys.path:
56
+ sys.path.insert(0, scripts)
57
+ from forge_dataset import data_home as home
58
+ return home()
59
+ except Exception:
60
+ return None
61
+
62
+
63
+ def q(text):
64
+ return shlex.quote(str(text))
65
+
66
+
67
+ def with_commands(result):
68
+ """The report with the commands that take each part back: text to copy, never run here."""
69
+ for run in result['runs']:
70
+ run['commands'] = []
71
+ if run['reclaimable']:
72
+ run['commands'].append(dict(label='remove its review snapshots and gzip its log copies (the run stays, viewable)',
73
+ command='forge runs compact %s --logs' % q(run['path'])))
74
+ run['commands'].append(dict(label='delete the run dir, after the dataset and an archive keep its traces (dry run)',
75
+ command='forge runs rm %s --dry-run' % q(run['path'])))
76
+ commands = []
77
+ if result['totals']['reclaimable']:
78
+ commands.append(dict(label='every run: remove the leftover review snapshots and gzip the log copies',
79
+ command='forge runs compact --all --logs', bytes=result['totals']['reclaimable']))
80
+ commands.append(dict(label='the same report in the terminal', command='forge du --all'))
81
+ result['commands'] = commands
82
+ return result
83
+
84
+
85
+ def with_keys(answer, keys):
86
+ """The answer with each run's forge-ui key, or None for a run dir the run list does not show (the Disk screen
87
+ links only the ones it can open). A copy: the cached result keeps no key, since the run list changes."""
88
+ data = answer.get('data')
89
+ if not data:
90
+ return answer
91
+ from forge_ui.reader import run_key
92
+ runs = []
93
+ for run in data['runs']:
94
+ key = run_key(run['path'])
95
+ runs.append(dict(run, key=key if key in keys else None))
96
+ return dict(answer, data=dict(data, runs=runs))
97
+
98
+
99
+ class Screen:
100
+ """The cached answer of /api/storage for one server; one measurement at a time, in a background thread."""
101
+
102
+ def __init__(self):
103
+ self.lock = threading.Lock()
104
+ self.result = None
105
+ self.error = None
106
+ self.started = None
107
+ self.progress = None
108
+ self.thread = None
109
+
110
+ def _work(self, module):
111
+ try:
112
+ home = data_home()
113
+
114
+ def progress(index, count, _path):
115
+ with self.lock:
116
+ self.progress = dict(done=index, of=count)
117
+ result = with_commands(module.report(None, home=home, progress=progress))
118
+ with self.lock:
119
+ self.result, self.error = result, None
120
+ except Exception as exc: # noqa: BLE001 -- the screen says what went wrong instead
121
+ with self.lock:
122
+ self.error = '%s: %s' % (type(exc).__name__, exc)
123
+ finally:
124
+ with self.lock:
125
+ self.thread, self.progress = None, None
126
+
127
+ def answer(self, refresh=False, now=None):
128
+ now = time.time() if now is None else now
129
+ module = rules()
130
+ if module is None:
131
+ return dict(state='unavailable', error='scripts/forge_storage.py could not be loaded', data=None)
132
+ with self.lock:
133
+ stale = self.result is None or now - self.result['computed'] > CACHE_S
134
+ if (refresh or stale) and self.thread is None:
135
+ self.started = now
136
+ self.thread = threading.Thread(target=self._work, args=(module,), name='forge-ui-storage', daemon=True)
137
+ self.thread.start()
138
+ measuring = self.thread is not None
139
+ return dict(state='measuring' if measuring else ('error' if self.error and self.result is None else 'ready'),
140
+ error=self.error, started=self.started if measuring else None, progress=self.progress,
141
+ data=self.result)
142
+
143
+
144
+ def screen(server):
145
+ """The server's Screen, made on first use."""
146
+ with _LOCK:
147
+ found = getattr(server, 'storage_screen', None)
148
+ if found is None:
149
+ found = server.storage_screen = Screen()
150
+ return found
@@ -34,11 +34,13 @@ from __future__ import annotations
34
34
 
35
35
  import bisect
36
36
  from datetime import datetime
37
+ import gzip
37
38
  import json
38
39
  import os
39
40
  from pathlib import Path
40
41
  import re
41
42
  import stat
43
+ import zlib
42
44
 
43
45
  TEXT_CAP = 20000 # characters kept of one message, reasoning or result
44
46
  OUTPUT_CAP = 8000 # of a command's or tool's output: the head and the tail
@@ -562,31 +564,54 @@ def session_file(session_id, home=None, environ=None):
562
564
 
563
565
  # ---------- one execution's transcript ----------
564
566
 
567
+ GZ_CAP = 512 << 20 # bytes a gzipped log may expand to before it is refused
568
+
569
+
565
570
  def _read(path):
566
- """The log's text (its end when it is over LOG_CAP), whether it was cut, and the byte offset it starts at."""
571
+ """The log's text (its end when it is over LOG_CAP), whether it was cut, and the byte offset it starts at.
572
+
573
+ A `.gz` log (an execution record's copy that `forge runs compact --logs` gzipped, #139) reads as the
574
+ plain log it was: the same text and the same offsets, so its clock still places every line."""
567
575
  base = 0
568
576
  try:
569
- size = path.stat().st_size
570
- with open(path, 'rb') as fh:
577
+ if path.name.endswith('.gz'):
578
+ with gzip.open(path, 'rb') as fh:
579
+ data = fh.read(GZ_CAP + 1)
580
+ if len(data) > GZ_CAP:
581
+ return None, False, 0
582
+ size = len(data)
571
583
  if size > LOG_CAP:
572
- fh.seek(size - LOG_CAP)
573
- data = fh.read()
584
+ data = data[size - LOG_CAP:]
574
585
  skip = data.find(b'\n') + 1
575
586
  data, base = data[skip:], size - LOG_CAP + skip
576
- else:
577
- data = fh.read()
578
- except OSError:
587
+ else:
588
+ size = path.stat().st_size
589
+ with open(path, 'rb') as fh:
590
+ if size > LOG_CAP:
591
+ fh.seek(size - LOG_CAP)
592
+ data = fh.read()
593
+ skip = data.find(b'\n') + 1
594
+ data, base = data[skip:], size - LOG_CAP + skip
595
+ else:
596
+ data = fh.read()
597
+ except (OSError, EOFError, zlib.error):
579
598
  return None, False, 0
580
599
  return data.decode('utf-8', 'replace'), size > LOG_CAP, base
581
600
 
582
601
 
602
+ def clock_path(log):
603
+ """`<role>.clock` beside `<role>.log` or `<role>.log.gz`."""
604
+ name = log.name[:-3] if log.name.endswith('.gz') else log.name
605
+ return log.with_name(name.rsplit('.', 1)[0] + '.clock')
606
+
607
+
583
608
  CLOCK_CAP = 8 << 20 # bytes of a clock read
584
609
 
585
610
 
586
611
  def clock_of(log):
587
612
  """The clock beside `log` (`<role>.clock` for `<role>.log`) as (sizes, times), sizes ascending; None without one."""
588
613
  try:
589
- path = log.with_name(log.stem + '.clock')
614
+ path = clock_path(log)
590
615
  with open(path, 'rb') as fh:
591
616
  if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
592
617
  return None
@@ -644,7 +669,7 @@ def transcript(log, harness=None, running=False, home=None, environ=None):
644
669
  if st is None or not stat.S_ISREG(st.st_mode):
645
670
  out['warnings'].append(f'{log.name} is not readable')
646
671
  return out
647
- key = (str(log), st.st_size, st.st_mtime_ns, harness, running, _signature(log.with_name(log.stem + '.clock')))
672
+ key = (str(log), st.st_size, st.st_mtime_ns, harness, running, _signature(clock_path(log)))
648
673
  if key in _CACHE:
649
674
  answer, sid, seen = _CACHE[key]
650
675
  if sid is None or _signature(session_file(sid, home, environ)) == seen: