@giamme/forge 0.14.1 → 0.16.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 (81) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/SKILL.md +47 -14
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +1 -1
  5. package/docs/commands.md +302 -9
  6. package/docs/forge-ui.md +14 -0
  7. package/docs/memory.md +22 -0
  8. package/docs/models.md +53 -0
  9. package/docs/reviews.md +7 -0
  10. package/forge +11 -0
  11. package/package.json +1 -1
  12. package/references/dataset.md +16 -4
  13. package/references/decompose.md +154 -9
  14. package/references/harnesses.md +21 -1
  15. package/references/planning.md +59 -0
  16. package/references/solo.md +5 -1
  17. package/references/ui.md +48 -1
  18. package/scripts/forge-artifact.sh +53 -0
  19. package/scripts/forge-compare.py +6 -3
  20. package/scripts/forge-config.py +531 -4
  21. package/scripts/forge-contract.py +55 -8
  22. package/scripts/forge-control.py +0 -2
  23. package/scripts/forge-dispatch.sh +84 -14
  24. package/scripts/forge-fail-first.py +3 -1
  25. package/scripts/forge-guard.py +247 -8
  26. package/scripts/forge-issues.py +12 -0
  27. package/scripts/forge-lib-adopt.sh +260 -0
  28. package/scripts/forge-lib-attribute.sh +10 -2
  29. package/scripts/forge-lib-plans.sh +35 -6
  30. package/scripts/forge-lib-review.sh +13 -5
  31. package/scripts/forge-lib-task.sh +138 -5
  32. package/scripts/forge-memory.sh +41 -4
  33. package/scripts/forge-metrics.sh +7 -0
  34. package/scripts/forge-parallel-options.sh +12 -6
  35. package/scripts/forge-parallel.sh +659 -32
  36. package/scripts/forge-plan-check.py +591 -8
  37. package/scripts/forge-planner.py +480 -0
  38. package/scripts/forge-route.py +16 -2
  39. package/scripts/forge-runs-rm.py +23 -7
  40. package/scripts/forge-runtime.py +111 -2
  41. package/scripts/forge-schedule.py +5 -2
  42. package/scripts/forge-shadow.py +53 -7
  43. package/scripts/forge-solo.sh +87 -7
  44. package/scripts/forge_dataset/cli.py +26 -0
  45. package/scripts/forge_dataset/efforts.py +215 -0
  46. package/scripts/forge_dataset/export.py +1 -0
  47. package/scripts/forge_dataset/harvest.py +55 -0
  48. package/scripts/forge_dataset/history.py +126 -0
  49. package/scripts/forge_dataset/worktrees.py +95 -0
  50. package/scripts/forge_decide/__init__.py +19 -1
  51. package/scripts/forge_decide/builtin_profiles.json +25 -0
  52. package/scripts/forge_decide/cli.py +12 -0
  53. package/scripts/forge_decide/profiles.py +866 -0
  54. package/scripts/forge_decide/resolve.py +38 -6
  55. package/scripts/forge_memory_list.py +153 -0
  56. package/scripts/forge_worktrees.py +88 -0
  57. package/ui/README.md +31 -0
  58. package/ui/docs/api.md +168 -12
  59. package/ui/forge_ui/__init__.py +14 -1
  60. package/ui/forge_ui/__main__.py +1 -1
  61. package/ui/forge_ui/control.py +250 -12
  62. package/ui/forge_ui/executions.py +28 -8
  63. package/ui/forge_ui/findings.py +7 -0
  64. package/ui/forge_ui/models.py +60 -1
  65. package/ui/forge_ui/projects.py +571 -0
  66. package/ui/forge_ui/reader.py +48 -8
  67. package/ui/forge_ui/static/app.js +99 -21
  68. package/ui/forge_ui/static/cloudui.js +6 -2
  69. package/ui/forge_ui/static/convo.js +1 -1
  70. package/ui/forge_ui/static/diffview.js +2 -2
  71. package/ui/forge_ui/static/files.js +1 -1
  72. package/ui/forge_ui/static/index.html +5 -1
  73. package/ui/forge_ui/static/leaderboard.js +5 -1
  74. package/ui/forge_ui/static/modelstats.js +25 -1
  75. package/ui/forge_ui/static/panel.js +47 -4
  76. package/ui/forge_ui/static/projectsview.js +372 -0
  77. package/ui/forge_ui/static/settings.js +924 -29
  78. package/ui/forge_ui/static/style.css +116 -3
  79. package/ui/forge_ui/static/uikit.js +94 -1
  80. package/ui/forge_ui/static/worktreesview.js +250 -0
  81. package/ui/forge_ui/worktrees.py +570 -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
@@ -25,7 +26,84 @@
25
26
  'coverage', 'retry-addressed', 'dwarf-message', 'attribution', 'findings'];
26
27
  const MODES = ['off', 'shadow', 'on'];
27
28
  const ADD_COMMAND = 'forge decide provider add …';
29
+ // What turning a gate on means, per gate: references/decision-models.md in words a first-time reader can act on. `sends`
30
+ // follows the state the site builds in scripts/forge_jev/; a change there changes what a user agreed to send.
31
+ const GATE_HELP = {
32
+ drift: { summary: 'Predicts files a task will edit but did not declare, so two tasks that touch one file do not run at once.',
33
+ when: 'At plan, once per task.', sends: "The goal, and the task's title, declared files, prompt and approach.",
34
+ on: "Adds each predicted file to the task's files before the waves are computed." },
35
+ forward: { summary: 'Spots an earlier task written against something a later task builds.',
36
+ when: 'At plan, once.', sends: 'The title, files and prompt of the tasks in each pair it checks.',
37
+ on: 'Makes the earlier task wait for the later one, unless that forms a cycle.' },
38
+ prompt: { summary: "Checks that a reviewer could judge a task from the task's own text.",
39
+ when: 'At plan, once per task.', sends: "The goal, the task and its prompt and approach, the plan's other tasks, excerpts of its files, and project memory.",
40
+ on: 'Sends a task whose prompt falls short back to the planner, once.' },
41
+ 'memory-curate': { summary: 'Keeps project memory clean as reviewers and implementers record facts.',
42
+ when: 'Each time a fact is recorded.', sends: 'The new fact and the existing memory entries.',
43
+ on: 'Refiles the fact, merges it with an existing one, or withholds it. The ledger keeps everything.' },
44
+ 'memory-slice': { summary: 'Leaves out memory lines that do not concern the task about to run.',
45
+ when: 'Each time memory is added to a prompt.', sends: 'The task and the memory facts.',
46
+ on: 'Removes lines from what the model is given. It never adds or reorders any.' },
47
+ 'memory-stale': { summary: 'Finds memory facts that are no longer true.',
48
+ when: 'Only during a deep memory prune.', sends: 'The fact and the path of the file it is about.',
49
+ on: 'Drops a fact that went false.' },
50
+ 'verify-discover': { summary: 'Picks a verification command for a repository that has none configured.',
51
+ when: 'When neither --verify nor .forge/verify exists.', sends: "The repository's file list, the candidate commands, and memory's lines about verifying.",
52
+ on: "Runs the chosen command. That command's own result decides verification." },
53
+ coverage: { summary: 'Finds parts of your request that no task covers.',
54
+ when: 'At plan, once.', sends: "Your request, its requirements, and each task's acceptance criteria.",
55
+ on: 'Sends each uncovered requirement back to the planner, once.' },
56
+ 'retry-addressed': { summary: 'Checks that a retry actually touched what its review asked to fix.',
57
+ when: 'On a retry after a review, before the next review.', sends: "The review's blocking findings and the retry's diff.",
58
+ on: 'Sends the retry back to its implementer without paying for a review.' },
59
+ 'dwarf-message': { summary: "Reads an implementer's final message for unfinished work or a question for you.",
60
+ when: "On each implementer's final message, before any review.", sends: "The task's title and the end of the message.",
61
+ on: 'Skips the review of an attempt that says it did not finish, or stops the task to ask you.' },
62
+ attribution: { summary: 'Guesses which merged task broke the combined verification, to shorten the search.',
63
+ when: 'After a combined verification fails.', sends: "The end of the failing log, and each merged task's title, files and diff.",
64
+ on: "Checks the likeliest task first. Nothing is merged, reverted or accepted." },
65
+ findings: { summary: 'Finds review findings that repeat an open issue, and the ones concrete enough to file.',
66
+ when: 'When you run forge issues.', sends: "The findings, and open issues' titles and bodies.",
67
+ on: 'Turns a duplicate into a comment on that issue (posted by forge issues --apply), and pre-selects concrete findings.' },
68
+ };
69
+ // The setup guide, as data. A key never passes through this page: each command runs in the reader's own terminal.
70
+ const SETUP_GUIDE = {
71
+ intro: 'A decision model is a small hosted model that answers narrow questions about your run, in about a second. It is optional and off until you turn a gate on. It never changes a review verdict or makes work pass, and if it fails, the run goes on as if it were off.',
72
+ steps: [
73
+ { title: 'Add a provider', text: 'Run one of these in a terminal. A key is read from stdin or the environment and is stored outside your repositories.',
74
+ commands: [
75
+ ['TypeSafe (Jev)', 'printf \'%s\\n\' "$TYPESAFE_API_KEY" | forge decide provider add jev --name typesafe --key-stdin'],
76
+ ['Cloudflare (Clef)', 'forge decide provider add clef --name cloudflare --account-id <id> --key-env CLOUDFLARE_API_TOKEN'],
77
+ ['A local server, no key', 'forge decide provider add jev --name local --url http://127.0.0.1:8080 --local'],
78
+ ] },
79
+ { title: 'Check that it answers', text: 'This sends one fixed test request with no data from your repositories.',
80
+ commands: [['', 'forge decide doctor --live']] },
81
+ { title: 'Start one gate in shadow', text: 'In shadow a gate asks and records the answer, and the run goes on exactly as if it were off. It does send data: open a gate below to see what. Use the gate\'s mode and provider below, or run:',
82
+ commands: [['', 'forge decide gate memory-curate shadow --provider typesafe']] },
83
+ { title: 'Run forge as usual, then look', text: 'Each answer is kept with the run. These show the gates in effect and how they did.',
84
+ commands: [['', 'forge decide status'], ['', 'forge decide report']] },
85
+ { title: 'Turn a gate on when it has earned it', text: 'A gate goes on only after a replay of its recorded requests passes, which takes about 15 runs of shadow data. Without --send a replay only counts what it would send.',
86
+ commands: [
87
+ ['', 'forge decide replay --site jev-drift --provider typesafe --model jev-latest'],
88
+ ['', 'forge decide replay --site jev-drift --provider typesafe --model jev-latest --send'],
89
+ ['', 'forge decide gate drift on --provider typesafe'],
90
+ ] },
91
+ ],
92
+ stop: [
93
+ ['Keep one repository out', 'forge decide privacy never-send --repo DIR'],
94
+ ['Send nothing while this is set', 'export FORGE_JEV=off'],
95
+ ],
96
+ };
28
97
  const POLL_MS = 20000; // the config rarely changes, and each read starts a CLI process
