@giamme/forge 0.14.0 → 0.15.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 (44) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/SKILL.md +47 -14
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +2 -1
  5. package/docs/commands.md +301 -7
  6. package/docs/models.md +53 -0
  7. package/package.json +1 -1
  8. package/references/dataset.md +12 -3
  9. package/references/decompose.md +108 -7
  10. package/references/harnesses.md +21 -1
  11. package/references/planning.md +59 -0
  12. package/references/ui.md +39 -1
  13. package/scripts/forge-compare.py +6 -3
  14. package/scripts/forge-config.py +531 -4
  15. package/scripts/forge-dispatch.sh +132 -22
  16. package/scripts/forge-lib-plans.sh +19 -2
  17. package/scripts/forge-lib-review.sh +5 -3
  18. package/scripts/forge-lib-task.sh +119 -0
  19. package/scripts/forge-parallel-options.sh +12 -6
  20. package/scripts/forge-parallel.sh +572 -26
  21. package/scripts/forge-plan-check.py +591 -8
  22. package/scripts/forge-planner.py +480 -0
  23. package/scripts/forge-route.py +72 -23
  24. package/scripts/forge-runtime.py +157 -1
  25. package/scripts/forge-shadow.py +51 -7
  26. package/scripts/forge-solo.sh +81 -7
  27. package/scripts/forge_dataset/cli.py +10 -0
  28. package/scripts/forge_dataset/efforts.py +215 -0
  29. package/scripts/forge_dataset/harvest.py +44 -0
  30. package/scripts/forge_decide/__init__.py +19 -1
  31. package/scripts/forge_decide/builtin_profiles.json +25 -0
  32. package/scripts/forge_decide/cli.py +12 -0
  33. package/scripts/forge_decide/profiles.py +866 -0
  34. package/scripts/forge_decide/resolve.py +38 -6
  35. package/ui/docs/api.md +87 -8
  36. package/ui/forge_ui/control.py +173 -12
  37. package/ui/forge_ui/executions.py +28 -8
  38. package/ui/forge_ui/models.py +60 -1
  39. package/ui/forge_ui/reader.py +21 -1
  40. package/ui/forge_ui/static/leaderboard.js +5 -1
  41. package/ui/forge_ui/static/modelstats.js +25 -1
  42. package/ui/forge_ui/static/panel.js +19 -2
  43. package/ui/forge_ui/static/settings.js +788 -25
  44. package/ui/forge_ui/static/style.css +23 -0
