@giamme/forge 0.12.1 → 0.13.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 (107) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/SKILL.md +29 -12
  4. package/VERSION +1 -1
  5. package/docs/add-ons.md +11 -6
  6. package/docs/artifacts.md +12 -6
  7. package/docs/commands.md +179 -17
  8. package/docs/decomposed-runs.md +13 -5
  9. package/docs/forge-ui.md +7 -3
  10. package/docs/memory.md +2 -1
  11. package/docs/models.md +4 -2
  12. package/docs/reviews.md +49 -20
  13. package/docs/troubleshooting.md +3 -1
  14. package/forge +17 -1
  15. package/package.json +1 -1
  16. package/references/dataset.md +39 -13
  17. package/references/decision-models.md +759 -0
  18. package/references/decompose.md +166 -29
  19. package/references/harnesses.md +10 -3
  20. package/references/planning.md +8 -0
  21. package/references/solo.md +13 -3
  22. package/scripts/forge-artifact.sh +30 -4
  23. package/scripts/forge-config.py +238 -29
  24. package/scripts/forge-contract.py +95 -56
  25. package/scripts/forge-control.py +40 -9
  26. package/scripts/forge-decide.py +6 -0
  27. package/scripts/forge-dispatch.sh +38 -16
  28. package/scripts/forge-fail-first.py +2 -2
  29. package/scripts/forge-gate-addressed.sh +40 -0
  30. package/scripts/forge-gate-message.sh +64 -0
  31. package/scripts/forge-issues.py +321 -33
  32. package/scripts/forge-jev-options.sh +269 -42
  33. package/scripts/forge-lib-attribute.sh +447 -0
  34. package/scripts/forge-lib-gates.sh +32 -0
  35. package/scripts/forge-lib-plans.sh +17 -6
  36. package/scripts/forge-lib-review.sh +22 -17
  37. package/scripts/forge-lib-task.sh +217 -38
  38. package/scripts/forge-lib-verify.sh +45 -8
  39. package/scripts/forge-memory.sh +3 -3
  40. package/scripts/forge-parallel-options.sh +18 -5
  41. package/scripts/forge-parallel.sh +455 -303
  42. package/scripts/forge-plan-check.py +35 -1
  43. package/scripts/forge-pre-review.py +437 -0
  44. package/scripts/forge-prompt.py +25 -5
  45. package/scripts/forge-route.py +2 -2
  46. package/scripts/forge-runtime.py +10 -4
  47. package/scripts/forge-schedule.py +21 -5
  48. package/scripts/forge-shadow.py +2 -2
  49. package/scripts/forge-solo.sh +38 -9
  50. package/scripts/forge-submodules.py +389 -0
  51. package/scripts/forge_dataset/cli.py +12 -6
  52. package/scripts/forge_dataset/export.py +55 -45
  53. package/scripts/forge_dataset/harvest.py +33 -5
  54. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  55. package/scripts/forge_decide/__init__.py +141 -0
  56. package/scripts/forge_decide/budget.py +149 -0
  57. package/scripts/forge_decide/cache.py +66 -0
  58. package/scripts/forge_decide/cli.py +953 -0
  59. package/scripts/forge_decide/doctor.py +221 -0
  60. package/scripts/forge_decide/label_addressed.py +75 -0
  61. package/scripts/forge_decide/label_attribution.py +62 -0
  62. package/scripts/forge_decide/label_coverage.py +81 -0
  63. package/scripts/forge_decide/label_message.py +38 -0
  64. package/scripts/forge_decide/label_prompt.py +139 -0
  65. package/scripts/forge_decide/labels.py +328 -0
  66. package/scripts/forge_decide/metrics.py +125 -0
  67. package/scripts/forge_decide/migrate.py +226 -0
  68. package/scripts/forge_decide/providers.py +292 -0
  69. package/scripts/forge_decide/replay.py +350 -0
  70. package/scripts/forge_decide/report.py +382 -0
  71. package/scripts/forge_decide/resolve.py +397 -0
  72. package/scripts/forge_decide/sites.py +377 -0
  73. package/scripts/forge_jev/__init__.py +202 -104
  74. package/scripts/forge_jev/addressed.py +171 -0
  75. package/scripts/forge_jev/attribution.py +198 -0
  76. package/scripts/forge_jev/cli.py +460 -382
  77. package/scripts/forge_jev/client.py +155 -77
  78. package/scripts/forge_jev/coupling.py +19 -87
  79. package/scripts/forge_jev/coverage.py +303 -0
  80. package/scripts/forge_jev/findings.py +219 -0
  81. package/scripts/forge_jev/gates.py +225 -27
  82. package/scripts/forge_jev/memory.py +65 -4
  83. package/scripts/forge_jev/message.py +134 -0
  84. package/scripts/forge_jev/plan_gates.py +294 -0
  85. package/scripts/forge_jev/questions.py +173 -313
  86. package/scripts/forge_jev/verify.py +130 -104
  87. package/ui/README.md +2 -2
  88. package/ui/docs/api.md +60 -32
  89. package/ui/forge_ui/control.py +60 -11
  90. package/ui/forge_ui/export.py +2 -1
  91. package/ui/forge_ui/models.py +1 -0
  92. package/ui/forge_ui/reader.py +87 -14
  93. package/ui/forge_ui/static/app.js +2 -2
  94. package/ui/forge_ui/static/controls.js +20 -13
  95. package/ui/forge_ui/static/panel.js +63 -17
  96. package/ui/forge_ui/static/runmodel.js +23 -1
  97. package/ui/forge_ui/static/scene3d.js +2 -15
  98. package/ui/forge_ui/static/settings.js +336 -41
  99. package/ui/forge_ui/static/style.css +19 -7
  100. package/references/jev.md +0 -865
  101. package/scripts/forge_jev/backtest.py +0 -322
  102. package/scripts/forge_jev/corpus.py +0 -156
  103. package/scripts/forge_jev/features.py +0 -24
  104. package/scripts/forge_jev/predict.py +0 -204
  105. package/scripts/forge_jev/review.py +0 -73
  106. package/scripts/forge_jev/routing.py +0 -271
  107. package/scripts/forge_jev/subset.py +0 -123