98
+ // The same order as forge_decide.profiles. A tier or key the body carries and this list does not still shows, after these.
99
+ const TIERS = ['any', 'low', 'medium', 'high'];
100
+ const POOLS = ['dwarf', 'qa'];
101
+ const ROUTING_ORDER = ['planner', 'fractal_planner', 'final_reviewer', 'escalate_after', 'escalate_effort'];
102
+ const POLICY_ORDER = ['qa_threshold', 'retry_failed', 'infra_retries', 'verify_retries', 'timeout', 'explore', 'shadow_rate', 'shadow_qa', 'fast'];
103
+ const BUDGET_PAIRS = [['run', 'run_tokens', 'run_usd'], ['daily', 'daily_tokens', 'daily_usd']];
104
+ const PROFILE_LEVELS = ['user', 'repo', 'builtin'];
105
+ const WRITE_LEVELS = ['user', 'repo']; // POST /api/config/profiles refuses builtin
106
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
29
107
  const list = v => Array.isArray(v) ? v : [];
30
108
  const object = v => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
31
109
  const text = v => typeof v === 'string' ? v : '';
@@ -182,6 +260,16 @@
182
260
  const latest = usable.slice().sort(newestFirst)[0];
183
261
  return latest ? latest.key : null;
184
262
  }
263
+ // The selected run has left the list. 'keep': another run of the same repository takes over and the editors stay.
264
+ // 'stay': nothing of this repository remains, but text is unsaved, so the page holds the gone run instead of
265
+ // picking a new one and discarding that text. 'drop': nothing unsaved, so a new default may replace it.
266
+ // 'here': the run is still listed, or none was selected.
267
+ function departedRun(run, repo, runs, unsaved) {
268
+ const usable = withRepo(runs);
269
+ if (run == null || usable.some(r => r.key === run)) return 'here';
270
+ if (usable.some(r => RM.repoKey(r) === repo)) return 'keep';
271
+ return unsaved ? 'stay' : 'drop';
272
+ }
185
273
  // The choices grouped by repository root: [{repo, name, runs}], the repository of the newest run first.
186
274
  function groupRuns(runs) {
187
275
  const groups = new Map();
@@ -234,6 +322,23 @@
234
322
  return { editor: e, dirty, moved: dirty && norm(from) !== norm(e.base) };
235
323
  }
236
324
  const shown = editor => editor.draft !== null ? editor.draft : editor.base;
325
+ // What a repository switch would discard. A profile's unsaved JSON counts: resetRun drops those editors, so a
326
+ // poll that sees the run leave the list must not move to another repository while one is dirty. Profile keys
327
+ // are `name\0level`. File names stay in the order the page edits them; profile names are sorted.
328
+ function unsavedLabels(editors, profileEditors) {
329
+ const labels = [];
330
+ const files = object(editors);
331
+ for (const name of FILES) {
332
+ if (isDirty(files[name])) labels.push('.forge/' + name);
333
+ }
334
+ const profiles = object(profileEditors);
335
+ for (const key of Object.keys(profiles).sort()) {
336
+ if (!isDirty(profiles[key])) continue;
337
+ const name = text(String(key).split('\0')[0]);
338
+ if (name) labels.push('profile ' + name);
339
+ }
340
+ return labels;
341
+ }
237
342
  // 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
343
  // failure; with none yet, the message replaces the page. Status 0 is no answer at all.
239
344
  function readFailure(res, hasData) {
@@ -241,16 +346,186 @@
241
346
  return { keep: !!hasData, message };
242
347
  }
243
348
 