@@ -1,8 +1,9 @@
1
1
  /* forge-ui settings view (window.ForgeSettings, and a CommonJS module under node:test). Route #/settings: the model
2
- registry (read-only), the decision-model gates, the three per-repo .forge files of one repository, the dataset and
3
- the FORGE_* environment. The pure helpers (request bodies, value checks, the decision-model view, the repository
4
- picker, the editors' unsaved-text state) are tested in ui/tests/js/settings.test.js; render(host, ctx) is thin DOM
5
- over them. Every value from the server enters the page as text.
2
+ registry (read-only), the decision-model gates, named profiles, the three per-repo .forge files of one repository,
3
+ the dataset and the FORGE_* environment. The pure helpers (request bodies, value checks, the decision-model view,
4
+ the profile summary, the repository picker, the editors' unsaved-text state) are tested in
5
+ ui/tests/js/settings.test.js; render(host, ctx) is thin DOM over them. Every value from the server enters the page
6
+ as text.
6
7
  ctx = { key (the run whose repo to show, or null), runs() (the run list), onPick?(key) }. render returns { poll() }:
7
8
  the page calls it on each refresh, and unsaved editor text survives it.
8
9
  The calls are GET /api/config?run=<key> and POST /api/config, see ui/docs/api.md, "Controls (write endpoints)". A write
@@ -26,6 +27,15 @@
26
27
  const MODES = ['off', 'shadow', 'on'];
27
28
  const ADD_COMMAND = 'forge decide provider add …';
28
29
  const POLL_MS = 20000; // the config rarely changes, and each read starts a CLI process
30
+ // The same order as forge_decide.profiles. A tier or key the body carries and this list does not still shows, after these.
31
+ const TIERS = ['any', 'low', 'medium', 'high'];
32
+ const POOLS = ['dwarf', 'qa'];
33
+ const ROUTING_ORDER = ['planner', 'fractal_planner', 'final_reviewer', 'escalate_after', 'escalate_effort'];
34
+ const POLICY_ORDER = ['qa_threshold', 'retry_failed', 'infra_retries', 'verify_retries', 'timeout', 'explore', 'shadow_rate', 'shadow_qa', 'fast'];
35
+ const BUDGET_PAIRS = [['run', 'run_tokens', 'run_usd'], ['daily', 'daily_tokens', 'daily_usd']];
36
+ const PROFILE_LEVELS = ['user', 'repo', 'builtin'];
37
+ const WRITE_LEVELS = ['user', 'repo']; // POST /api/config/profiles refuses builtin
38
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
29
39
  const list = v => Array.isArray(v) ? v : [];
30
40
  const object = v => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
31
41
  const text = v => typeof v === 'string' ? v : '';
@@ -182,6 +192,16 @@
182
192
  const latest = usable.slice().sort(newestFirst)[0];
183
193
  return latest ? latest.key : null;
184
194
  }
195
+ // The selected run has left the list. 'keep': another run of the same repository takes over and the editors stay.
196
+ // 'stay': nothing of this repository remains, but text is unsaved, so the page holds the gone run instead of
197
+ // picking a new one and discarding that text. 'drop': nothing unsaved, so a new default may replace it.
198
+ // 'here': the run is still listed, or none was selected.
199
+ function departedRun(run, repo, runs, unsaved) {
200
+ const usable = withRepo(runs);
201
+ if (run == null || usable.some(r => r.key === run)) return 'here';
202
+ if (usable.some(r => RM.repoKey(r) === repo)) return 'keep';
203
+ return unsaved ? 'stay' : 'drop';
204
+ }
185
205
  // The choices grouped by repository root: [{repo, name, runs}], the repository of the newest run first.
186
206
  function groupRuns(runs) {
187
207
  const groups = new Map();
@@ -234,6 +254,23 @@
234
254
  return { editor: e, dirty, moved: dirty && norm(from) !== norm(e.base) };
235
255
  }
236
256
  const shown = editor => editor.draft !== null ? editor.draft : editor.base;
257
+ // What a repository switch would discard. A profile's unsaved JSON counts: resetRun drops those editors, so a
258
+ // poll that sees the run leave the list must not move to another repository while one is dirty. Profile keys
259
+ // are `name\0level`. File names stay in the order the page edits them; profile names are sorted.
260
+ function unsavedLabels(editors, profileEditors) {
261
+ const labels = [];
262
+ const files = object(editors);
263
+ for (const name of FILES) {
264
+ if (isDirty(files[name])) labels.push('.forge/' + name);
265
+ }
266
+ const profiles = object(profileEditors);
267
+ for (const key of Object.keys(profiles).sort()) {
268
+ if (!isDirty(profiles[key])) continue;
269
+ const name = text(String(key).split('\0')[0]);
270
+ if (name) labels.push('profile ' + name);
271
+ }
272
+ return labels;
273
+ }
237
274
  // What a failed GET /api/config does: with a good read of this run on the page, it stays and a note names the
238
275
  // failure; with none yet, the message replaces the page. Status 0 is no answer at all.
239
276
  function readFailure(res, hasData) {
@@ -241,16 +278,186 @@
241
278
  return { keep: !!hasData, message };
242
279
  }
243
280
 
281
+ // A scalar, or a list of them, as the summary shows it. An object is not a routing or policy value the table can name.
282
+ function showValue(value) {
283
+ if (typeof value === 'string') return value;
284
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
285
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
286
+ if (Array.isArray(value)) return value.map(showValue).filter(Boolean).join(', ');
287
+ return '';
288
+ }
289
+ const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
290
+ // Known keys first, in `order`, then any other own key, sorted. `skip` names keys a table already showed.
291
+ function orderedEntries(obj, order, skip) {
292
+ const src = object(obj), seen = new Set(skip || []), out = [];
293
+ for (const key of order) {
294
+ if (has(src, key)) { out.push([key, src[key]]); seen.add(key); }
295
+ }
296
+ for (const key of Object.keys(src).sort()) {
297
+ if (!seen.has(key)) out.push([key, src[key]]);
298
+ }
299
+ return out;
300
+ }
301
+ function budgetPart(label, tokensKey, usdKey, budget) {
302
+ const hasTokens = has(budget, tokensKey), hasUsd = has(budget, usdKey);
303
+ if (!hasTokens && !hasUsd) return '';
304
+ const bits = [];
305
+ if (hasTokens) bits.push((finite(budget[tokensKey]) ? String(budget[tokensKey]) : 'none') + ' tokens');
306
+ if (hasUsd) bits.push('$' + (finite(budget[usdKey]) ? Number(budget[usdKey]).toFixed(4) : 'none'));
307
+ return label + ' ' + bits.join(', ');
308
+ }
309
+ // One gate as `name mode · provider · model`. A mode string is the short form the file stores.
310
+ function gateText(name, value) {
311
+ if (typeof value === 'string') return name + ' ' + value;
312
+ const g = object(value);
313
+ const bits = [text(g.mode), text(g.provider), text(g.model)].filter(Boolean);
314
+ return bits.length ? name + ' ' + bits.join(' · ') : name;
315
+ }
316
+
317
+ // The selected profile's body, as data. render() draws only this: pools per tier, then the other routing and policy
318
+ // values, then one line each for gates and budget. A missing block is an empty list or ''.
319
+ function describeProfile(body) {
320
+ const b = object(body), routing = object(b.routing), pools = {};
321
+ for (const name of POOLS) {
322
+ const value = routing[name];
323
+ pools[name] = value && typeof value === 'object' && !Array.isArray(value) ? value : null;
324
+ }
325
+ const tierNames = [];
326
+ for (const tier of TIERS) {
327
+ if (POOLS.some(name => pools[name] && has(pools[name], tier))) tierNames.push(tier);
328
+ }
329
+ const known = new Set(TIERS);
330
+ const extra = new Set();
331
+ for (const name of POOLS) {
332
+ if (!pools[name]) continue;
333
+ for (const tier of Object.keys(pools[name])) if (!known.has(tier)) extra.add(tier);
334
+ }
335
+ for (const tier of [...extra].sort()) tierNames.push(tier);
336
+ const tiers = tierNames.map(tier => ({
337
+ tier,
338
+ dwarf: (pools.dwarf && showValue(pools.dwarf[tier])) || '—',
339
+ qa: (pools.qa && showValue(pools.qa[tier])) || '—',
340
+ })).filter(row => row.dwarf !== '—' || row.qa !== '—');
341
+ const poolSkip = POOLS.filter(name => pools[name]);
342
+ const routingLines = orderedEntries(routing, ROUTING_ORDER, poolSkip)
343
+ .map(([key, value]) => ({ key, text: showValue(value) }))
344
+ .filter(row => row.text);
345
+ const policy = orderedEntries(b.policy, POLICY_ORDER)
346
+ .map(([key, value]) => ({ key, text: showValue(value) }))
347
+ .filter(row => row.text);
348
+ const gates = b.gates && typeof b.gates === 'object' && !Array.isArray(b.gates)
349
+ ? Object.keys(b.gates).sort().map(name => gateText(name, b.gates[name])).join('; ') : '';
350
+ const budgetObj = b.budget && typeof b.budget === 'object' && !Array.isArray(b.budget) ? b.budget : {};
351
+ const budgetBits = BUDGET_PAIRS.map(([label, tokens, usd]) => budgetPart(label, tokens, usd, budgetObj)).filter(Boolean);
352
+ const budgetSeen = new Set(BUDGET_PAIRS.flatMap(([, tokens, usd]) => [tokens, usd]));
353
+ for (const key of Object.keys(budgetObj).sort()) {
354
+ if (!budgetSeen.has(key)) {
355
+ const shown = showValue(budgetObj[key]);
356
+ if (shown) budgetBits.push(key + ' ' + shown);
357
+ }
358
+ }
359
+ return { tiers, routing: routingLines, policy, gates, budget: budgetBits.join('; ') };
360
+ }
361
+
362
+ // The POST /api/config/profiles body for one action. `use` with none clears the default and carries no name.
363
+ // create carries `from` or `body`, never both; a missing body is the blank profile {}.
364
+ function profileRequest(run, spec) {
365
+ const s = object(spec), action = text(s.action);
366
+ const body = { run: String(run == null ? '' : run), action };
367
+ if (s.level != null) body.level = String(s.level);
368
+ if (action === 'use' && s.none === true) { body.none = true; return body; }
369
+ if (s.name != null) body.name = String(s.name);
370
+ if (action === 'create' && s.from != null && text(s.from) !== '') body.from = String(s.from);
371
+ else if (action === 'create' || action === 'edit') body.body = object(s.body);
372
+ if (action === 'set' || action === 'unset') body.key = String(s.key == null ? '' : s.key);
373
+ if (action === 'set') body.value = String(s.value == null ? '' : s.value);
374
+ return body;
375
+ }
376
+ // The create spec for a blank profile, or a copy of `source` ({name, level, body}). A user-level write passes
377
+ // no --repo, so --from resolves against the user file and the built-ins only. A repo profile is not there: the
378
+ // CLI reports it missing, or copies a built-in of the same name. Send the body the list shows instead.
379
+ // Every other copy is `from`, which is what a repo-level write resolves, and what a user-level copy of a user
380
+ // or built-in profile resolves.
381
+ function profileCopySpec(name, level, source) {
382
+ const spec = { action: 'create', name: text(name), level: text(level) };
383
+ const row = source && typeof source === 'object' ? source : null;
384
+ const sourceName = row ? text(row.name) : '';
385
+ if (!sourceName) { spec.body = {}; return spec; }
386
+ if (spec.level === 'user' && text(row.level) === 'repo') spec.body = object(row.body);
387
+ else spec.from = sourceName;
388
+ return spec;
389
+ }
390
+ // `use --none` clears default_profile in the file that stores it. That file's level is payload.default.level
391
+ // (the user file, else the repo file), not the profile's own level: a repo default_profile can name a user
392
+ // profile, and clearing the user file would leave the repo default in effect while the CLI still says it cleared.
393
+ // The profile's level is only the fallback when the payload names no user or repo level.
394
+ function clearDefaultLevel(payload, profileLevel) {
395
+ const stored = text(object(object(payload).default).level);
396
+ if (stored === 'user' || stored === 'repo') return stored;
397
+ return profileLevel === 'repo' ? 'repo' : 'user';
398
+ }
399
+
400
+ // What a row may do. A built-in (and anything that is not user or repo) can only be duplicated: the CLI refuses
401
+ // to edit, remove or store a default at that level.
402
+ function profileOffers(level) {
403
+ const writable = level === 'user' || level === 'repo';
404
+ return { edit: writable, duplicate: true, remove: writable, setDefault: writable };
405
+ }
406
+ // "shadows repo, builtin", or '' when the winning copy hides nothing.
407
+ function shadowLabel(shadowed) {
408
+ const levels = list(shadowed).map(text).filter(Boolean);
409
+ return levels.length ? 'shadows ' + levels.join(', ') : '';
410
+ }
411
+ // The run record's Profile row: `NAME (level)`, and `· flags override: KEY, KEY` when `overridden` lists keys.
412
+ // Null when there is no profile. Anything but a list in `overridden` names no key, so it adds nothing.
413
+ function profileRowText(profile) {
414
+ if (!profile || typeof profile !== 'object' || Array.isArray(profile)) return null;
415
+ const name = text(profile.name), level = text(profile.level);
416
+ if (!name || !level) return null;
417
+ const keys = Array.isArray(profile.overridden) ? profile.overridden.map(text).filter(Boolean) : [];
418
+ return name + ' (' + level + ')' + (keys.length ? ' · flags override: ' + keys.join(', ') : '');
419
+ }
420
+ // The editor's text. Pretty-printed so a refresh of an untouched profile does not look like an edit.
421
+ function profileText(body) {
422
+ try { return JSON.stringify(object(body), null, 2); }
423
+ catch (_) { return '{}'; }
424
+ }
425
+ function profileNameProblem(name) {
426
+ return PROFILE_NAME.test(text(name)) ? null : 'Use 1–64 letters, digits, ".", "_" or "-", starting with a letter or digit.';
427
+ }
428
+ // Why this text cannot be posted as a profile body, or null. The CLI still checks the keys.
429
+ function profileJsonProblem(value) {
430
+ const v = text(value);
431
+ if (!v.trim()) return 'Empty: a profile body is a JSON object.';
432
+ let parsed;
433
+ try { parsed = JSON.parse(v); }
434
+ catch (_) { return 'Not valid JSON.'; }
435
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return 'A profile body is a JSON object.';
436
+ return null;
437
+ }
438
+ // The CLI's reasons for a refused write. Exit 2's HTTP detail is only the last line; the whole list is result.error,
439
+ // one reason per line. Empty when the write succeeded.
440
+ function refusalReasons(res) {
441
+ if (!res || res.ok) return [];
442
+ const err = res.result && typeof res.result.error === 'string' ? res.result.error : '';
443
+ const lines = err.split('\n').map(line => line.trim()).filter(Boolean);
444
+ if (lines.length) return lines;
445
+ const detail = typeof res.detail === 'string' ? res.detail.trim() : '';
446
+ return detail ? [detail] : [];
447
+ }
448
+
244
449
  /* ---------- DOM ---------- */