@@ -15,6 +15,9 @@
15
15
  const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
16
16
  const DONE = new Set(['MERGED', 'PASS', 'NOCHANGES']);
17
17
  const BAD = new Set(['FAIL', 'ERROR', 'CONFLICT', 'INFRA', 'TIMEOUT', 'INVALIDATED', 'INTERRUPTED', 'UNKNOWN', 'BLOCKED']);
18
+ // NEEDS_INPUT: stopped for an answer only the user can give. Neither DONE nor BAD, so never a failure.
19
+ const WAITING = new Set(['NEEDS_INPUT']);
20
+ const isWaiting = status => WAITING.has(status);
18
21
  const WEIGHT = { low: 1, medium: 2, high: 3 };
19
22
  const weight = t => WEIGHT[String(t && t.difficulty || '').toLowerCase()] || 2;
20
23
  const alias = spec => spec ? String(spec).split(':')[0] : null;
@@ -73,6 +76,7 @@
73
76
  }
74
77
 
75
78
  /* ---------- statuses ---------- */
79
+ // A waiting task is in neither set: a run with nothing else left is pending, not failed and not done.
76
80
  function runState(run) {
77
81
  const counts = run && run.counts || {};
78
82
  if (counts.RUNNING) return 'live';
@@ -180,6 +184,8 @@
180
184
  if (statuses.some(s => s === 'RUNNING')) return 'RUNNING';
181
185
  if (statuses.every(s => s === 'MERGED')) return 'MERGED';
182
186
  if (statuses.some(s => s === 'PENDING' || s === 'PASS')) return 'PENDING';
187
+ // only answers are missing: the integration waits for the user, not for a fix
188
+ if (statuses.some(isWaiting) && statuses.every(s => s === 'MERGED' || isWaiting(s))) return 'WAITING';
183
189
  return 'BLOCKED';
184
190
  }
185
191
  // How one final review reads as a stage. OUTDATED only once it is done and the reader says the
@@ -226,6 +232,21 @@
226
232
  if (n !== null && want !== null && n === want) return 'ACCEPTED';
227
233
  return raw;
228
234
  }
235
+ // The send-backs forge writes into attempts.tsv without a reviewer's verdict. The task status stays FAIL, but each
236
+ // is a failed attempt with its own word, and a note says what forge did with it.
237
+ const SENT_BACK = new Map([['BOUNCED', 'sent back: the review left blocking findings unaddressed'],
238
+ ['INCOMPLETE', 'sent back: the dwarf said it did not finish']]);
239
+ const attemptNote = status => SENT_BACK.get(status) || null;
240
+ const attemptFailed = status => status === 'FAIL' || status === 'ERROR' || SENT_BACK.has(status);
241
+ // The run's attribution (attribution.json) as the line under its verification result, or null when it names nothing.
242
+ function attributionLine(a) {
243
+ if (!a || typeof a !== 'object') return null;
244
+ const n = num(a.verification_runs), runs = (word) => n === null ? '' : ` (${n} ${word}${n === 1 ? '' : 's'})`;
245
+ if (a.culprit) return `integration failure: merge ${a.culprit} breaks verification${runs('verification run')}`;
246
+ if (a.base_fails === true) return `the base already fails verification${runs('run')}`;
247
+ if (a.inconclusive) return `attribution inconclusive: ${a.inconclusive}${runs('run')}`;
248
+ return null;
249
+ }
229
250
  function shortTip(tip) {
230
251
  if (tip === null || tip === undefined || tip === '') return '—';
231
252
  return String(tip).slice(0, 7);
@@ -873,7 +894,8 @@
873
894
  }
874
895
 
875
896
  return { liveNow, runState, execStatus, matchRun, filterOptions, atlasModel, columns, planModel, finishState,
876
- finalStatus, runReviewStatus, reviewSinceLine, reviewAt, taskStatus, taskVerdict, attemptStatus, taskParts,
897
+ finalStatus, runReviewStatus, reviewSinceLine, reviewAt, taskStatus, taskVerdict, attemptStatus, attemptNote, attemptFailed, isWaiting,
898
+ attributionLine, taskParts,
877
899
  taskTimes, metricValue, overlap, projectSchedule, execModel, verifyLeds, criticalPath, concurrency, stateAt, timeRange, events, lineage, structureKey, innerKey,
878
900
  fmtDur, alias, basename, weight, searchIndex, searchRank, statusEvents, fractalTree, sweepLine, sweepState };
879
901
  });