349
+ // 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.
350
+ function showValue(value) {
351
+ if (typeof value === 'string') return value;
352
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
353
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
354
+ if (Array.isArray(value)) return value.map(showValue).filter(Boolean).join(', ');
355
+ return '';
356
+ }
357
+ const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
358
+ // Known keys first, in `order`, then any other own key, sorted. `skip` names keys a table already showed.
359
+ function orderedEntries(obj, order, skip) {
360
+ const src = object(obj), seen = new Set(skip || []), out = [];
361
+ for (const key of order) {
362
+ if (has(src, key)) { out.push([key, src[key]]); seen.add(key); }
363
+ }
364
+ for (const key of Object.keys(src).sort()) {
365
+ if (!seen.has(key)) out.push([key, src[key]]);
366
+ }
367
+ return out;
368
+ }
369
+ function budgetPart(label, tokensKey, usdKey, budget) {
370
+ const hasTokens = has(budget, tokensKey), hasUsd = has(budget, usdKey);
371
+ if (!hasTokens && !hasUsd) return '';
372
+ const bits = [];
373
+ if (hasTokens) bits.push((finite(budget[tokensKey]) ? String(budget[tokensKey]) : 'none') + ' tokens');
374
+ if (hasUsd) bits.push('$' + (finite(budget[usdKey]) ? Number(budget[usdKey]).toFixed(4) : 'none'));
375
+ return label + ' ' + bits.join(', ');
376
+ }
377
+ // One gate as `name mode · provider · model`. A mode string is the short form the file stores.
378
+ function gateText(name, value) {
379
+ if (typeof value === 'string') return name + ' ' + value;
380
+ const g = object(value);
381
+ const bits = [text(g.mode), text(g.provider), text(g.model)].filter(Boolean);
382
+ return bits.length ? name + ' ' + bits.join(' · ') : name;
383
+ }
384
+
385
+ // The selected profile's body, as data. render() draws only this: pools per tier, then the other routing and policy
386
+ // values, then one line each for gates and budget. A missing block is an empty list or ''.
387
+ function describeProfile(body) {
388
+ const b = object(body), routing = object(b.routing), pools = {};
389
+ for (const name of POOLS) {
390
+ const value = routing[name];
391
+ pools[name] = value && typeof value === 'object' && !Array.isArray(value) ? value : null;
392
+ }
393
+ const tierNames = [];
394
+ for (const tier of TIERS) {
395
+ if (POOLS.some(name => pools[name] && has(pools[name], tier))) tierNames.push(tier);
396
+ }
397
+ const known = new Set(TIERS);
398
+ const extra = new Set();
399
+ for (const name of POOLS) {
400
+ if (!pools[name]) continue;
401
+ for (const tier of Object.keys(pools[name])) if (!known.has(tier)) extra.add(tier);
402
+ }
403
+ for (const tier of [...extra].sort()) tierNames.push(tier);
404
+ const tiers = tierNames.map(tier => ({
405
+ tier,
406
+ dwarf: (pools.dwarf && showValue(pools.dwarf[tier])) || '—',
407
+ qa: (pools.qa && showValue(pools.qa[tier])) || '—',
408
+ })).filter(row => row.dwarf !== '—' || row.qa !== '—');
409
+ const poolSkip = POOLS.filter(name => pools[name]);
410
+ const routingLines = orderedEntries(routing, ROUTING_ORDER, poolSkip)
411
+ .map(([key, value]) => ({ key, text: showValue(value) }))
412
+ .filter(row => row.text);
413
+ const policy = orderedEntries(b.policy, POLICY_ORDER)
414
+ .map(([key, value]) => ({ key, text: showValue(value) }))
415
+ .filter(row => row.text);
416
+ const gates = b.gates && typeof b.gates === 'object' && !Array.isArray(b.gates)
417
+ ? Object.keys(b.gates).sort().map(name => gateText(name, b.gates[name])).join('; ') : '';
418
+ const budgetObj = b.budget && typeof b.budget === 'object' && !Array.isArray(b.budget) ? b.budget : {};
419
+ const budgetBits = BUDGET_PAIRS.map(([label, tokens, usd]) => budgetPart(label, tokens, usd, budgetObj)).filter(Boolean);
420
+ const budgetSeen = new Set(BUDGET_PAIRS.flatMap(([, tokens, usd]) => [tokens, usd]));
421
+ for (const key of Object.keys(budgetObj).sort()) {
422
+ if (!budgetSeen.has(key)) {
423
+ const shown = showValue(budgetObj[key]);
424
+ if (shown) budgetBits.push(key + ' ' + shown);
425
+ }
426
+ }
427
+ return { tiers, routing: routingLines, policy, gates, budget: budgetBits.join('; ') };
428
+ }
429
+
430
+ // The POST /api/config/profiles body for one action. `use` with none clears the default and carries no name.
431
+ // create carries `from` or `body`, never both; a missing body is the blank profile {}.
432
+ function profileRequest(run, spec) {
433
+ const s = object(spec), action = text(s.action);
434
+ const body = { run: String(run == null ? '' : run), action };
435
+ if (s.level != null) body.level = String(s.level);
436
+ if (action === 'use' && s.none === true) { body.none = true; return body; }
437
+ if (s.name != null) body.name = String(s.name);
438
+ if (action === 'create' && s.from != null && text(s.from) !== '') body.from = String(s.from);
439
+ else if (action === 'create' || action === 'edit') body.body = object(s.body);
440
+ if (action === 'set' || action === 'unset') body.key = String(s.key == null ? '' : s.key);
441
+ if (action === 'set') body.value = String(s.value == null ? '' : s.value);
442
+ return body;
443
+ }
444
+ // The create spec for a blank profile, or a copy of `source` ({name, level, body}). A user-level write passes
445
+ // no --repo, so --from resolves against the user file and the built-ins only. A repo profile is not there: the
446
+ // CLI reports it missing, or copies a built-in of the same name. Send the body the list shows instead.
447
+ // Every other copy is `from`, which is what a repo-level write resolves, and what a user-level copy of a user
448
+ // or built-in profile resolves.
449
+ function profileCopySpec(name, level, source) {
450
+ const spec = { action: 'create', name: text(name), level: text(level) };
451
+ const row = source && typeof source === 'object' ? source : null;
452
+ const sourceName = row ? text(row.name) : '';
453
+ if (!sourceName) { spec.body = {}; return spec; }
454
+ if (spec.level === 'user' && text(row.level) === 'repo') spec.body = object(row.body);
455
+ else spec.from = sourceName;
456
+ return spec;
457
+ }
458
+ // `use --none` clears default_profile in the file that stores it. That file's level is payload.default.level
459
+ // (the user file, else the repo file), not the profile's own level: a repo default_profile can name a user
460
+ // profile, and clearing the user file would leave the repo default in effect while the CLI still says it cleared.
461
+ // The profile's level is only the fallback when the payload names no user or repo level.
462
+ function clearDefaultLevel(payload, profileLevel) {
463
+ const stored = text(object(object(payload).default).level);
464
+ if (stored === 'user' || stored === 'repo') return stored;
465
+ return profileLevel === 'repo' ? 'repo' : 'user';
466
+ }
467
+
468
+ // What a row may do. A built-in (and anything that is not user or repo) can only be duplicated: the CLI refuses
469
+ // to edit, remove or store a default at that level.
470
+ function profileOffers(level) {
471
+ const writable = level === 'user' || level === 'repo';
472
+ return { edit: writable, duplicate: true, remove: writable, setDefault: writable };
473
+ }
474
+ // "shadows repo, builtin", or '' when the winning copy hides nothing.
475
+ function shadowLabel(shadowed) {
476
+ const levels = list(shadowed).map(text).filter(Boolean);
477
+ return levels.length ? 'shadows ' + levels.join(', ') : '';
478
+ }
479
+ // The run record's Profile row: `NAME (level)`, and `· flags override: KEY, KEY` when `overridden` lists keys.
480
+ // Null when there is no profile. Anything but a list in `overridden` names no key, so it adds nothing.
481
+ function profileRowText(profile) {
482
+ if (!profile || typeof profile !== 'object' || Array.isArray(profile)) return null;
483
+ const name = text(profile.name), level = text(profile.level);
484
+ if (!name || !level) return null;
485
+ const keys = Array.isArray(profile.overridden) ? profile.overridden.map(text).filter(Boolean) : [];
486
+ return name + ' (' + level + ')' + (keys.length ? ' · flags override: ' + keys.join(', ') : '');
487
+ }
488
+ // The editor's text. Pretty-printed so a refresh of an untouched profile does not look like an edit.
489
+ function profileText(body) {
490
+ try { return JSON.stringify(object(body), null, 2); }
491
+ catch (_) { return '{}'; }
492
+ }
493
+ function profileNameProblem(name) {
494
+ return PROFILE_NAME.test(text(name)) ? null : 'Use 1–64 letters, digits, ".", "_" or "-", starting with a letter or digit.';
495
+ }
496
+ // Why this text cannot be posted as a profile body, or null. The CLI still checks the keys.
497
+ function profileJsonProblem(value) {
498
+ const v = text(value);
499
+ if (!v.trim()) return 'Empty: a profile body is a JSON object.';
500
+ let parsed;
501
+ try { parsed = JSON.parse(v); }
502
+ catch (_) { return 'Not valid JSON.'; }
503
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return 'A profile body is a JSON object.';
504
+ return null;
505
+ }
506
+ // The CLI's reasons for a refused write. Exit 2's HTTP detail is only the last line; the whole list is result.error,
507
+ // one reason per line. Empty when the write succeeded.
508
+ function refusalReasons(res) {
509
+ if (!res || res.ok) return [];
510
+ const err = res.result && typeof res.result.error === 'string' ? res.result.error : '';
511
+ const lines = err.split('\n').map(line => line.trim()).filter(Boolean);
512
+ if (lines.length) return lines;
513
+ const detail = typeof res.detail === 'string' ? res.detail.trim() : '';
514
+ return detail ? [detail] : [];
515
+ }
516
+
244
517
  /* ---------- DOM ---------- */
245
518
  function render(host, ctx) {
246
519
  const UI = root.ForgeUI, c = ctx || {};
247
520
  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 };
521
+ 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,
522
+ profiles: null, profilesText: null, profilesError: null, profileKey: null, profileEditors: {}, profileMoved: {}, profileReasons: [], profileReasonFor: null,
523
+ forms: { create: { name: '', level: 'user', source: '' }, duplicate: null } };
249
524
  const key_ = (label, cls, onclick) => { const b = el('button', label, cls); b.type = 'button'; if (onclick) b.addEventListener('click', onclick); return b; };