245
450
  function render(host, ctx) {
246
451
  const UI = root.ForgeUI, c = ctx || {};
247
452
  const el = (tag, t, cls) => UI.el(tag, t, cls);
248
- const s = { run: null, data: null, dataText: null, error: null, writes: false, loading: true, editors: {}, moved: {}, models: {}, modelMoved: {}, hold: 0, redraw: false, seq: 0, gen: 0, runsSig: null, ready: false, loadedAt: 0, repo: null, gone: false, asking: 0, asks: 0, pickerLate: false, listOpen: false };
453
+ const s = { run: null, data: null, dataText: null, error: null, writes: false, loading: true, editors: {}, moved: {}, models: {}, modelMoved: {}, hold: 0, redraw: false, seq: 0, gen: 0, runsSig: null, ready: false, loadedAt: 0, repo: null, gone: false, asking: 0, asks: 0, pickerLate: false, listOpen: false,
454
+ profiles: null, profilesText: null, profilesError: null, profileKey: null, profileEditors: {}, profileMoved: {}, profileReasons: [], profileReasonFor: null,
455
+ forms: { create: { name: '', level: 'user', source: '' }, duplicate: null } };
249
456
  const key_ = (label, cls, onclick) => { const b = el('button', label, cls); b.type = 'button'; if (onclick) b.addEventListener('click', onclick); return b; };
250
457
 
251
458
  const head = el('header', undefined, 'set-head');
252
459
  head.append(el('h1', 'Settings', 'module-title'),
253
- el('p', 'What forge reads when it runs: its model registry, the decision-model gates, and the three files a repository can keep in .forge.', 'muted set-lede'));
460
+ el('p', 'What forge reads when it runs: its model registry, the decision-model gates, named profiles, and the three files a repository can keep in .forge.', 'muted set-lede'));
254
461
  const picker = el('div', undefined, 'set-picker');
255
462
  const body = el('div', undefined, 'set-body');
256
463
  const note = el('p', 'This page is read-only: this server has no write token, or has controls off.', 'muted set-readonly');
@@ -287,14 +494,14 @@
287
494
  const before = s.run, usable = withRepo(runs);
288
495
  let kept = false;
289
496
  s.gone = false;
290
- if (s.run != null && !usable.some(r => r.key === s.run)) {
291
- // The run left the list. Another run of the same repository carries on with the editors as they are; with unsaved
292
- // text and no such run the page stays on it, flagged, rather than throwing the text away.
497
+ // File editors and profile JSON both count. A poll that drops this run must not switch repositories
498
+ // while either is dirty: resetRun would drop the text.
499
+ const departure = departedRun(s.run, s.repo, runs, unsavedLabels(s.editors, s.profileEditors).length > 0);
500
+ if (departure === 'keep') {
293
501
  const sibling = usable.slice().sort(newestFirst).find(r => RM.repoKey(r) === s.repo);
294
502
  if (sibling) { s.run = sibling.key; kept = true; }
295
- else if (FILES.some(n => isDirty(s.editors[n]))) s.gone = true;
296
- else s.run = null;
297
- }
503
+ } else if (departure === 'stay') s.gone = true;
504
+ else if (departure === 'drop') s.run = null;
298
505
  if (s.run == null) s.run = pickDefault(runs, c.key);
299
506
  const now = usable.find(r => r.key === s.run);
300
507
  if (now) s.repo = RM.repoKey(now);