@@ -167,6 +167,7 @@ export async function createStage(host, cb = {}) {
167
167
  const parts = [r.kind === 'solo' ? (Object.keys(c)[0] || 'solo') : `${merged}/${total} done`];
168
168
  if (running) parts.push(`${running} running`);
169
169
  if (bad) parts.push(`${bad} failed`);
170
+ if (c.NEEDS_INPUT) parts.push(`${c.NEEDS_INPUT} waiting for you`); // not in the failed count: it waits for an answer
170
171
  const reviewStatus = RM.runReviewStatus(r);
171
172
  if (reviewStatus) parts.push(`review ${reviewStatus}`);
172
173
  else if (r.verification_status) parts.push(`verify ${r.verification_status}`);
@@ -271,18 +272,6 @@ export async function createStage(host, cb = {}) {
271
272
  el.ledCount = tries;
272
273
  setLeds(el, attemptLamps(t).slice(-el.ledCount));
273
274
  display(el, taskLine, { w: w - 24, x: x + 12, y: y + d, z: h - 8 });
274
- // the Clef ring: how likely the first try was to pass, in the colour of what happened
275
- const p0 = t.clef && t.clef.first_pass && num(t.clef.first_pass.p);
276
- if (p0 !== null) {
277
- const cx0 = x + w - 22, cy0 = y + 22, rIn = 8, rOut = 11.5;
278
- const bgM = new THREE.MeshBasicMaterial({ color: E.DETAIL.clone(), toneMapped: false, transparent: true, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -12 });
279
- const fgM = new THREE.MeshBasicMaterial({ color: 0xffffff, toneMapped: false, transparent: true, polygonOffset: true, polygonOffsetFactor: -5, polygonOffsetUnits: -14 });
280
- for (const [m, len] of [[bgM, Math.PI * 2], [fgM, Math.max(.05, Math.min(1, p0)) * Math.PI * 2]]) {
281
- const ring = E.noRay(new THREE.Mesh(new THREE.RingGeometry(rIn * TS, rOut * TS, 40, 1, Math.PI / 2, len), m));
282
- ring.rotation.x = -Math.PI / 2; ring.position.copy(W(cx0, cy0, h + .2)); el.cover.add(ring); el.M.labs.push(m);
283
- }
284
- el.clef = { fgM, p: p0 };
285
- }
286
275
  halo(el);
287
276
  return el;
288
277
  }
@@ -975,7 +964,6 @@ export async function createStage(host, cb = {}) {
975
964
  if (c.tint > .001) el.M.body.color.lerp(TMP2.copy(col), c.tint * c.vis);
976
965
  if (el.tintMat) { el.tintMat.color.copy(col); el.tintMat.opacity = (c.tint * (E.theme === 'light' ? 1.45 : 1.1) + .08 * c.sel) * ob * gf * c.vis; }
977
966
  if (el.haloMat) el.haloMat.uniforms.opacity.value = (c.halo + (el.pulse ? .12 * pulseK : 0)) * gf * c.vis;
978
- if (el.clef) el.clef.fgM.color.copy(E.statusColor(['MERGED', 'PASS', 'ACCEPTED'].includes(el.status) ? 'pass' : ['FAIL', 'ERROR', 'CONFLICT'].includes(el.status) ? 'fail' : 'pending'));
979
967
  if (el.inner) {
980
968
  const p = pr ? pr.p : 0, vis = p > .002;
981
969
  if (!vis && el.inner.visible) { E.release(el.inner); }
@@ -1260,7 +1248,7 @@ export async function createStage(host, cb = {}) {
1260
1248
  const lamps = { title: 'Lamps', rows: [
1261
1249
  { sw: { lamp: 'st-merged' }, label: 'merged · passed · accepted' }, { sw: { lamp: 'st-running' }, label: 'running · interrupted' },
1262
1250
  { sw: { lamp: 'st-fail' }, label: 'failed · conflict · infra · timeout' }, { sw: { lamp: 'st-pending' }, label: 'pending, not started' },
1263
- { sw: { lamp: 'st-outdated' }, label: 'outdated review' },
1251
+ { sw: { lamp: 'st-outdated' }, label: 'outdated review' }, { sw: { lamp: 'st-needs_input' }, label: 'waiting for you' },
1264
1252
  { sw: { route: true }, label: st.view === 'atlas' ? 'chosen run' : 'chosen task' + (L.route ? ' and its route' : '') }] };
1265
1253
  if (st.view === 'atlas') {
1266
1254
  out.push({ title: 'Map', rows: [], note: 'Each block is a run, each district a repository. The lamps on a block are its tasks; the block stands taller the more tasks it has.' }, lamps);
@@ -1283,7 +1271,6 @@ export async function createStage(host, cb = {}) {
1283
1271
  if (fs.some(it => it.plausible)) rows.push({ sw: { sev: 'P2', pale: true }, label: 'plausible: smaller, paler' });
1284
1272
  out.push({ title: 'Findings', rows, note: 'A click opens the diff at the finding.' });
1285
1273
  }
1286
- if (o.arcs && list(st.run.tasks).some(t => t.clef && t.clef.first_pass)) out.push({ title: 'Review marks', rows: [{ sw: { ring: true }, label: 'Clef ring: the chance the first try passes' }] });
1287
1274
  if (o.height !== 'none') {
1288
1275
  const mx = st.metricMax && st.metricMax[o.height];
1289
1276
  out.push({ title: 'Height', rows: [{ sw: { height: true }, label: `${o.height}: up to ${fmtMetric(o.height, mx)}` }] });
@@ -1,11 +1,13 @@
1
1
  /* forge-ui settings view (window.ForgeSettings, and a CommonJS module under node:test). Route #/settings: the model
2
- registry (read-only), Jev, the three per-repo .forge files of one repository, the dataset and the FORGE_* environment.
3
- The pure helpers (request bodies, value checks, the repository picker, the editors' unsaved-text state) are tested in
4
- ui/tests/js/settings.test.js; render(host, ctx) is thin DOM over them. Every value from the server enters the page as text.
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.
5
6
  ctx = { key (the run whose repo to show, or null), runs() (the run list), onPick?(key) }. render returns { poll() }:
6
7
  the page calls it on each refresh, and unsaved editor text survives it.
7
8
  The calls are GET /api/config?run=<key> and POST /api/config, see ui/docs/api.md, "Controls (write endpoints)". A write
8
- changes a file in the repository's working tree (or forge's own Jev config) and is only offered with controls on. */
9
+ changes a file in the repository's working tree, or a decision-model gate in forge's user config, and is only offered
10
+ with controls on. */
9
11
  (function (root, factory) {
10
12
  'use strict';
11
13
  const api = factory(root);
@@ -16,6 +18,12 @@
16
18
 
17
19
  const FILES = ['verify', 'setup', 'verify-subset'];
18
20
  const VALUE_MAX = 4096;
21
+ const DECIDE_VALUE_MAX = 256;
22
+ // The same names as forge_decide.GATES. The section renders this list, not whatever keys a payload happens to carry.
23
+ const GATES = ['drift', 'forward', 'prompt', 'memory-curate', 'memory-slice', 'memory-stale', 'verify-discover',
24
+ 'coverage', 'retry-addressed', 'dwarf-message', 'attribution', 'findings'];
25
+ const MODES = ['off', 'shadow', 'on'];
26
+ const ADD_COMMAND = 'forge decide provider add …';
19
27
  const POLL_MS = 20000; // the config rarely changes, and each read starts a CLI process
20
28
  const list = v => Array.isArray(v) ? v : [];
21
29
  const object = v => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
@@ -23,13 +31,14 @@
23
31
  const basename = p => String(p || '').replace(/\/+$/, '').split('/').pop() || String(p || '');
24
32
 
25
33
  /* ---------- pure ---------- */
26
- // The POST body: a set carries `value`, an unset carries `unset: true`, never both. jev.enabled's value is the text
27
- // 'true' or 'false', as the CLI takes it.
34
+ // The POST body: a set carries `value`, an unset carries `unset: true`, never both.
28
35
  function configBody(run, key, value, unset) {
29
36
  if (unset) return { run: String(run), key: String(key), unset: true };
30
37
  return { run: String(run), key: String(key), value: String(value) };
31
38
  }
32
39
  const repoKey = name => 'repo.' + name;
40
+ // decide.gate.<gate>, or the same with .provider or .model.
41
+ const gateKey = (name, field) => 'decide.gate.' + name + (field ? '.' + field : '');
33
42
  // The file a save or remove touches, as the confirm names it.
34
43
  const targetPath = (repo, name) => String(repo || '').replace(/\/+$/, '') + '/.forge/' + name;
35
44
 
@@ -48,6 +57,120 @@
48
57
  return null;
49
58
  }
50
59
 
60
+ // Why a provider or model would be refused: empty, too long, a control character (newline and tab included),
61
+ // leading or trailing whitespace, or a leading '-'. The same rules as the server, so a bad value is never posted.
62
+ function decideTextProblem(value) {
63
+ const v = text(value);
64
+ if (!v.trim()) return 'Empty.';
65
+ if (v !== v.trim()) return 'The text cannot start or end with a space.';
66
+ const chars = Array.from(v).length;
67
+ if (chars > DECIDE_VALUE_MAX) return `Too long: ${chars} of ${DECIDE_VALUE_MAX} characters.`;
68
+ if (/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(v)) return 'The text has an unpaired surrogate, which cannot be saved.';
69
+ if (/[\u0000-\u001f\u007f]/.test(v)) return 'Control characters are not allowed.';
70
+ if (v.startsWith('-')) return 'The text cannot start with "-".';
71
+ return null;
72
+ }
73
+
74
+ const finite = n => typeof n === 'number' && Number.isFinite(n);
75
+ const capTokens = n => finite(n) ? String(n) : 'none';
76
+ const capMoney = n => finite(n) ? n.toFixed(4) : 'none';
77
+ const money = n => finite(n) ? n.toFixed(4) : '0.0000';
78
+ const count = n => finite(n) ? String(n) : '0';
79
+ // How a shadowed value is named in the note. Strings keep their JSON quotes so a mode is not a bare word.
80
+ function literal(value) {
81
+ if (value == null) return 'nothing';
82
+ if (typeof value === 'string') return JSON.stringify(value);
83
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
84
+ if (typeof value === 'boolean') return String(value);
85
+ return 'a value';
86
+ }
87
+
88
+ // The replay a gate carries, or null: `forge decide replay`'s recorded result for the gate's provider and model. An older
89
+ // forge sends none, which reads as no replay, never as an error.
90
+ function describeReplay(replay) {
91
+ if (!replay || typeof replay !== 'object' || Array.isArray(replay)) return null;
92
+ return { provider: text(replay.provider), model: text(replay.model), passes: replay.passes === true, at: finite(replay.at) ? replay.at : null };
93
+ }
94
+ // The day a replay was recorded, in local time like the CLI's `replayed <date>`; '?' when the time is unusable.
95
+ function replayDate(at) {
96
+ const d = finite(at) ? new Date(at * 1000) : null;
97
+ if (!d || Number.isNaN(d.getTime())) return '?';
98
+ const two = n => String(n).padStart(2, '0');
99
+ return d.getFullYear() + '-' + two(d.getMonth() + 1) + '-' + two(d.getDate());
100
+ }
101
+ // The tags a gate row shows beside its source tag: [{suffix, text, title, bad}], the element id being
102
+ // set-gate-<name>-<suffix>. A forced gate acts on without a passing replay; a replay shows when it was recorded and
103
+ // whether it passed. A gate with neither has none.
104
+ function gateTags(gate) {
105
+ const tags = [];
106
+ const replay = gate.replay;
107
+ const on = replay ? replay.provider + '/' + replay.model : '';
108
+ if (gate.forced && gate.mode === 'on') {
109
+ tags.push({ suffix: 'forced', text: 'forced', bad: true,
110
+ title: 'This gate acts without a recorded replay for its provider and model that passes.' });
111
+ }
112
+ if (replay) {
113
+ tags.push(replay.passes
114
+ ? { suffix: 'replay', text: 'replayed ' + replayDate(replay.at), title: 'Replay on ' + on + ' passed.', bad: false }
115
+ : { suffix: 'replay', text: 'replay failed', title: 'Replay on ' + on + ' did not pass (' + replayDate(replay.at) + ').', bad: true });
116
+ }
117
+ return tags;
118
+ }
119
+
120
+ // The Decision models section, as data. render() draws only this, so the page and the test share one reading of the
121
+ // status object. Provider key fields are dropped here and never reach a string the page shows.
122
+ function describeDecide(decide) {
123
+ const d = object(decide);
124
+ const gatesIn = object(d.gates);
125
+ const floor = object(d.privacy).floor === true;
126
+ const providers = Object.keys(object(d.providers)).sort().map(name => {
127
+ const row = object(object(d.providers)[name]);
128
+ return { name, type: text(row.type), local: row.local === true };
129
+ });
130
+ const gates = GATES.map(name => {
131
+ const g = object(gatesIn[name]);
132
+ const skip = floor ? 'privacy' : (typeof g.skip === 'string' ? g.skip : '');
133
+ const mode = MODES.includes(g.mode) ? g.mode : 'off';
134
+ const source = text(g.source) || 'default';
135
+ return {
136
+ name,
137
+ mode,
138
+ source,
139
+ // The mode the user level holds, where the status shows it: the user file set it and no override applies.
140
+ userMode: source === 'user' && !skip ? mode : null,
141
+ provider: typeof g.provider === 'string' ? g.provider : '',
142
+ model: typeof g.model === 'string' ? g.model : '',
143
+ skip,
144
+ ready: g.ready === true,
145
+ forced: g.forced === true,
146
+ replay: describeReplay(g.replay),
147
+ };
148
+ });
149
+ const caps = object(object(d.budget).caps);
150
+ const spend = object(object(d.budget).spend);
151
+ const today = object(spend.today);
152
+ const date = text(spend.date) || '—';
153
+ const line = 'run cap ' + capTokens(caps.run_tokens) + ' tokens, $' + capMoney(caps.run_usd)
154
+ + '; daily cap ' + capTokens(caps.daily_tokens) + ' tokens, $' + capMoney(caps.daily_usd)
155
+ + '; today (' + date + '): ' + count(today.tokens) + ' tokens of ' + capTokens(caps.daily_tokens)
156
+ + ', $' + money(today.usd) + ' of $' + capMoney(caps.daily_usd);
157
+ const shadowed = list(d.shadowed).filter(e => e && typeof e === 'object').map(e => ({
158
+ key: text(e.key),
159
+ note: text(e.key) + ': the repo sets ' + literal(e.repo) + ', the user file\'s ' + literal(e.user) + ' wins',
160
+ }));
161
+ return {
162
+ gates, privacyFloor: floor,
163
+ banner: floor ? 'Nothing is sent. This repository is under a privacy floor.' : '',
164
+ budget: {
165
+ run: { tokens: caps.run_tokens == null ? null : caps.run_tokens, usd: caps.run_usd == null ? null : caps.run_usd },
166
+ daily: { tokens: caps.daily_tokens == null ? null : caps.daily_tokens, usd: caps.daily_usd == null ? null : caps.daily_usd },
167
+ today: { tokens: today.tokens == null ? 0 : today.tokens, usd: today.usd == null ? 0 : today.usd, date },
168
+ line,
169
+ },
170
+ shadowed, providers, noProviders: providers.length === 0, addCommand: ADD_COMMAND,
171
+ };
172
+ }
173
+
51
174
  // The runs a repository can be taken from (those that name one), newest first.
52
175
  const withRepo = runs => list(runs).filter(r => r && r.key != null && typeof r.repo === 'string' && r.repo);
53
176
  const newestFirst = (a, b) => (Number(b.updated) || 0) - (Number(a.updated) || 0);
@@ -103,12 +226,12 @@
103
226
  function render(host, ctx) {
104
227
  const UI = root.ForgeUI, c = ctx || {};
105
228
  const el = (tag, t, cls) => UI.el(tag, t, cls);
106
- const s = { run: null, data: null, dataText: null, error: null, writes: false, loading: true, editors: {}, moved: {}, hold: 0, redraw: false, seq: 0, gen: 0, runsSig: null, ready: false, loadedAt: 0, repo: null, gone: false, asking: 0, asks: 0, pickerLate: false };
229
+ 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 };
107
230
  const key_ = (label, cls, onclick) => { const b = el('button', label, cls); b.type = 'button'; if (onclick) b.addEventListener('click', onclick); return b; };
108
231
 
109
232
  const head = el('header', undefined, 'set-head');
110
233
  head.append(el('h1', 'Settings', 'module-title'),
111
- el('p', 'What forge reads when it runs: its model registry and Jev switch, and the three files a repository can keep in .forge.', 'muted set-lede'));
234
+ 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'));
112
235
  const picker = el('div', undefined, 'set-picker');
113
236
  const body = el('div', undefined, 'set-body');
114
237
  const note = el('p', 'This page is read-only: this server has no write token, or has controls off.', 'muted set-readonly');
@@ -178,7 +301,7 @@
178
301
  // A new run: nothing of the old one stays, and confirms of the old body (now detached) no longer hold a redraw.
179
302
  function resetRun() {
180
303
  staleNote(null);
181
- s.data = null; s.dataText = null; s.error = null; s.editors = {}; s.moved = {}; s.loading = s.run != null;
304
+ s.data = null; s.dataText = null; s.error = null; s.editors = {}; s.moved = {}; s.models = {}; s.modelMoved = {}; s.loading = s.run != null;
182
305
  s.gen++; s.hold = 0; s.redraw = false;
183
306
  }
184
307
  function pick(key) {
@@ -210,6 +333,10 @@
210
333
  const next = dirtyState(s.editors[name], object(files[name]).content);
211
334
  s.editors[name] = next.editor; s.moved[name] = next.moved || (next.dirty && !!s.moved[name]);
212
335
  }
336
+ for (const g of describeDecide(res.data.decide).gates) {
337
+ const next = dirtyState(s.models[g.name], g.model);
338
+ s.models[g.name] = next.editor; s.modelMoved[g.name] = next.moved || (next.dirty && !!s.modelMoved[g.name]);
339
+ }
213
340
  const t = JSON.stringify(res.data);
214
341
  if (t === s.dataText && !s.redraw) return;
215
342
  s.data = res.data; s.dataText = t;
@@ -224,13 +351,14 @@
224
351
 
225
352
  function drawBody() {
226
353
  const focus = document.activeElement && body.contains(document.activeElement) ? document.activeElement : null;
227
- const at = focus && focus.dataset.editor ? { name: focus.dataset.editor, a: focus.selectionStart, b: focus.selectionEnd } : null;
354
+ const at = focus && focus.dataset.editor ? { kind: 'editor', name: focus.dataset.editor, a: focus.selectionStart, b: focus.selectionEnd }
355
+ : focus && focus.dataset.model ? { kind: 'model', name: focus.dataset.model, a: focus.selectionStart, b: focus.selectionEnd } : null;
228
356
  if (s.loading) { body.replaceChildren(el('p', 'Reading the configuration…', 'muted')); return; }
229
357
  if (s.error) { body.replaceChildren(el('p', 'Could not read the configuration: ' + s.error, 'warn')); return; }
230
358
  if (!s.data) { body.replaceChildren(); return; }
231
- body.replaceChildren(registrySection(), jevSection(), repoSection(), datasetSection(), envSection());
359
+ body.replaceChildren(registrySection(), decideSection(), repoSection(), datasetSection(), envSection());
232
360
  if (at) {
233
- const t = body.querySelector(`textarea[data-editor="${at.name}"]`);
361
+ const t = at.kind === 'model' ? body.querySelector(`input[data-model="${at.name}"]`) : body.querySelector(`textarea[data-editor="${at.name}"]`);
234
362
  if (t) { t.focus({ preventScroll: true }); try { t.setSelectionRange(at.a, at.b); } catch (_) { /* not selectable */ } }
235
363
  }
236
364
  }
@@ -274,37 +402,203 @@
274
402
  return sec;
275
403
  }
276
404
 
277
- function jevSection() {
278
- const jev = object(s.data.jev), on = !!jev.enabled;
279
- const sec = section('jev', 'Jev', 'Forge\'s own switch for its decision model. It lives in forge\'s config, so it applies to every repository and run, not only this one.');
280
- sec.append(pathLine('config', text(jev.path), jev.exists ? null : 'absent'));
281
- const row = el('div', undefined, 'set-switch-row');
282
- const lamp = el('i', undefined, 'lamp ' + (on ? 'st-pass' : ''));
283
- const state = el('span', on ? 'Jev is enabled' : 'Jev is disabled', 'set-state');
284
- row.append(lamp, state);
285
- const result = el('div', undefined, 'set-result');
286
- if (s.writes) {
287
- const sw = el('button', undefined, 'set-switch'); sw.type = 'button';
288
- sw.setAttribute('role', 'switch'); sw.setAttribute('aria-checked', String(on));
289
- sw.append(el('span', undefined, 'set-switch-knob'), el('span', on ? 'On' : 'Off', 'set-switch-label'));
290
- sw.setAttribute('aria-label', 'Jev enabled');
291
- sw.addEventListener('click', async () => {
292
- const next = !on;
293
- const gen = s.gen, release = grab();
294
- sw.disabled = true;
295
- const yes = await UI.confirmInline(result, `Turn Jev ${next ? 'on' : 'off'}? This changes forge's own config (${text(jev.path)}) for every repository.`);
296
- if (!yes) { sw.disabled = false; release(); sw.focus({ preventScroll: true }); return; }
297
- const res = await UI.post('/api/config', configBody(s.run, 'jev.enabled', next));
298
- UI.outcome(result, res, `Jev is now ${next ? 'enabled' : 'disabled'}.`);
299
- sw.disabled = false; release();
300
- if (res.ok && gen === s.gen) await reload();
301
- });
302
- row.append(sw);
405
+ function decideSection() {
406
+ const view = describeDecide(s.data.decide);
407
+ 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.');
408
+ const where = text(object(s.data.decide).user_path);
409
+ if (where) sec.append(pathLine('config', where));
410
+ if (view.privacyFloor) {
411
+ const banner = el('p', view.banner, 'set-banner');
412
+ banner.id = 'set-decide-privacy';
413
+ sec.append(banner);
303
414
  }
304
- sec.append(row, result);
415
+ const budget = el('p', view.budget.line, 'muted set-budget');
416
+ budget.id = 'set-decide-budget';
417
+ sec.append(budget);
418
+ if (view.noProviders) {
419
+ const note = el('p', undefined, 'muted');
420
+ note.append(el('span', 'No provider is configured. Add one with '), el('span', view.addCommand, 'mono'), el('span', '.'));
421
+ sec.append(note);
422
+ }
423
+ for (const item of view.shadowed) sec.append(el('p', item.note, 'muted'));
424
+ const gates = el('div', undefined, 'set-gates');
425
+ for (const gate of view.gates) gates.append(gateRow(gate, view.providers));
426
+ sec.append(gates);
305
427
  return sec;
306
428
  }
307
429
 
430
+ const providerLabel = p => [p.name, p.type, p.local ? 'local' : ''].filter(Boolean).join(' · ');
431
+
432
+ function gateRow(gate, providers) {
433
+ const art = el('article', undefined, 'set-file set-gate');
434
+ art.id = 'set-gate-' + gate.name;
435
+ const h = el('h3', gate.name, 'set-file-name');
436
+ const status = el('p', undefined, 'set-file-status');
437
+ const source = el('span', gate.source, 'tag');
438
+ source.id = 'set-gate-' + gate.name + '-source';
439
+ status.append(source);
440
+ for (const t of gateTags(gate)) {
441
+ const tag = el('span', t.text, t.bad ? 'tag tag-bad' : 'tag');
442
+ tag.id = 'set-gate-' + gate.name + '-' + t.suffix;
443
+ tag.title = t.title;
444
+ status.append(tag);
445
+ }
446
+ if (gate.skip) status.append(el('span', 'skip: ' + gate.skip, 'set-gate-skip'));
447
+ const top = el('div', undefined, 'set-file-head');
448
+ top.append(h, status);
449
+ art.append(top);
450
+ if (!s.writes) {
451
+ const bits = ['mode ' + gate.mode, gate.provider ? 'provider ' + gate.provider : 'no provider', gate.model ? 'model ' + gate.model : 'no model'];
452
+ art.append(el('p', bits.join(', '), 'muted'));
453
+ return art;
454
+ }
455
+ const result = el('div', undefined, 'set-result');
456
+ const row = el('div', undefined, 'filters');
457
+ row.append(modeField(gate, result), providerField(gate, providers, result), modelField(gate, result));
458
+ art.append(row, result);
459
+ return art;
460
+ }
461
+
462
+ function modeField(gate, result) {
463
+ const lab = el('label', undefined, 'filter');
464
+ const sel = el('select');
465
+ sel.id = 'set-gate-' + gate.name + '-mode';
466
+ sel.setAttribute('aria-label', 'Mode for ' + gate.name);
467
+ // The select shows the user level's mode when the status has it. Otherwise the mode in effect is a label that no
468
+ // choice matches, so every mode is a choice that writes the user level, the one in effect included.
469
+ const rest = gate.userMode || ''; // the value the select goes back to
470
+ if (!gate.userMode) {
471
+ const effect = el('option', 'in effect: ' + gate.mode);
472
+ effect.value = ''; effect.disabled = true; effect.selected = true;
473
+ sel.append(effect);
474
+ }
475
+ for (const mode of MODES) {
476
+ const o = el('option', mode);
477
+ o.value = mode;
478
+ o.selected = mode === gate.userMode;
479
+ sel.append(o);
480
+ }
481
+ sel.addEventListener('change', async () => {
482
+ const next = sel.value;
483
+ if (!MODES.includes(next) || next === gate.userMode) { sel.value = rest; return; }
484
+ const gen = s.gen, release = grab();
485
+ sel.disabled = true;
486
+ const yes = await UI.confirmInline(result, `Set ${gate.name} to ${next}? This writes your forge config (the user level) for every repository.`);
487
+ if (!yes || gen !== s.gen) {
488
+ sel.value = rest; sel.disabled = false; release();
489
+ if (!yes && gen === s.gen) sel.focus({ preventScroll: true });
490
+ return;
491
+ }
492
+ const res = await UI.post('/api/config', configBody(s.run, gateKey(gate.name), next));
493
+ UI.outcome(result, res, `${gate.name} is set to ${next}.`);
494
+ if (!res.ok) sel.value = rest;
495
+ sel.disabled = false; release();
496
+ if (res.ok && gen === s.gen) await reload();
497
+ });
498
+ lab.append(el('span', 'Mode'), sel);
499
+ return lab;
500
+ }
501
+
502
+ function providerField(gate, providers, result) {
503
+ const lab = el('label', undefined, 'filter');
504
+ const sel = el('select');
505
+ sel.id = 'set-gate-' + gate.name + '-provider';
506
+ sel.setAttribute('aria-label', 'Provider for ' + gate.name);
507
+ const blank = el('option', providers.length ? 'Default' : 'No provider');
508
+ blank.value = '';
509
+ if (gate.provider) blank.disabled = true;
510
+ sel.append(blank);
511
+ const known = new Set(providers.map(p => p.name));
512
+ for (const p of providers) {
513
+ const o = el('option', providerLabel(p));
514
+ o.value = p.name;
515
+ o.selected = p.name === gate.provider;
516
+ sel.append(o);
517
+ }
518
+ if (gate.provider && !known.has(gate.provider)) {
519
+ const o = el('option', gate.provider + ' · not configured');
520
+ o.value = gate.provider;
521
+ o.selected = true;
522
+ sel.append(o);
523
+ }
524
+ if (!providers.length) sel.disabled = true;
525
+ sel.addEventListener('change', async () => {
526
+ const next = sel.value;
527
+ if (!next || next === gate.provider) { sel.value = gate.provider; return; }
528
+ if (decideTextProblem(next)) { sel.value = gate.provider; return; }
529
+ const gen = s.gen, release = grab();
530
+ sel.disabled = true;
531
+ const yes = await UI.confirmInline(result, `Set the provider for ${gate.name} to ${next}? This writes your forge config (the user level) for every repository.`);
532
+ if (!yes || gen !== s.gen) {
533
+ sel.value = gate.provider;
534
+ sel.disabled = providers.length === 0;
535
+ release();
536
+ if (!yes && gen === s.gen) sel.focus({ preventScroll: true });
537
+ return;
538
+ }
539
+ const res = await UI.post('/api/config', configBody(s.run, gateKey(gate.name, 'provider'), next));
540
+ UI.outcome(result, res, `The provider for ${gate.name} is set to ${next}.`);
541
+ if (!res.ok) sel.value = gate.provider;
542
+ sel.disabled = false; release();
543
+ if (res.ok && gen === s.gen) await reload();
544
+ });
545
+ lab.append(el('span', 'Provider'), sel);
546
+ return lab;
547
+ }
548
+
549
+ function modelField(gate, result) {
550
+ const id = 'set-gate-' + gate.name + '-model';
551
+ const ed = s.models[gate.name] || (s.models[gate.name] = editorOf(gate.model));
552
+ const wrap = el('div', undefined, 'filter');
553
+ const input = el('input', undefined, 'mono');
554
+ input.type = 'text'; input.id = id; input.dataset.model = gate.name;
555
+ input.spellcheck = false; input.setAttribute('autocomplete', 'off'); input.setAttribute('autocapitalize', 'off');
556
+ input.setAttribute('aria-label', 'Model for ' + gate.name);
557
+ input.value = shown(ed);
558
+ let from = ed.base;
559
+ const movedNote = el('p', 'The model changed on disk after you began editing; saving replaces it with your text.', 'warn set-file-note');
560
+ movedNote.hidden = !(isDirty(ed) && s.modelMoved[gate.name]);
561
+ const problem = el('p', undefined, 'warn set-problem');
562
+ problem.hidden = true; problem.id = id + '-problem';
563
+ const set = key_('Set', 'primary');
564
+ set.setAttribute('aria-label', 'Set model for ' + gate.name);
565
+ const sync = () => {
566
+ const cur = s.models[gate.name], dirtyNow = isDirty(cur), bad = dirtyNow ? decideTextProblem(cur.draft) : null;
567
+ problem.hidden = !bad; problem.textContent = bad || '';
568
+ if (bad) { input.setAttribute('aria-invalid', 'true'); input.setAttribute('aria-describedby', problem.id); }
569
+ else { input.removeAttribute('aria-invalid'); input.removeAttribute('aria-describedby'); }
570
+ set.disabled = !dirtyNow || !!bad;
571
+ movedNote.hidden = !(dirtyNow && s.modelMoved[gate.name]);
572
+ };
573
+ input.addEventListener('input', () => {
574
+ const next = typed(s.models[gate.name], input.value, from);
575
+ s.models[gate.name] = next.editor;
576
+ s.modelMoved[gate.name] = next.moved || (next.dirty && !!s.modelMoved[gate.name]);
577
+ sync();
578
+ });
579
+ set.addEventListener('click', async () => {
580
+ const cur = s.models[gate.name], bad = decideTextProblem(shown(cur));
581
+ if (!isDirty(cur) || bad) { sync(); return; }
582
+ const draft = cur.draft;
583
+ const gen = s.gen, release = grab();
584
+ set.disabled = true; input.readOnly = true;
585
+ const yes = await UI.confirmInline(result, `Set the model for ${gate.name} to ${draft}? This writes your forge config (the user level) for every repository.`);
586
+ if (!yes || gen !== s.gen) {
587
+ input.readOnly = false; release(); sync();
588
+ if (!yes && gen === s.gen) set.focus({ preventScroll: true });
589
+ return;
590
+ }
591
+ const res = await UI.post('/api/config', configBody(s.run, gateKey(gate.name, 'model'), draft));
592
+ UI.outcome(result, res, `The model for ${gate.name} is set.`);
593
+ if (res.ok && gen === s.gen) { s.models[gate.name] = editorOf(draft); s.modelMoved[gate.name] = false; from = draft; }
594
+ input.readOnly = false; release(); sync();
595
+ if (res.ok && gen === s.gen) await reload();
596
+ });
597
+ wrap.append(el('span', 'Model'), input, problem, movedNote, set);
598
+ sync();
599
+ return wrap;
600
+ }
601
+
308
602
  function repoSection() {
309
603
  const repo = object(s.data.repo), files = object(repo.files);
310
604
  const sec = section('repo', 'This repository');
@@ -430,6 +724,7 @@
430
724
  return { poll, pick };
431
725
  }
432
726
 
433
- return { render, configBody, repoKey, targetPath, subsetOk, valueProblem, pickDefault, groupRuns, optionLabel,
434
- editorOf, isDirty, dirtyState, edited, typed, shown, readFailure, FILES, VALUE_MAX };
727
+ return { render, configBody, repoKey, gateKey, targetPath, subsetOk, valueProblem, decideTextProblem, describeDecide, gateTags, replayDate,
728
+ pickDefault, groupRuns, optionLabel, editorOf, isDirty, dirtyState, edited, typed, shown, readFailure,
729
+ FILES, GATES, MODES, VALUE_MAX, DECIDE_VALUE_MAX, ADD_COMMAND };
435
730
  });