250
525
 
251
526
  const head = el('header', undefined, 'set-head');
252
527
  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'));
528
+ 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
529
  const picker = el('div', undefined, 'set-picker');
255
530
  const body = el('div', undefined, 'set-body');
256
531
  const note = el('p', 'This page is read-only: this server has no write token, or has controls off.', 'muted set-readonly');
@@ -287,14 +562,14 @@
287
562
  const before = s.run, usable = withRepo(runs);
288
563
  let kept = false;
289
564
  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.
565
+ // File editors and profile JSON both count. A poll that drops this run must not switch repositories
566
+ // while either is dirty: resetRun would drop the text.
567
+ const departure = departedRun(s.run, s.repo, runs, unsavedLabels(s.editors, s.profileEditors).length > 0);
568
+ if (departure === 'keep') {
293
569
  const sibling = usable.slice().sort(newestFirst).find(r => RM.repoKey(r) === s.repo);
294
570
  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
- }
571
+ } else if (departure === 'stay') s.gone = true;
572
+ else if (departure === 'drop') s.run = null;
298
573
  if (s.run == null) s.run = pickDefault(runs, c.key);
299
574
  const now = usable.find(r => r.key === s.run);
300
575
  if (now) s.repo = RM.repoKey(now);
@@ -393,10 +668,10 @@
393
668
  async function choose(key) {
394
669
  close();
395
670
  if (key === btn.dataset.run) return; // the run already shown
396
- const unsaved = FILES.filter(n => s.editors[n] && isDirty(s.editors[n]));
671
+ const unsaved = unsavedLabels(s.editors, s.profileEditors);
397
672
  if (unsaved.length) {
398
673
  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 });
674
+ const yes = await UI.confirmInline(picker, `Switch repository and discard the unsaved edits to ${unsaved.join(', ')}?`, { danger: true });
400
675
  if (s.asking !== ask) return; // a later choice asked again, and that confirm decides
401
676
  const late = s.pickerLate;
402
677
  s.asking = 0; s.pickerLate = false;
@@ -419,6 +694,9 @@
419
694
  function resetRun() {
420
695
  staleNote(null);
421
696
  s.data = null; s.dataText = null; s.error = null; s.editors = {}; s.moved = {}; s.models = {}; s.modelMoved = {}; s.loading = s.run != null;
697
+ s.profiles = null; s.profilesText = null; s.profilesError = null; s.profileKey = null;
698
+ s.profileEditors = {}; s.profileMoved = {}; s.profileReasons = []; s.profileReasonFor = null;
699
+ s.forms = { create: { name: '', level: 'user', source: '' }, duplicate: null };
422
700
  s.gen++; s.hold = 0; s.redraw = false;
423
701
  }
424
702
  function pick(key) {
@@ -430,17 +708,55 @@
430
708
  }
431
709
 
432
710
  /* loading, and keeping unsaved text across it */
711
+ const profileId = row => text(row && row.name) + '\0' + text(row && row.level);
712
+ // Fold a profiles read into the page. A failed read keeps the previous list when there is one. An editor's unsaved
713
+ // JSON stays; `moved` says the stored body changed under it.
714
+ function applyProfiles(res) {
715
+ if (!res || !res.ok) {
716
+ const failed = readFailure(res, s.profiles);
717
+ s.profilesError = failed.message;
718
+ if (!failed.keep) { s.profiles = null; }
719
+ return;
720
+ }
721
+ s.profilesError = null;
722
+ const data = object(res.data), rows = list(data.profiles);
723
+ for (const row of rows) {
724
+ const key = profileId(row);
725
+ if (!s.profileEditors[key]) continue;
726
+ const next = dirtyState(s.profileEditors[key], profileText(row.body));
727
+ s.profileEditors[key] = next.editor;
728
+ s.profileMoved[key] = next.moved || (next.dirty && !!s.profileMoved[key]);
729
+ }
730
+ if (!rows.some(row => profileId(row) === s.profileKey)) {
731
+ const def = rows.find(row => row.default) || rows[0];
732
+ s.profileKey = def ? profileId(def) : null;
733
+ }
734
+ s.profiles = data;
735
+ }
433
736
  async function load() {
434
737
  const run = s.run, seq = ++s.seq;
435
738
  if (run == null) { s.loading = false; drawBody(); return; }
436
739
  if (s.gone) return; // the run is not listed: nothing to read until another is picked
437
740
  s.loadedAt = Date.now();
438
- const res = await UI.get('/api/config?run=' + encodeURIComponent(run));
741
+ const query = encodeURIComponent(run);
742
+ const [res, pres] = await Promise.all([
743
+ UI.get('/api/config?run=' + query),
744
+ UI.get('/api/config/profiles?run=' + query),
745
+ ]);
439
746
  if (seq !== s.seq || run !== s.run) return; // a later pick or load answered
440
747
  s.loading = false;
441
748
  if (!res.ok) {
442
749
  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
750
+ if (failed.keep) { // the last good page, its editors and their unsaved text stay
751
+ staleNote(failed.message);
752
+ applyProfiles(pres);
753
+ const pt = JSON.stringify([s.profiles, s.profilesError]);
754
+ if (pt !== s.profilesText) {
755
+ s.profilesText = pt;
756
+ if (s.hold > 0) s.redraw = true; else drawBody();
757
+ }
758
+ return;
759
+ }
444
760
  if (s.hold > 0) return; // a confirm or a write is open: its strip must not be torn down
445
761
  s.error = failed.message; s.data = null; s.dataText = null; drawBody(); return;
446
762
  }
@@ -454,9 +770,11 @@
454
770
  const next = dirtyState(s.models[g.name], g.model);
455
771
  s.models[g.name] = next.editor; s.modelMoved[g.name] = next.moved || (next.dirty && !!s.modelMoved[g.name]);
456
772
  }
773
+ applyProfiles(pres);
457
774
  const t = JSON.stringify(res.data);
458
- if (t === s.dataText && !s.redraw) return;
459
- s.data = res.data; s.dataText = t;
775
+ const pt = JSON.stringify([s.profiles, s.profilesError]);
776
+ if (t === s.dataText && pt === s.profilesText && !s.redraw) return;
777
+ s.data = res.data; s.dataText = t; s.profilesText = pt;
460
778
  drawPicker(); // its path line names the repository this read came from
461
779
  if (s.hold > 0) { s.redraw = true; return; } // a confirm or a write is open: draw after it
462
780
  drawBody();
@@ -467,18 +785,24 @@
467
785
  return () => { if (gen !== s.gen) return; s.hold--; if (!s.hold && s.redraw) { s.redraw = false; drawBody(); } };
468
786
  }
469
787
 
470
- function drawBody() {
788
+ // A held draw runs later, when a confirm may have opened: it then waits for that hold, as load() does.
789
+ function drawBody() { UI.guard(body, drawBodyNow, () => { if (s.hold > 0) s.redraw = true; else drawBodyNow(); }); }
790
+ function drawBodyNow() {
471
791
  const focus = document.activeElement && body.contains(document.activeElement) ? document.activeElement : null;
472
792
  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;
793
+ : focus && focus.dataset.model ? { kind: 'model', name: focus.dataset.model, a: focus.selectionStart, b: focus.selectionEnd }
794
+ : focus && focus.dataset.profileEditor ? { kind: 'profile', a: focus.selectionStart, b: focus.selectionEnd }
795
+ : focus && focus.id ? { kind: 'id', id: focus.id, a: focus.selectionStart, b: focus.selectionEnd } : null;
474
796
  if (s.loading) { body.replaceChildren(el('p', 'Reading the configuration…', 'muted')); return; }
475
797
  if (s.error) { body.replaceChildren(el('p', 'Could not read the configuration: ' + s.error, 'warn')); return; }
476
798
  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
- }
799
+ body.replaceChildren(registrySection(), decideSection(), profilesSection(), repoSection(), datasetSection(), envSection());
800
+ if (!at) return;
801
+ const t = at.kind === 'model' ? body.querySelector(`input[data-model="${at.name}"]`)
802
+ : at.kind === 'editor' ? body.querySelector(`textarea[data-editor="${at.name}"]`)
803
+ : at.kind === 'profile' ? body.querySelector('textarea[data-profile-editor]')
804
+ : document.getElementById(at.id);
805
+ if (t && body.contains(t)) { t.focus({ preventScroll: true }); try { t.setSelectionRange(at.a, at.b); } catch (_) { /* not selectable */ } }
482
806
  }