@@ -393,10 +600,10 @@
393
600
  async function choose(key) {
394
601
  close();
395
602
  if (key === btn.dataset.run) return; // the run already shown
396
- const unsaved = FILES.filter(n => s.editors[n] && isDirty(s.editors[n]));
603
+ const unsaved = unsavedLabels(s.editors, s.profileEditors);
397
604
  if (unsaved.length) {
398
605
  const ask = s.asking = ++s.asks;
399
- const yes = await UI.confirmInline(picker, `Switch repository and discard the unsaved edits to ${unsaved.map(n => '.forge/' + n).join(', ')}?`, { danger: true });
606
+ const yes = await UI.confirmInline(picker, `Switch repository and discard the unsaved edits to ${unsaved.join(', ')}?`, { danger: true });
400
607
  if (s.asking !== ask) return; // a later choice asked again, and that confirm decides
401
608
  const late = s.pickerLate;
402
609
  s.asking = 0; s.pickerLate = false;
@@ -419,6 +626,9 @@
419
626
  function resetRun() {
420
627
  staleNote(null);
421
628
  s.data = null; s.dataText = null; s.error = null; s.editors = {}; s.moved = {}; s.models = {}; s.modelMoved = {}; s.loading = s.run != null;
629
+ s.profiles = null; s.profilesText = null; s.profilesError = null; s.profileKey = null;
630
+ s.profileEditors = {}; s.profileMoved = {}; s.profileReasons = []; s.profileReasonFor = null;
631
+ s.forms = { create: { name: '', level: 'user', source: '' }, duplicate: null };
422
632
  s.gen++; s.hold = 0; s.redraw = false;
423
633
  }
424
634
  function pick(key) {
@@ -430,17 +640,55 @@
430
640
  }
431
641
 
432
642
  /* loading, and keeping unsaved text across it */
643
+ const profileId = row => text(row && row.name) + '\0' + text(row && row.level);
644
+ // Fold a profiles read into the page. A failed read keeps the previous list when there is one. An editor's unsaved
645
+ // JSON stays; `moved` says the stored body changed under it.
646
+ function applyProfiles(res) {
647
+ if (!res || !res.ok) {
648
+ const failed = readFailure(res, s.profiles);
649
+ s.profilesError = failed.message;
650
+ if (!failed.keep) { s.profiles = null; }
651
+ return;
652
+ }
653
+ s.profilesError = null;
654
+ const data = object(res.data), rows = list(data.profiles);
655
+ for (const row of rows) {
656
+ const key = profileId(row);
657
+ if (!s.profileEditors[key]) continue;
658
+ const next = dirtyState(s.profileEditors[key], profileText(row.body));
659
+ s.profileEditors[key] = next.editor;
660
+ s.profileMoved[key] = next.moved || (next.dirty && !!s.profileMoved[key]);
661
+ }
662
+ if (!rows.some(row => profileId(row) === s.profileKey)) {
663
+ const def = rows.find(row => row.default) || rows[0];
664
+ s.profileKey = def ? profileId(def) : null;
665
+ }
666
+ s.profiles = data;
667
+ }
433
668
  async function load() {
434
669
  const run = s.run, seq = ++s.seq;
435
670
  if (run == null) { s.loading = false; drawBody(); return; }
436
671
  if (s.gone) return; // the run is not listed: nothing to read until another is picked
437
672
  s.loadedAt = Date.now();
438
- const res = await UI.get('/api/config?run=' + encodeURIComponent(run));
673
+ const query = encodeURIComponent(run);
674
+ const [res, pres] = await Promise.all([
675
+ UI.get('/api/config?run=' + query),
676
+ UI.get('/api/config/profiles?run=' + query),
677
+ ]);
439
678
  if (seq !== s.seq || run !== s.run) return; // a later pick or load answered
440
679
  s.loading = false;
441
680
  if (!res.ok) {
442
681
  const failed = readFailure(res, s.data);
443
- if (failed.keep) { staleNote(failed.message); return; } // the last good page, its editors and their unsaved text stay
682
+ if (failed.keep) { // the last good page, its editors and their unsaved text stay
683
+ staleNote(failed.message);
684
+ applyProfiles(pres);
685
+ const pt = JSON.stringify([s.profiles, s.profilesError]);
686
+ if (pt !== s.profilesText) {
687
+ s.profilesText = pt;
688
+ if (s.hold > 0) s.redraw = true; else drawBody();
689
+ }
690
+ return;
691
+ }
444
692
  if (s.hold > 0) return; // a confirm or a write is open: its strip must not be torn down
445
693
  s.error = failed.message; s.data = null; s.dataText = null; drawBody(); return;
446
694
  }
@@ -454,9 +702,11 @@
454
702
  const next = dirtyState(s.models[g.name], g.model);
455
703
  s.models[g.name] = next.editor; s.modelMoved[g.name] = next.moved || (next.dirty && !!s.modelMoved[g.name]);
456
704
  }
705
+ applyProfiles(pres);
457
706
  const t = JSON.stringify(res.data);
458
- if (t === s.dataText && !s.redraw) return;
459
- s.data = res.data; s.dataText = t;
707
+ const pt = JSON.stringify([s.profiles, s.profilesError]);
708
+ if (t === s.dataText && pt === s.profilesText && !s.redraw) return;
709
+ s.data = res.data; s.dataText = t; s.profilesText = pt;
460
710
  drawPicker(); // its path line names the repository this read came from
461
711
  if (s.hold > 0) { s.redraw = true; return; } // a confirm or a write is open: draw after it
462
712
  drawBody();
@@ -470,15 +720,19 @@
470
720
  function drawBody() {
471
721
  const focus = document.activeElement && body.contains(document.activeElement) ? document.activeElement : null;
472
722
  const at = focus && focus.dataset.editor ? { kind: 'editor', name: focus.dataset.editor, a: focus.selectionStart, b: focus.selectionEnd }
473
- : focus && focus.dataset.model ? { kind: 'model', name: focus.dataset.model, a: focus.selectionStart, b: focus.selectionEnd } : null;
723
+ : focus && focus.dataset.model ? { kind: 'model', name: focus.dataset.model, a: focus.selectionStart, b: focus.selectionEnd }
724
+ : focus && focus.dataset.profileEditor ? { kind: 'profile', a: focus.selectionStart, b: focus.selectionEnd }
725
+ : focus && focus.id ? { kind: 'id', id: focus.id, a: focus.selectionStart, b: focus.selectionEnd } : null;
474
726
  if (s.loading) { body.replaceChildren(el('p', 'Reading the configuration…', 'muted')); return; }
475
727
  if (s.error) { body.replaceChildren(el('p', 'Could not read the configuration: ' + s.error, 'warn')); return; }
476
728
  if (!s.data) { body.replaceChildren(); return; }
477
- body.replaceChildren(registrySection(), decideSection(), repoSection(), datasetSection(), envSection());
478
- if (at) {
479
- const t = at.kind === 'model' ? body.querySelector(`input[data-model="${at.name}"]`) : body.querySelector(`textarea[data-editor="${at.name}"]`);
480
- if (t) { t.focus({ preventScroll: true }); try { t.setSelectionRange(at.a, at.b); } catch (_) { /* not selectable */ } }
481
- }
729
+ body.replaceChildren(registrySection(), decideSection(), profilesSection(), repoSection(), datasetSection(), envSection());
730
+ if (!at) return;
731
+ const t = at.kind === 'model' ? body.querySelector(`input[data-model="${at.name}"]`)
732
+ : at.kind === 'editor' ? body.querySelector(`textarea[data-editor="${at.name}"]`)
733
+ : at.kind === 'profile' ? body.querySelector('textarea[data-profile-editor]')
734
+ : document.getElementById(at.id);
735
+ if (t && body.contains(t)) { t.focus({ preventScroll: true }); try { t.setSelectionRange(at.a, at.b); } catch (_) { /* not selectable */ } }
482
736
  }
483
737
 
484
738
  /* sections */
@@ -811,6 +1065,513 @@
811
1065
  return art;
812
1066
  }
813
1067
 
1068
+ function profilesSection() {
1069
+ const sec = section('profiles', 'Profiles', 'A named bundle of routing, policy, gates and budget. A user profile hides a repo profile of the same name, which hides a built-in. Editing writes decide.json at the profile\'s level.');
1070
+ if (s.profilesError && !s.profiles) {
1071
+ sec.append(el('p', 'Could not read profiles: ' + s.profilesError, 'warn'));
1072
+ return sec;
1073
+ }
1074
+ if (!s.profiles) { sec.append(el('p', 'Reading profiles…', 'muted')); return sec; }
1075
+ if (s.profilesError) sec.append(el('p', 'The last read of profiles failed: ' + s.profilesError + '. This shows the read before it.', 'warn set-problem'));
1076
+ const rows = list(s.profiles.profiles);
1077
+ if (!rows.length) sec.append(el('p', 'No profiles.', 'muted'));
1078
+ else sec.append(profileList(rows));
1079
+ const row = rows.find(item => profileId(item) === s.profileKey);
1080
+ if (row) sec.append(profileDetail(row));
1081
+ if (s.writes) sec.append(newProfileForm(rows));
1082
+ return sec;
1083
+ }
1084
+
1085
+ function profileList(rows) {
1086
+ const ul = el('ul', undefined, 'set-profiles');
1087
+ ul.setAttribute('aria-label', 'Profiles');
1088
+ for (const row of rows) {
1089
+ const li = el('li');
1090
+ const on = profileId(row) === s.profileKey;
1091
+ const b = el('button', undefined, 'set-profile');
1092
+ b.type = 'button';
1093
+ b.id = 'set-prof-' + text(row.name);
1094
+ b.dataset.profile = text(row.name);
1095
+ b.dataset.level = text(row.level);
1096
+ b.setAttribute('aria-pressed', on ? 'true' : 'false');
1097
+ const shadow = shadowLabel(row.shadowed);
1098
+ b.setAttribute('aria-label', [text(row.name), text(row.level), row.default ? 'default' : '', shadow].filter(Boolean).join(', '));
1099
+ b.append(el('span', text(row.name), 'set-profile-name'), el('span', text(row.level), 'tag'));
1100
+ if (row.default) b.append(el('span', 'default', 'tag'));
1101
+ if (shadow) b.append(el('span', shadow, 'set-profile-meta'));
1102
+ b.addEventListener('click', () => {
1103
+ const key = profileId(row);
1104
+ if (s.profileKey === key) return;
1105
+ s.profileKey = key;
1106
+ s.forms.duplicate = null;
1107
+ s.profileReasons = [];
1108
+ s.profileReasonFor = null;
1109
+ drawBody();
1110
+ const again = document.getElementById(b.id);
1111
+ if (again) again.focus({ preventScroll: true });
1112
+ });
1113
+ li.append(b);
1114
+ ul.append(li);
1115
+ }
1116
+ return ul;
1117
+ }
1118
+
1119
+ function summaryBlock(title, id) {
1120
+ const block = el('div');
1121
+ block.id = id;
1122
+ block.append(el('p', title, 'plate'));
1123
+ return block;
1124
+ }
1125
+ function profileSummary(body) {
1126
+ const view = describeProfile(body);
1127
+ const box = el('div', undefined, 'set-profile-summary');
1128
+ if (view.tiers.length) {
1129
+ const wrap = el('div', undefined, 'set-table-wrap');
1130
+ const table = el('table', undefined, 'set-table');
1131
+ const cap = el('caption', 'Dwarf and QA pools by tier', 'visually-hidden');
1132
+ const hr = el('tr');
1133
+ for (const h of ['Tier', 'Dwarf', 'QA']) { const th = el('th', h); th.scope = 'col'; hr.append(th); }
1134
+ const thead = el('thead'); thead.append(hr);
1135
+ const tbody = el('tbody');
1136
+ for (const tier of view.tiers) {
1137
+ const tr = el('tr');
1138
+ const th = el('th', tier.tier, 'set-alias'); th.scope = 'row';
1139
+ tr.append(th, el('td', tier.dwarf, 'mono'), el('td', tier.qa, 'mono'));
1140
+ tbody.append(tr);
1141
+ }
1142
+ table.append(cap, thead, tbody);
1143
+ wrap.append(table);
1144
+ box.append(wrap);
1145
+ }
1146
+ if (view.routing.length) {
1147
+ const block = summaryBlock('Routing', 'set-profile-routing');
1148
+ const dl = el('dl', undefined, 'set-kv');
1149
+ for (const item of view.routing) dl.append(el('dt', item.key), el('dd', item.text, 'mono'));
1150
+ block.append(dl);
1151
+ box.append(block);
1152
+ }
1153
+ if (view.policy.length) {
1154
+ const block = summaryBlock('Policy', 'set-profile-policy');
1155
+ const dl = el('dl', undefined, 'set-kv');
1156
+ for (const item of view.policy) dl.append(el('dt', item.key), el('dd', item.text, 'mono'));
1157
+ block.append(dl);
1158
+ box.append(block);
1159
+ }
1160
+ if (view.gates) {
1161
+ const block = summaryBlock('Gates', 'set-profile-gates');
1162
+ block.append(el('p', view.gates, 'mono set-summary-line'));
1163
+ box.append(block);
1164
+ }
1165
+ if (view.budget) {
1166
+ const block = summaryBlock('Budget', 'set-profile-budget');
1167
+ block.append(el('p', view.budget, 'mono set-summary-line'));
1168
+ box.append(block);
1169
+ }
1170
+ const source = text(object(body).source);
1171
+ if (source) {
1172
+ const block = summaryBlock('Source', 'set-profile-source');
1173
+ block.append(el('p', source, 'muted set-summary-line'));
1174
+ box.append(block);
1175
+ }
1176
+ if (!box.childElementCount) box.append(el('p', 'This profile sets nothing.', 'muted'));
1177
+ return box;
1178
+ }
1179
+
1180
+ function showReasons(row) {
1181
+ if (s.profileReasonFor !== profileId(row) || !s.profileReasons.length) return null;
1182
+ const ul = el('ul', undefined, 'set-reasons');
1183
+ ul.id = 'set-profile-reasons';
1184
+ for (const reason of s.profileReasons) ul.append(el('li', reason));
1185
+ return ul;
1186
+ }
1187
+
1188
+ function profileEditor(row, result) {
1189
+ const key = profileId(row);
1190
+ const fresh = profileText(row.body);
1191
+ const ed = s.profileEditors[key] || (s.profileEditors[key] = editorOf(fresh));
1192
+ const id = 'set-profile-body';
1193
+ const lab = el('label', 'Body of ' + text(row.name) + ' as JSON', 'visually-hidden');
1194
+ lab.htmlFor = id;
1195
+ const ta = el('textarea', undefined, 'set-editor mono');
1196
+ ta.id = id;
1197
+ ta.dataset.profileEditor = '1';
1198
+ ta.rows = Math.max(6, Math.min(18, shown(ed).split('\n').length + 1));
1199
+ ta.spellcheck = false;
1200
+ ta.setAttribute('autocapitalize', 'off');
1201
+ ta.setAttribute('autocomplete', 'off');
1202
+ ta.value = shown(ed);
1203
+ let from = ed.base;
1204
+ const movedNote = el('p', 'The profile changed after you began editing; saving replaces it with your text.', 'warn set-file-note');
1205
+ movedNote.hidden = !(isDirty(ed) && s.profileMoved[key]);
1206
+ const problem = el('p', undefined, 'warn set-problem');
1207
+ problem.hidden = true;
1208
+ problem.id = id + '-problem';
1209
+ const save = key_('Save', 'primary');
1210
+ save.id = 'set-profile-save';
1211
+ save.setAttribute('aria-label', 'Save profile ' + text(row.name));
1212
+ const sync = () => {
1213
+ const cur = s.profileEditors[key], dirtyNow = isDirty(cur);
1214
+ const bad = dirtyNow ? profileJsonProblem(cur.draft) : null;
1215
+ const reasons = s.profileReasonFor === key ? s.profileReasons : [];
1216
+ problem.hidden = !bad;
1217
+ problem.textContent = bad || '';
1218
+ const described = [bad ? problem.id : '', reasons.length ? 'set-profile-reasons' : ''].filter(Boolean).join(' ');
1219
+ if (bad || reasons.length) {
1220
+ ta.setAttribute('aria-invalid', 'true');
1221
+ if (described) ta.setAttribute('aria-describedby', described);
1222
+ } else {
1223
+ ta.removeAttribute('aria-invalid');
1224
+ ta.removeAttribute('aria-describedby');
1225
+ }
1226
+ save.disabled = !dirtyNow || !!bad;
1227
+ movedNote.hidden = !(dirtyNow && s.profileMoved[key]);
1228
+ };
1229
+ ta.addEventListener('input', () => {
1230
+ const next = typed(s.profileEditors[key], ta.value, from);
1231
+ s.profileEditors[key] = next.editor;
1232
+ s.profileMoved[key] = next.moved || (next.dirty && !!s.profileMoved[key]);
1233
+ if (s.profileReasonFor === key) {
1234
+ s.profileReasons = []; s.profileReasonFor = null;
1235
+ const old = document.getElementById('set-profile-reasons');
1236
+ if (old) old.remove();
1237
+ }
1238
+ sync();
1239
+ });
1240
+ save.addEventListener('click', async () => {
1241
+ const cur = s.profileEditors[key];
1242
+ const bad = profileJsonProblem(shown(cur));
1243
+ if (!isDirty(cur) || bad) { sync(); return; }
1244
+ let parsed;
1245
+ try { parsed = JSON.parse(cur.draft); } catch (_) { sync(); return; }
1246
+ const gen = s.gen, release = grab();
1247
+ save.disabled = true;
1248
+ ta.readOnly = true;
1249
+ const yes = await UI.confirmInline(result, `Replace the body of profile ${text(row.name)} at the ${text(row.level)} level?`);
1250
+ if (!yes || gen !== s.gen) {
1251
+ ta.readOnly = false;
1252
+ release();
1253
+ sync();
1254
+ if (!yes && gen === s.gen) save.focus({ preventScroll: true });
1255
+ return;
1256
+ }
1257
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, { action: 'edit', name: row.name, level: row.level, body: parsed }));
1258
+ const reasons = refusalReasons(res);
1259
+ s.profileReasons = res.ok ? [] : reasons;
1260
+ s.profileReasonFor = res.ok ? null : key;
1261
+ UI.outcome(result, res, `Saved ${text(row.name)}.`);
1262
+ if (res.ok && gen === s.gen) {
1263
+ s.profileEditors[key] = editorOf(profileText(parsed));
1264
+ s.profileMoved[key] = false;
1265
+ from = s.profileEditors[key].base;
1266
+ }
1267
+ ta.readOnly = false;
1268
+ release();
1269
+ // A refusal keeps this textarea. The reasons go under it; a redraw would drop the outcome line.
1270
+ if (!res.ok && gen === s.gen && ta.isConnected) {
1271
+ const old = document.getElementById('set-profile-reasons');
1272
+ if (old) old.remove();
1273
+ const list = showReasons(row);
1274
+ const editor = ta.closest('.set-profile-editor');
1275
+ if (list && editor) editor.after(list);
1276
+ }
1277
+ if (gen === s.gen && ta.isConnected) sync();
1278
+ if (res.ok && gen === s.gen) await reload();
1279
+ });
1280
+ const wrap = el('div', undefined, 'set-profile-editor');
1281
+ wrap.append(lab, ta, problem, movedNote, save);
1282
+ sync();
1283
+ return wrap;
1284
+ }
1285
+
1286
+ function duplicateForm(row, result) {
1287
+ const draft = s.forms.duplicate;
1288
+ const form = el('div', undefined, 'set-profile-form');
1289
+ form.id = 'set-dup-form';
1290
+ const name = el('input');
1291
+ name.type = 'text';
1292
+ name.id = 'set-dup-name';
1293
+ name.value = draft.name;
1294
+ name.spellcheck = false;
1295
+ name.setAttribute('autocomplete', 'off');
1296
+ name.setAttribute('autocapitalize', 'off');
1297
+ const nameLab = el('label', undefined, 'filter');
1298
+ nameLab.htmlFor = name.id;
1299
+ nameLab.append(el('span', 'New name'), name);
1300
+ const sel = el('select');
1301
+ sel.id = 'set-dup-level';
1302
+ sel.setAttribute('aria-label', 'Level for the copy of ' + text(row.name));
1303
+ for (const level of WRITE_LEVELS) {
1304
+ const o = el('option', level);
1305
+ o.value = level;
1306
+ o.selected = level === draft.level;
1307
+ sel.append(o);
1308
+ }
1309
+ const levelLab = el('label', undefined, 'filter');
1310
+ levelLab.htmlFor = sel.id;
1311
+ levelLab.append(el('span', 'Level'), sel);
1312
+ const problem = el('p', undefined, 'warn set-problem');
1313
+ problem.hidden = true;
1314
+ problem.id = 'set-dup-problem';
1315
+ const go = key_('Create copy', 'primary');
1316
+ go.id = 'set-dup-save';
1317
+ go.setAttribute('aria-label', 'Create a copy of ' + text(row.name));
1318
+ const cancel = key_('Cancel');
1319
+ cancel.id = 'set-dup-cancel';
1320
+ cancel.setAttribute('aria-label', 'Cancel duplicating ' + text(row.name));
1321
+ name.addEventListener('input', () => { draft.name = name.value; problem.hidden = true; name.removeAttribute('aria-invalid'); });
1322
+ sel.addEventListener('change', () => { draft.level = sel.value; });
1323
+ cancel.addEventListener('click', () => {
1324
+ s.forms.duplicate = null;
1325
+ drawBody();
1326
+ const again = document.getElementById('set-profile-duplicate');
1327
+ if (again) again.focus({ preventScroll: true });
1328
+ });
1329
+ go.addEventListener('click', async () => {
1330
+ const bad = profileNameProblem(draft.name);
1331
+ if (bad) {
1332
+ problem.hidden = false;
1333
+ problem.textContent = bad;
1334
+ name.setAttribute('aria-invalid', 'true');
1335
+ name.setAttribute('aria-describedby', problem.id);
1336
+ name.focus({ preventScroll: true });
1337
+ return;
1338
+ }
1339
+ const gen = s.gen, release = grab();
1340
+ go.disabled = true;
1341
+ name.readOnly = true;
1342
+ const yes = await UI.confirmInline(result, `Create profile ${draft.name} at the ${draft.level} level as a copy of ${text(row.name)}?`);
1343
+ if (!yes || gen !== s.gen) {
1344
+ go.disabled = false;
1345
+ name.readOnly = false;
1346
+ release();
1347
+ if (!yes && gen === s.gen) go.focus({ preventScroll: true });
1348
+ return;
1349
+ }
1350
+ const created = draft.name, level = draft.level;
1351
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, profileCopySpec(created, level, row)));
1352
+ UI.outcome(result, res, `Created ${created}.`);
1353
+ name.readOnly = false;
1354
+ if (res.ok && gen === s.gen) {
1355
+ s.profileKey = created + '\0' + level;
1356
+ s.forms.duplicate = null;
1357
+ } else go.disabled = false;
1358
+ release();
1359
+ if (res.ok && gen === s.gen) await reload();
1360
+ });
1361
+ const keys = el('div', undefined, 'set-keys');
1362
+ keys.append(go, cancel);
1363
+ form.append(nameLab, levelLab, problem, keys);
1364
+ return form;
1365
+ }
1366
+
1367
+ function defaultButton(row, result) {
1368
+ const clearing = row.default === true;
1369
+ // Setting writes default_profile at the profile's own level. Clearing removes it from the file that
1370
+ // actually stores it, which can be the other level (a repo default_profile naming a user profile).
1371
+ const level = clearing ? clearDefaultLevel(s.profiles, row.level) : text(row.level);
1372
+ const label = clearing ? 'Clear default' : 'Set as default';
1373
+ const b = key_(label);
1374
+ b.id = 'set-profile-default';
1375
+ b.setAttribute('aria-label', clearing
1376
+ ? 'Clear the default profile at the ' + level + ' level'
1377
+ : 'Set ' + text(row.name) + ' as the default profile at the ' + level + ' level');
1378
+ b.addEventListener('click', async () => {
1379
+ const gen = s.gen, release = grab();
1380
+ b.disabled = true;
1381
+ const question = clearing
1382
+ ? `Clear the default profile at the ${level} level?`
1383
+ : `Set ${text(row.name)} as the default profile at the ${level} level?`;
1384
+ const yes = await UI.confirmInline(result, question);
1385
+ if (!yes || gen !== s.gen) {
1386
+ b.disabled = false;
1387
+ release();
1388
+ if (!yes && gen === s.gen) b.focus({ preventScroll: true });
1389
+ return;
1390
+ }
1391
+ const spec = clearing
1392
+ ? { action: 'use', level, none: true }
1393
+ : { action: 'use', name: row.name, level };
1394
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, spec));
1395
+ UI.outcome(result, res, clearing ? `Cleared the default at the ${level} level.` : `${text(row.name)} is the default at the ${level} level.`);
1396
+ b.disabled = false;
1397
+ release();
1398
+ if (res.ok && gen === s.gen) await reload();
1399
+ });
1400
+ return b;
1401
+ }
1402
+
1403
+ function deleteButton(row, result) {
1404
+ const b = key_('Delete');
1405
+ b.classList.add('set-remove');
1406
+ b.id = 'set-profile-delete';
1407
+ b.setAttribute('aria-label', 'Delete profile ' + text(row.name));
1408
+ b.addEventListener('click', async () => {
1409
+ const gen = s.gen, release = grab();
1410
+ b.disabled = true;
1411
+ const yes = await UI.confirmInline(result, `Delete profile ${text(row.name)} at the ${text(row.level)} level?`, { danger: true });
1412
+ if (!yes || gen !== s.gen) {
1413
+ b.disabled = false;
1414
+ release();
1415
+ if (!yes && gen === s.gen) b.focus({ preventScroll: true });
1416
+ return;
1417
+ }
1418
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, { action: 'rm', name: row.name, level: row.level }));
1419
+ UI.outcome(result, res, `Deleted ${text(row.name)}.`);
1420
+ if (res.ok && gen === s.gen) {
1421
+ const key = profileId(row);
1422
+ delete s.profileEditors[key];
1423
+ delete s.profileMoved[key];
1424
+ s.profileKey = null;
1425
+ s.profileReasons = [];
1426
+ s.profileReasonFor = null;
1427
+ } else b.disabled = false;
1428
+ release();
1429
+ if (res.ok && gen === s.gen) await reload();
1430
+ });
1431
+ return b;
1432
+ }
1433
+
1434
+ function profileDetail(row) {
1435
+ const offers = profileOffers(row.level);
1436
+ const art = el('article', undefined, 'set-file set-profile-detail');
1437
+ art.id = 'set-profile-detail';
1438
+ const h = el('h3', text(row.name), 'set-file-name');
1439
+ h.id = 'set-profile-detail-h';
1440
+ art.setAttribute('aria-labelledby', h.id);
1441
+ const status = el('p', undefined, 'set-file-status');
1442
+ status.append(el('span', text(row.level), 'tag'));
1443
+ if (row.default) status.append(el('span', 'default', 'tag'));
1444
+ const shadow = shadowLabel(row.shadowed);
1445
+ if (shadow) status.append(el('span', shadow, 'set-profile-meta'));
1446
+ const top = el('div', undefined, 'set-file-head');
1447
+ top.append(h, status);
1448
+ art.append(top, profileSummary(row.body));
1449
+ if (!offers.edit) art.append(el('p', 'This built-in profile is read-only. Duplicate it to change a copy.', 'muted set-file-blurb'));
1450
+ if (!s.writes) return art;
1451
+ const result = el('div', undefined, 'set-result');
1452
+ result.id = 'set-profile-result';
1453
+ if (offers.edit) art.append(profileEditor(row, result));
1454
+ const reasons = showReasons(row);
1455
+ if (reasons) art.append(reasons);
1456
+ const keys = el('div', undefined, 'set-keys');
1457
+ const dup = key_('Duplicate');
1458
+ dup.id = 'set-profile-duplicate';
1459
+ dup.setAttribute('aria-label', 'Duplicate profile ' + text(row.name));
1460
+ dup.addEventListener('click', () => {
1461
+ if (s.forms.duplicate && s.forms.duplicate.of === profileId(row)) return;
1462
+ s.forms.duplicate = { of: profileId(row), name: '', level: row.level === 'repo' ? 'repo' : 'user' };
1463
+ drawBody();
1464
+ const field = document.getElementById('set-dup-name');
1465
+ if (field) field.focus({ preventScroll: true });
1466
+ });
1467
+ keys.append(dup);
1468
+ if (offers.setDefault) keys.append(defaultButton(row, result));
1469
+ if (offers.remove) keys.append(deleteButton(row, result));
1470
+ art.append(keys);
1471
+ if (s.forms.duplicate && s.forms.duplicate.of === profileId(row)) art.append(duplicateForm(row, result));
1472
+ art.append(result);
1473
+ return art;
1474
+ }
1475
+
1476
+ function newProfileForm(rows) {
1477
+ const draft = s.forms.create;
1478
+ const box = el('div', undefined, 'set-file');
1479
+ box.id = 'set-new';
1480
+ const h = el('h3', 'New profile', 'set-file-name');
1481
+ h.id = 'set-new-h';
1482
+ box.setAttribute('aria-labelledby', h.id);
1483
+ box.append(h, el('p', 'A blank body, or a copy of a profile that already exists.', 'muted set-file-blurb'));
1484
+ const name = el('input');
1485
+ name.type = 'text';
1486
+ name.id = 'set-new-name';
1487
+ name.value = draft.name;
1488
+ name.spellcheck = false;
1489
+ name.setAttribute('autocomplete', 'off');
1490
+ name.setAttribute('autocapitalize', 'off');
1491
+ const nameLab = el('label', undefined, 'filter');
1492
+ nameLab.htmlFor = name.id;
1493
+ nameLab.append(el('span', 'Name'), name);
1494
+ const level = el('select');
1495
+ level.id = 'set-new-level';
1496
+ level.setAttribute('aria-label', 'Level for the new profile');
1497
+ for (const item of WRITE_LEVELS) {
1498
+ const o = el('option', item);
1499
+ o.value = item;
1500
+ o.selected = item === draft.level;
1501
+ level.append(o);
1502
+ }
1503
+ const levelLab = el('label', undefined, 'filter');
1504
+ levelLab.htmlFor = level.id;
1505
+ levelLab.append(el('span', 'Level'), level);
1506
+ const source = el('select');
1507
+ source.id = 'set-new-source';
1508
+ source.setAttribute('aria-label', 'Body for the new profile');
1509
+ const blank = el('option', 'Blank body');
1510
+ blank.value = '';
1511
+ blank.selected = !draft.source;
1512
+ source.append(blank);
1513
+ for (const row of rows) {
1514
+ const o = el('option', text(row.name) + ' (' + text(row.level) + ')');
1515
+ o.value = text(row.name);
1516
+ o.selected = text(row.name) === draft.source;
1517
+ source.append(o);
1518
+ }
1519
+ const sourceLab = el('label', undefined, 'filter');
1520
+ sourceLab.htmlFor = source.id;
1521
+ sourceLab.append(el('span', 'Copy from'), source);
1522
+ const problem = el('p', undefined, 'warn set-problem');
1523
+ problem.hidden = true;
1524
+ problem.id = 'set-new-problem';
1525
+ const result = el('div', undefined, 'set-result');
1526
+ const go = key_('Create', 'primary');
1527
+ go.id = 'set-new-save';
1528
+ go.setAttribute('aria-label', 'Create profile');
1529
+ name.addEventListener('input', () => { draft.name = name.value; problem.hidden = true; name.removeAttribute('aria-invalid'); });
1530
+ level.addEventListener('change', () => { draft.level = level.value; });
1531
+ source.addEventListener('change', () => { draft.source = source.value; });
1532
+ go.addEventListener('click', async () => {
1533
+ const bad = profileNameProblem(draft.name);
1534
+ if (bad) {
1535
+ problem.hidden = false;
1536
+ problem.textContent = bad;
1537
+ name.setAttribute('aria-invalid', 'true');
1538
+ name.setAttribute('aria-describedby', problem.id);
1539
+ name.focus({ preventScroll: true });
1540
+ return;
1541
+ }
1542
+ const sourceRow = draft.source ? rows.find(item => text(item.name) === draft.source) : null;
1543
+ // A chosen name whose row is gone still goes as `from`. A repo profile copied to the user level
1544
+ // cannot: that write passes no --repo, so the spec carries the body instead.
1545
+ const spec = profileCopySpec(draft.name, draft.level, draft.source ? (sourceRow || { name: draft.source }) : null);
1546
+ const gen = s.gen, release = grab();
1547
+ go.disabled = true;
1548
+ name.readOnly = true;
1549
+ const from = draft.source ? `a copy of ${draft.source}` : 'a blank body';
1550
+ const yes = await UI.confirmInline(result, `Create profile ${draft.name} at the ${draft.level} level with ${from}?`);
1551
+ if (!yes || gen !== s.gen) {
1552
+ go.disabled = false;
1553
+ name.readOnly = false;
1554
+ release();
1555
+ if (!yes && gen === s.gen) go.focus({ preventScroll: true });
1556
+ return;
1557
+ }
1558
+ const created = draft.name, at = draft.level;
1559
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, spec));
1560
+ UI.outcome(result, res, `Created ${created}.`);
1561
+ name.readOnly = false;
1562
+ if (res.ok && gen === s.gen) {
1563
+ s.profileKey = created + '\0' + at;
1564
+ s.forms.create = { name: '', level: 'user', source: '' };
1565
+ } else go.disabled = false;
1566
+ release();
1567
+ if (res.ok && gen === s.gen) await reload();
1568
+ });
1569
+ const form = el('div', undefined, 'set-profile-form');
1570
+ form.append(nameLab, levelLab, sourceLab, problem, go);
1571
+ box.append(form, result);
1572
+ return box;
1573
+ }
1574
+
814
1575
  function datasetSection() {
815
1576
  const d = object(s.data.dataset), sec = section('dataset', 'Dataset');
816
1577
  sec.append(pathLine('folder', text(d.path)));
@@ -844,5 +1605,7 @@
844
1605
 
845
1606
  return { render, configBody, repoKey, gateKey, targetPath, subsetOk, valueProblem, decideTextProblem, describeDecide, gateTags, replayDate,
846
1607
  pickDefault, groupRuns, optionLabel, typeAhead, editorOf, isDirty, dirtyState, edited, typed, shown, readFailure,
847
- FILES, GATES, MODES, VALUE_MAX, DECIDE_VALUE_MAX, ADD_COMMAND };
1608
+ unsavedLabels, departedRun,
1609
+ describeProfile, profileRequest, profileCopySpec, clearDefaultLevel, profileOffers, profileRowText, shadowLabel, refusalReasons, profileText, profileJsonProblem, profileNameProblem,
1610
+ FILES, GATES, MODES, VALUE_MAX, DECIDE_VALUE_MAX, ADD_COMMAND, PROFILE_LEVELS, WRITE_LEVELS, TIERS };
848
1611
  });