483
807
 
484
808
  /* sections */
@@ -522,7 +846,11 @@
522
846
 
523
847
  function decideSection() {
524
848
  const view = describeDecide(s.data.decide);
525
- const sec = section('decide', 'Decision models', 'Each gate is off, shadow or on, with a provider and a model. A change writes your forge config (the user level), so it applies to every repository. The mode shown is the one in effect for this repository, and where it came from.');
849
+ const sec = section('decide', 'Decision models', 'Each gate is off, shadow or on, with a provider and a model. Off asks nothing. Shadow asks and records, and changes nothing. On lets the gate act. A change writes your forge config (the user level), so it applies to every repository. The mode shown is the one in effect for this repository, and where it came from.');
850
+ const guide = el('button', 'How to set this up', 'set-guide-open');
851
+ guide.type = 'button'; guide.id = 'set-decide-guide';
852
+ guide.addEventListener('click', openGuide);
853
+ sec.append(guide);
526
854
  const where = text(object(s.data.decide).user_path);
527
855
  if (where) sec.append(pathLine('config', where));
528
856
  if (view.privacyFloor) {
@@ -545,6 +873,64 @@
545
873
  return sec;
546
874
  }
547
875
 
876
+ // The guide lives on document.body, so a refresh of the page's body never closes it.
877
+ function openGuide() {
878
+ let dlg = document.getElementById('set-guide');
879
+ if (!dlg) {
880
+ dlg = el('dialog', undefined, 'set-guide');
881
+ dlg.id = 'set-guide'; dlg.setAttribute('aria-labelledby', 'set-guide-h');
882
+ const title = el('h2', 'Set up a decision model'); title.id = 'set-guide-h';
883
+ const close = el('button', 'Close', 'set-guide-close'); close.type = 'button';
884
+ close.addEventListener('click', () => dlg.close());
885
+ const head = el('div', undefined, 'set-guide-head');
886
+ head.append(title, close);
887
+ dlg.append(head, el('p', SETUP_GUIDE.intro));
888
+ const steps = el('ol', undefined, 'set-guide-steps');
889
+ for (const step of SETUP_GUIDE.steps) {
890
+ const li = el('li');
891
+ li.append(el('strong', step.title), el('p', step.text, 'muted'));
892
+ for (const [label, command] of step.commands) li.append(commandLine(label, command));
893
+ steps.append(li);
894
+ }
895
+ dlg.append(steps, el('h3', 'To stop sending'));
896
+ for (const [label, command] of SETUP_GUIDE.stop) dlg.append(commandLine(label, command));
897
+ dlg.addEventListener('click', e => { if (e.target === dlg) dlg.close(); }); // a click on the backdrop
898
+ document.body.append(dlg);
899
+ }
900
+ if (!dlg.open) dlg.showModal();
901
+ }
902
+
903
+ function commandLine(label, command) {
904
+ const line = el('div', undefined, 'set-guide-command');
905
+ if (label) line.append(el('span', label, 'muted'));
906
+ const row = el('div', undefined, 'set-guide-row');
907
+ const copy = el('button', 'Copy', 'set-guide-copy'); copy.type = 'button';
908
+ copy.addEventListener('click', async () => {
909
+ try { await navigator.clipboard.writeText(command); copy.textContent = 'Copied'; }
910
+ catch { copy.textContent = 'Copy failed'; }
911
+ });
912
+ const code = el('code', command, 'mono');
913
+ code.tabIndex = 0; // one line, scrolled: a wrap inside `--local` misleads anyone retyping it
914
+ row.append(code, copy);
915
+ line.append(row);
916
+ return line;
917
+ }
918
+
919
+ // What a gate does. Its open state outlives a refresh, which rebuilds the row.
920
+ function gateHelp(gate) {
921
+ const help = GATE_HELP[gate.name];
922
+ if (!help) return [];
923
+ const more = el('details', undefined, 'set-gate-more');
924
+ more.id = 'set-gate-' + gate.name + '-help';
925
+ more.open = !!s.gateHelpOpen?.[gate.name];
926
+ more.addEventListener('toggle', () => { (s.gateHelpOpen ||= {})[gate.name] = more.open; });
927
+ more.append(el('summary', 'What it sends and what on does'));
928
+ const dl = el('dl');
929
+ for (const [term, value] of [['When', help.when], ['Sends', help.sends], ['When on', help.on]]) dl.append(el('dt', term), el('dd', value));
930
+ more.append(dl);
931
+ return [el('p', help.summary, 'set-gate-summary'), more];
932
+ }
933
+
548
934
  const providerLabel = p => [p.name, p.type, p.local ? 'local' : ''].filter(Boolean).join(' · ');
549
935
 
550
936
  function gateRow(gate, providers) {
@@ -564,7 +950,7 @@
564
950
  if (gate.skip) status.append(el('span', 'skip: ' + gate.skip, 'set-gate-skip'));
565
951
  const top = el('div', undefined, 'set-file-head');
566
952
  top.append(h, status);
567
- art.append(top);
953
+ art.append(top, ...gateHelp(gate));
568
954
  if (!s.writes) {
569
955
  const bits = ['mode ' + gate.mode, gate.provider ? 'provider ' + gate.provider : 'no provider', gate.model ? 'model ' + gate.model : 'no model'];
570
956
  art.append(el('p', bits.join(', '), 'muted'));
@@ -811,6 +1197,513 @@
811
1197
  return art;
812
1198
  }
813
1199
 
1200
+ function profilesSection() {
1201
+ 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.');
1202
+ if (s.profilesError && !s.profiles) {
1203
+ sec.append(el('p', 'Could not read profiles: ' + s.profilesError, 'warn'));
1204
+ return sec;
1205
+ }
1206
+ if (!s.profiles) { sec.append(el('p', 'Reading profiles…', 'muted')); return sec; }
1207
+ if (s.profilesError) sec.append(el('p', 'The last read of profiles failed: ' + s.profilesError + '. This shows the read before it.', 'warn set-problem'));
1208
+ const rows = list(s.profiles.profiles);
1209
+ if (!rows.length) sec.append(el('p', 'No profiles.', 'muted'));
1210
+ else sec.append(profileList(rows));
1211
+ const row = rows.find(item => profileId(item) === s.profileKey);
1212
+ if (row) sec.append(profileDetail(row));
1213
+ if (s.writes) sec.append(newProfileForm(rows));
1214
+ return sec;
1215
+ }
1216
+
1217
+ function profileList(rows) {
1218
+ const ul = el('ul', undefined, 'set-profiles');
1219
+ ul.setAttribute('aria-label', 'Profiles');
1220
+ for (const row of rows) {
1221
+ const li = el('li');
1222
+ const on = profileId(row) === s.profileKey;
1223
+ const b = el('button', undefined, 'set-profile');
1224
+ b.type = 'button';
1225
+ b.id = 'set-prof-' + text(row.name);
1226
+ b.dataset.profile = text(row.name);
1227
+ b.dataset.level = text(row.level);
1228
+ b.setAttribute('aria-pressed', on ? 'true' : 'false');
1229
+ const shadow = shadowLabel(row.shadowed);
1230
+ b.setAttribute('aria-label', [text(row.name), text(row.level), row.default ? 'default' : '', shadow].filter(Boolean).join(', '));
1231
+ b.append(el('span', text(row.name), 'set-profile-name'), el('span', text(row.level), 'tag'));
1232
+ if (row.default) b.append(el('span', 'default', 'tag'));
1233
+ if (shadow) b.append(el('span', shadow, 'set-profile-meta'));
1234
+ b.addEventListener('click', () => {
1235
+ const key = profileId(row);
1236
+ if (s.profileKey === key) return;
1237
+ s.profileKey = key;
1238
+ s.forms.duplicate = null;
1239
+ s.profileReasons = [];
1240
+ s.profileReasonFor = null;
1241
+ drawBody();
1242
+ const again = document.getElementById(b.id);
1243
+ if (again) again.focus({ preventScroll: true });
1244
+ });
1245
+ li.append(b);
1246
+ ul.append(li);
1247
+ }
1248
+ return ul;
1249
+ }
1250
+
1251
+ function summaryBlock(title, id) {
1252
+ const block = el('div');
1253
+ block.id = id;
1254
+ block.append(el('p', title, 'plate'));
1255
+ return block;
1256
+ }
1257
+ function profileSummary(body) {
1258
+ const view = describeProfile(body);
1259
+ const box = el('div', undefined, 'set-profile-summary');
1260
+ if (view.tiers.length) {
1261
+ const wrap = el('div', undefined, 'set-table-wrap');
1262
+ const table = el('table', undefined, 'set-table');
1263
+ const cap = el('caption', 'Dwarf and QA pools by tier', 'visually-hidden');
1264
+ const hr = el('tr');
1265
+ for (const h of ['Tier', 'Dwarf', 'QA']) { const th = el('th', h); th.scope = 'col'; hr.append(th); }
1266
+ const thead = el('thead'); thead.append(hr);
1267
+ const tbody = el('tbody');
1268
+ for (const tier of view.tiers) {
1269
+ const tr = el('tr');
1270
+ const th = el('th', tier.tier, 'set-alias'); th.scope = 'row';
1271
+ tr.append(th, el('td', tier.dwarf, 'mono'), el('td', tier.qa, 'mono'));
1272
+ tbody.append(tr);
1273
+ }
1274
+ table.append(cap, thead, tbody);
1275
+ wrap.append(table);
1276
+ box.append(wrap);
1277
+ }
1278
+ if (view.routing.length) {
1279
+ const block = summaryBlock('Routing', 'set-profile-routing');
1280
+ const dl = el('dl', undefined, 'set-kv');
1281
+ for (const item of view.routing) dl.append(el('dt', item.key), el('dd', item.text, 'mono'));
1282
+ block.append(dl);
1283
+ box.append(block);
1284
+ }
1285
+ if (view.policy.length) {
1286
+ const block = summaryBlock('Policy', 'set-profile-policy');
1287
+ const dl = el('dl', undefined, 'set-kv');
1288
+ for (const item of view.policy) dl.append(el('dt', item.key), el('dd', item.text, 'mono'));
1289
+ block.append(dl);
1290
+ box.append(block);
1291
+ }
1292
+ if (view.gates) {
1293
+ const block = summaryBlock('Gates', 'set-profile-gates');
1294
+ block.append(el('p', view.gates, 'mono set-summary-line'));
1295
+ box.append(block);
1296
+ }
1297
+ if (view.budget) {
1298
+ const block = summaryBlock('Budget', 'set-profile-budget');
1299
+ block.append(el('p', view.budget, 'mono set-summary-line'));
1300
+ box.append(block);
1301
+ }
1302
+ const source = text(object(body).source);
1303
+ if (source) {
1304
+ const block = summaryBlock('Source', 'set-profile-source');
1305
+ block.append(el('p', source, 'muted set-summary-line'));
1306
+ box.append(block);
1307
+ }
1308
+ if (!box.childElementCount) box.append(el('p', 'This profile sets nothing.', 'muted'));
1309
+ return box;
1310
+ }
1311
+
1312
+ function showReasons(row) {
1313
+ if (s.profileReasonFor !== profileId(row) || !s.profileReasons.length) return null;
1314
+ const ul = el('ul', undefined, 'set-reasons');
1315
+ ul.id = 'set-profile-reasons';
1316
+ for (const reason of s.profileReasons) ul.append(el('li', reason));
1317
+ return ul;
1318
+ }
1319
+
1320
+ function profileEditor(row, result) {
1321
+ const key = profileId(row);
1322
+ const fresh = profileText(row.body);
1323
+ const ed = s.profileEditors[key] || (s.profileEditors[key] = editorOf(fresh));
1324
+ const id = 'set-profile-body';
1325
+ const lab = el('label', 'Body of ' + text(row.name) + ' as JSON', 'visually-hidden');
1326
+ lab.htmlFor = id;
1327
+ const ta = el('textarea', undefined, 'set-editor mono');
1328
+ ta.id = id;
1329
+ ta.dataset.profileEditor = '1';
1330
+ ta.rows = Math.max(6, Math.min(18, shown(ed).split('\n').length + 1));
1331
+ ta.spellcheck = false;
1332
+ ta.setAttribute('autocapitalize', 'off');
1333
+ ta.setAttribute('autocomplete', 'off');
1334
+ ta.value = shown(ed);
1335
+ let from = ed.base;
1336
+ const movedNote = el('p', 'The profile changed after you began editing; saving replaces it with your text.', 'warn set-file-note');
1337
+ movedNote.hidden = !(isDirty(ed) && s.profileMoved[key]);
1338
+ const problem = el('p', undefined, 'warn set-problem');
1339
+ problem.hidden = true;
1340
+ problem.id = id + '-problem';
1341
+ const save = key_('Save', 'primary');
1342
+ save.id = 'set-profile-save';
1343
+ save.setAttribute('aria-label', 'Save profile ' + text(row.name));
1344
+ const sync = () => {
1345
+ const cur = s.profileEditors[key], dirtyNow = isDirty(cur);
1346
+ const bad = dirtyNow ? profileJsonProblem(cur.draft) : null;
1347
+ const reasons = s.profileReasonFor === key ? s.profileReasons : [];
1348
+ problem.hidden = !bad;
1349
+ problem.textContent = bad || '';
1350
+ const described = [bad ? problem.id : '', reasons.length ? 'set-profile-reasons' : ''].filter(Boolean).join(' ');
1351
+ if (bad || reasons.length) {
1352
+ ta.setAttribute('aria-invalid', 'true');
1353
+ if (described) ta.setAttribute('aria-describedby', described);
1354
+ } else {
1355
+ ta.removeAttribute('aria-invalid');
1356
+ ta.removeAttribute('aria-describedby');
1357
+ }
1358
+ save.disabled = !dirtyNow || !!bad;
1359
+ movedNote.hidden = !(dirtyNow && s.profileMoved[key]);
1360
+ };
1361
+ ta.addEventListener('input', () => {
1362
+ const next = typed(s.profileEditors[key], ta.value, from);
1363
+ s.profileEditors[key] = next.editor;
1364
+ s.profileMoved[key] = next.moved || (next.dirty && !!s.profileMoved[key]);
1365
+ if (s.profileReasonFor === key) {
1366
+ s.profileReasons = []; s.profileReasonFor = null;
1367
+ const old = document.getElementById('set-profile-reasons');
1368
+ if (old) old.remove();
1369
+ }
1370
+ sync();
1371
+ });
1372
+ save.addEventListener('click', async () => {
1373
+ const cur = s.profileEditors[key];
1374
+ const bad = profileJsonProblem(shown(cur));
1375
+ if (!isDirty(cur) || bad) { sync(); return; }
1376
+ let parsed;
1377
+ try { parsed = JSON.parse(cur.draft); } catch (_) { sync(); return; }
1378
+ const gen = s.gen, release = grab();
1379
+ save.disabled = true;
1380
+ ta.readOnly = true;
1381
+ const yes = await UI.confirmInline(result, `Replace the body of profile ${text(row.name)} at the ${text(row.level)} level?`);
1382
+ if (!yes || gen !== s.gen) {
1383
+ ta.readOnly = false;
1384
+ release();
1385
+ sync();
1386
+ if (!yes && gen === s.gen) save.focus({ preventScroll: true });
1387
+ return;
1388
+ }
1389
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, { action: 'edit', name: row.name, level: row.level, body: parsed }));
1390
+ const reasons = refusalReasons(res);
1391
+ s.profileReasons = res.ok ? [] : reasons;
1392
+ s.profileReasonFor = res.ok ? null : key;
1393
+ UI.outcome(result, res, `Saved ${text(row.name)}.`);
1394
+ if (res.ok && gen === s.gen) {
1395
+ s.profileEditors[key] = editorOf(profileText(parsed));
1396
+ s.profileMoved[key] = false;
1397
+ from = s.profileEditors[key].base;
1398
+ }
1399
+ ta.readOnly = false;
1400
+ release();
1401
+ // A refusal keeps this textarea. The reasons go under it; a redraw would drop the outcome line.
1402
+ if (!res.ok && gen === s.gen && ta.isConnected) {
1403
+ const old = document.getElementById('set-profile-reasons');
1404
+ if (old) old.remove();
1405
+ const list = showReasons(row);
1406
+ const editor = ta.closest('.set-profile-editor');
1407
+ if (list && editor) editor.after(list);
1408
+ }
1409
+ if (gen === s.gen && ta.isConnected) sync();
1410
+ if (res.ok && gen === s.gen) await reload();
1411
+ });
1412
+ const wrap = el('div', undefined, 'set-profile-editor');
1413
+ wrap.append(lab, ta, problem, movedNote, save);
1414
+ sync();
1415
+ return wrap;
1416
+ }
1417
+
1418
+ function duplicateForm(row, result) {
1419
+ const draft = s.forms.duplicate;
1420
+ const form = el('div', undefined, 'set-profile-form');
1421
+ form.id = 'set-dup-form';
1422
+ const name = el('input');
1423
+ name.type = 'text';
1424
+ name.id = 'set-dup-name';
1425
+ name.value = draft.name;
1426
+ name.spellcheck = false;
1427
+ name.setAttribute('autocomplete', 'off');
1428
+ name.setAttribute('autocapitalize', 'off');
1429
+ const nameLab = el('label', undefined, 'filter');
1430
+ nameLab.htmlFor = name.id;
1431
+ nameLab.append(el('span', 'New name'), name);
1432
+ const sel = el('select');
1433
+ sel.id = 'set-dup-level';
1434
+ sel.setAttribute('aria-label', 'Level for the copy of ' + text(row.name));
1435
+ for (const level of WRITE_LEVELS) {
1436
+ const o = el('option', level);
1437
+ o.value = level;
1438
+ o.selected = level === draft.level;
1439
+ sel.append(o);
1440
+ }
1441
+ const levelLab = el('label', undefined, 'filter');
1442
+ levelLab.htmlFor = sel.id;
1443
+ levelLab.append(el('span', 'Level'), sel);
1444
+ const problem = el('p', undefined, 'warn set-problem');
1445
+ problem.hidden = true;
1446
+ problem.id = 'set-dup-problem';
1447
+ const go = key_('Create copy', 'primary');
1448
+ go.id = 'set-dup-save';
1449
+ go.setAttribute('aria-label', 'Create a copy of ' + text(row.name));
1450
+ const cancel = key_('Cancel');
1451
+ cancel.id = 'set-dup-cancel';
1452
+ cancel.setAttribute('aria-label', 'Cancel duplicating ' + text(row.name));
1453
+ name.addEventListener('input', () => { draft.name = name.value; problem.hidden = true; name.removeAttribute('aria-invalid'); });
1454
+ sel.addEventListener('change', () => { draft.level = sel.value; });
1455
+ cancel.addEventListener('click', () => {
1456
+ s.forms.duplicate = null;
1457
+ drawBody();
1458
+ const again = document.getElementById('set-profile-duplicate');
1459
+ if (again) again.focus({ preventScroll: true });
1460
+ });
1461
+ go.addEventListener('click', async () => {
1462
+ const bad = profileNameProblem(draft.name);
1463
+ if (bad) {
1464
+ problem.hidden = false;
1465
+ problem.textContent = bad;
1466
+ name.setAttribute('aria-invalid', 'true');
1467
+ name.setAttribute('aria-describedby', problem.id);
1468
+ name.focus({ preventScroll: true });
1469
+ return;
1470
+ }
1471
+ const gen = s.gen, release = grab();
1472
+ go.disabled = true;
1473
+ name.readOnly = true;
1474
+ const yes = await UI.confirmInline(result, `Create profile ${draft.name} at the ${draft.level} level as a copy of ${text(row.name)}?`);
1475
+ if (!yes || gen !== s.gen) {
1476
+ go.disabled = false;
1477
+ name.readOnly = false;
1478
+ release();
1479
+ if (!yes && gen === s.gen) go.focus({ preventScroll: true });
1480
+ return;
1481
+ }
1482
+ const created = draft.name, level = draft.level;
1483
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, profileCopySpec(created, level, row)));
1484
+ UI.outcome(result, res, `Created ${created}.`);
1485
+ name.readOnly = false;
1486
+ if (res.ok && gen === s.gen) {
1487
+ s.profileKey = created + '\0' + level;
1488
+ s.forms.duplicate = null;
1489
+ } else go.disabled = false;
1490
+ release();
1491
+ if (res.ok && gen === s.gen) await reload();
1492
+ });
1493
+ const keys = el('div', undefined, 'set-keys');
1494
+ keys.append(go, cancel);
1495
+ form.append(nameLab, levelLab, problem, keys);
1496
+ return form;
1497
+ }
1498
+
1499
+ function defaultButton(row, result) {
1500
+ const clearing = row.default === true;
1501
+ // Setting writes default_profile at the profile's own level. Clearing removes it from the file that
1502
+ // actually stores it, which can be the other level (a repo default_profile naming a user profile).
1503
+ const level = clearing ? clearDefaultLevel(s.profiles, row.level) : text(row.level);
1504
+ const label = clearing ? 'Clear default' : 'Set as default';
1505
+ const b = key_(label);
1506
+ b.id = 'set-profile-default';
1507
+ b.setAttribute('aria-label', clearing
1508
+ ? 'Clear the default profile at the ' + level + ' level'
1509
+ : 'Set ' + text(row.name) + ' as the default profile at the ' + level + ' level');
1510
+ b.addEventListener('click', async () => {
1511
+ const gen = s.gen, release = grab();
1512
+ b.disabled = true;
1513
+ const question = clearing
1514
+ ? `Clear the default profile at the ${level} level?`
1515
+ : `Set ${text(row.name)} as the default profile at the ${level} level?`;
1516
+ const yes = await UI.confirmInline(result, question);
1517
+ if (!yes || gen !== s.gen) {
1518
+ b.disabled = false;
1519
+ release();
1520
+ if (!yes && gen === s.gen) b.focus({ preventScroll: true });
1521
+ return;
1522
+ }
1523
+ const spec = clearing
1524
+ ? { action: 'use', level, none: true }
1525
+ : { action: 'use', name: row.name, level };
1526
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, spec));
1527
+ UI.outcome(result, res, clearing ? `Cleared the default at the ${level} level.` : `${text(row.name)} is the default at the ${level} level.`);
1528
+ b.disabled = false;
1529
+ release();
1530
+ if (res.ok && gen === s.gen) await reload();
1531
+ });
1532
+ return b;
1533
+ }
1534
+
1535
+ function deleteButton(row, result) {
1536
+ const b = key_('Delete');
1537
+ b.classList.add('set-remove');
1538
+ b.id = 'set-profile-delete';
1539
+ b.setAttribute('aria-label', 'Delete profile ' + text(row.name));
1540
+ b.addEventListener('click', async () => {
1541
+ const gen = s.gen, release = grab();
1542
+ b.disabled = true;
1543
+ const yes = await UI.confirmInline(result, `Delete profile ${text(row.name)} at the ${text(row.level)} level?`, { danger: true });
1544
+ if (!yes || gen !== s.gen) {
1545
+ b.disabled = false;
1546
+ release();
1547
+ if (!yes && gen === s.gen) b.focus({ preventScroll: true });
1548
+ return;
1549
+ }
1550
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, { action: 'rm', name: row.name, level: row.level }));
1551
+ UI.outcome(result, res, `Deleted ${text(row.name)}.`);
1552
+ if (res.ok && gen === s.gen) {
1553
+ const key = profileId(row);
1554
+ delete s.profileEditors[key];
1555
+ delete s.profileMoved[key];
1556
+ s.profileKey = null;
1557
+ s.profileReasons = [];
1558
+ s.profileReasonFor = null;
1559
+ } else b.disabled = false;
1560
+ release();
1561
+ if (res.ok && gen === s.gen) await reload();
1562
+ });
1563
+ return b;
1564
+ }
1565
+
1566
+ function profileDetail(row) {
1567
+ const offers = profileOffers(row.level);
1568
+ const art = el('article', undefined, 'set-file set-profile-detail');
1569
+ art.id = 'set-profile-detail';
1570
+ const h = el('h3', text(row.name), 'set-file-name');
1571
+ h.id = 'set-profile-detail-h';
1572
+ art.setAttribute('aria-labelledby', h.id);
1573
+ const status = el('p', undefined, 'set-file-status');
1574
+ status.append(el('span', text(row.level), 'tag'));
1575
+ if (row.default) status.append(el('span', 'default', 'tag'));
1576
+ const shadow = shadowLabel(row.shadowed);
1577
+ if (shadow) status.append(el('span', shadow, 'set-profile-meta'));
1578
+ const top = el('div', undefined, 'set-file-head');
1579
+ top.append(h, status);
1580
+ art.append(top, profileSummary(row.body));
1581
+ if (!offers.edit) art.append(el('p', 'This built-in profile is read-only. Duplicate it to change a copy.', 'muted set-file-blurb'));
1582
+ if (!s.writes) return art;
1583
+ const result = el('div', undefined, 'set-result');
1584
+ result.id = 'set-profile-result';
1585
+ if (offers.edit) art.append(profileEditor(row, result));
1586
+ const reasons = showReasons(row);
1587
+ if (reasons) art.append(reasons);
1588
+ const keys = el('div', undefined, 'set-keys');
1589
+ const dup = key_('Duplicate');
1590
+ dup.id = 'set-profile-duplicate';
1591
+ dup.setAttribute('aria-label', 'Duplicate profile ' + text(row.name));
1592
+ dup.addEventListener('click', () => {
1593
+ if (s.forms.duplicate && s.forms.duplicate.of === profileId(row)) return;
1594
+ s.forms.duplicate = { of: profileId(row), name: '', level: row.level === 'repo' ? 'repo' : 'user' };
1595
+ drawBody();
1596
+ const field = document.getElementById('set-dup-name');
1597
+ if (field) field.focus({ preventScroll: true });
1598
+ });
1599
+ keys.append(dup);
1600
+ if (offers.setDefault) keys.append(defaultButton(row, result));
1601
+ if (offers.remove) keys.append(deleteButton(row, result));
1602
+ art.append(keys);
1603
+ if (s.forms.duplicate && s.forms.duplicate.of === profileId(row)) art.append(duplicateForm(row, result));
1604
+ art.append(result);
1605
+ return art;
1606
+ }
1607
+
1608
+ function newProfileForm(rows) {
1609
+ const draft = s.forms.create;
1610
+ const box = el('div', undefined, 'set-file');
1611
+ box.id = 'set-new';
1612
+ const h = el('h3', 'New profile', 'set-file-name');
1613
+ h.id = 'set-new-h';
1614
+ box.setAttribute('aria-labelledby', h.id);
1615
+ box.append(h, el('p', 'A blank body, or a copy of a profile that already exists.', 'muted set-file-blurb'));
1616
+ const name = el('input');
1617
+ name.type = 'text';
1618
+ name.id = 'set-new-name';
1619
+ name.value = draft.name;
1620
+ name.spellcheck = false;
1621
+ name.setAttribute('autocomplete', 'off');
1622
+ name.setAttribute('autocapitalize', 'off');
1623
+ const nameLab = el('label', undefined, 'filter');
1624
+ nameLab.htmlFor = name.id;
1625
+ nameLab.append(el('span', 'Name'), name);
1626
+ const level = el('select');
1627
+ level.id = 'set-new-level';
1628
+ level.setAttribute('aria-label', 'Level for the new profile');
1629
+ for (const item of WRITE_LEVELS) {
1630
+ const o = el('option', item);
1631
+ o.value = item;
1632
+ o.selected = item === draft.level;
1633
+ level.append(o);
1634
+ }
1635
+ const levelLab = el('label', undefined, 'filter');
1636
+ levelLab.htmlFor = level.id;
1637
+ levelLab.append(el('span', 'Level'), level);
1638
+ const source = el('select');
1639
+ source.id = 'set-new-source';
1640
+ source.setAttribute('aria-label', 'Body for the new profile');
1641
+ const blank = el('option', 'Blank body');
1642
+ blank.value = '';
1643
+ blank.selected = !draft.source;
1644
+ source.append(blank);
1645
+ for (const row of rows) {
1646
+ const o = el('option', text(row.name) + ' (' + text(row.level) + ')');
1647
+ o.value = text(row.name);
1648
+ o.selected = text(row.name) === draft.source;
1649
+ source.append(o);
1650
+ }
1651
+ const sourceLab = el('label', undefined, 'filter');
1652
+ sourceLab.htmlFor = source.id;
1653
+ sourceLab.append(el('span', 'Copy from'), source);
1654
+ const problem = el('p', undefined, 'warn set-problem');
1655
+ problem.hidden = true;
1656
+ problem.id = 'set-new-problem';
1657
+ const result = el('div', undefined, 'set-result');
1658
+ const go = key_('Create', 'primary');
1659
+ go.id = 'set-new-save';
1660
+ go.setAttribute('aria-label', 'Create profile');
1661
+ name.addEventListener('input', () => { draft.name = name.value; problem.hidden = true; name.removeAttribute('aria-invalid'); });
1662
+ level.addEventListener('change', () => { draft.level = level.value; });
1663
+ source.addEventListener('change', () => { draft.source = source.value; });
1664
+ go.addEventListener('click', async () => {
1665
+ const bad = profileNameProblem(draft.name);
1666
+ if (bad) {
1667
+ problem.hidden = false;
1668
+ problem.textContent = bad;
1669
+ name.setAttribute('aria-invalid', 'true');
1670
+ name.setAttribute('aria-describedby', problem.id);
1671
+ name.focus({ preventScroll: true });
1672
+ return;
1673
+ }
1674
+ const sourceRow = draft.source ? rows.find(item => text(item.name) === draft.source) : null;
1675
+ // A chosen name whose row is gone still goes as `from`. A repo profile copied to the user level
1676
+ // cannot: that write passes no --repo, so the spec carries the body instead.
1677
+ const spec = profileCopySpec(draft.name, draft.level, draft.source ? (sourceRow || { name: draft.source }) : null);
1678
+ const gen = s.gen, release = grab();
1679
+ go.disabled = true;
1680
+ name.readOnly = true;
1681
+ const from = draft.source ? `a copy of ${draft.source}` : 'a blank body';
1682
+ const yes = await UI.confirmInline(result, `Create profile ${draft.name} at the ${draft.level} level with ${from}?`);
1683
+ if (!yes || gen !== s.gen) {
1684
+ go.disabled = false;
1685
+ name.readOnly = false;
1686
+ release();
1687
+ if (!yes && gen === s.gen) go.focus({ preventScroll: true });
1688
+ return;
1689
+ }
1690
+ const created = draft.name, at = draft.level;
1691
+ const res = await UI.post('/api/config/profiles', profileRequest(s.run, spec));
1692
+ UI.outcome(result, res, `Created ${created}.`);
1693
+ name.readOnly = false;
1694
+ if (res.ok && gen === s.gen) {
1695
+ s.profileKey = created + '\0' + at;
1696
+ s.forms.create = { name: '', level: 'user', source: '' };
1697
+ } else go.disabled = false;
1698
+ release();
1699
+ if (res.ok && gen === s.gen) await reload();
1700
+ });
1701
+ const form = el('div', undefined, 'set-profile-form');
1702
+ form.append(nameLab, levelLab, sourceLab, problem, go);
1703
+ box.append(form, result);
1704
+ return box;
1705
+ }
1706
+
814
1707
  function datasetSection() {
815
1708
  const d = object(s.data.dataset), sec = section('dataset', 'Dataset');
816
1709
  sec.append(pathLine('folder', text(d.path)));
@@ -842,7 +1735,9 @@
842
1735
  return { poll, pick };
843
1736
  }
844
1737
 
845
- return { render, configBody, repoKey, gateKey, targetPath, subsetOk, valueProblem, decideTextProblem, describeDecide, gateTags, replayDate,
1738
+ return { render, configBody, repoKey, gateKey, targetPath, subsetOk, valueProblem, decideTextProblem, describeDecide, gateTags, replayDate, GATES, GATE_HELP, SETUP_GUIDE,
846
1739
  pickDefault, groupRuns, optionLabel, typeAhead, editorOf, isDirty, dirtyState, edited, typed, shown, readFailure,
847
- FILES, GATES, MODES, VALUE_MAX, DECIDE_VALUE_MAX, ADD_COMMAND };
1740
+ unsavedLabels, departedRun,
1741
+ describeProfile, profileRequest, profileCopySpec, clearDefaultLevel, profileOffers, profileRowText, shadowLabel, refusalReasons, profileText, profileJsonProblem, profileNameProblem,
1742
+ FILES, GATES, MODES, VALUE_MAX, DECIDE_VALUE_MAX, ADD_COMMAND, PROFILE_LEVELS, WRITE_LEVELS, TIERS };
848
1743
  });