@richjava/req0 0.1.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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -0
  3. package/cockpit/android-chrome-192x192.png +0 -0
  4. package/cockpit/android-chrome-512x512.png +0 -0
  5. package/cockpit/app.js +1710 -0
  6. package/cockpit/apple-touch-icon.png +0 -0
  7. package/cockpit/favicon-16x16.png +0 -0
  8. package/cockpit/favicon-32x32.png +0 -0
  9. package/cockpit/favicon.ico +0 -0
  10. package/cockpit/index.html +180 -0
  11. package/cockpit/markdown-editor.js +93 -0
  12. package/cockpit/req0-logo-horiz.png +0 -0
  13. package/cockpit/req0-logo-stacked.png +0 -0
  14. package/cockpit/site.webmanifest +19 -0
  15. package/cockpit/styles.css +1710 -0
  16. package/cockpit/tokens.css +118 -0
  17. package/dist/adapter.d.ts +5 -0
  18. package/dist/adapter.js +16 -0
  19. package/dist/browser.d.ts +33 -0
  20. package/dist/browser.js +524 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +265 -0
  23. package/dist/compile.d.ts +5 -0
  24. package/dist/compile.js +456 -0
  25. package/dist/diff.d.ts +15 -0
  26. package/dist/diff.js +114 -0
  27. package/dist/fix-from-proof.d.ts +13 -0
  28. package/dist/fix-from-proof.js +61 -0
  29. package/dist/gates.d.ts +7 -0
  30. package/dist/gates.js +7 -0
  31. package/dist/implement-brief.d.ts +9 -0
  32. package/dist/implement-brief.js +142 -0
  33. package/dist/implement.d.ts +70 -0
  34. package/dist/implement.js +615 -0
  35. package/dist/improve-log.d.ts +11 -0
  36. package/dist/improve-log.js +38 -0
  37. package/dist/improve-review.d.ts +45 -0
  38. package/dist/improve-review.js +182 -0
  39. package/dist/improve.d.ts +16 -0
  40. package/dist/improve.js +127 -0
  41. package/dist/jev-pack.d.ts +2 -0
  42. package/dist/jev-pack.js +114 -0
  43. package/dist/jev.d.ts +23 -0
  44. package/dist/jev.js +142 -0
  45. package/dist/pack.d.ts +101 -0
  46. package/dist/pack.js +609 -0
  47. package/dist/personas.d.ts +13 -0
  48. package/dist/personas.js +88 -0
  49. package/dist/proof-report.d.ts +8 -0
  50. package/dist/proof-report.js +82 -0
  51. package/dist/proof.d.ts +45 -0
  52. package/dist/proof.js +394 -0
  53. package/dist/qa-plan.d.ts +6 -0
  54. package/dist/qa-plan.js +58 -0
  55. package/dist/ready.d.ts +29 -0
  56. package/dist/ready.js +317 -0
  57. package/dist/runtime.d.ts +25 -0
  58. package/dist/runtime.js +125 -0
  59. package/dist/server.d.ts +15 -0
  60. package/dist/server.js +588 -0
  61. package/dist/stack.d.ts +35 -0
  62. package/dist/stack.js +220 -0
  63. package/dist/stages.d.ts +15 -0
  64. package/dist/stages.js +345 -0
  65. package/dist/template.d.ts +5 -0
  66. package/dist/template.js +55 -0
  67. package/dist/types.d.ts +282 -0
  68. package/dist/types.js +12 -0
  69. package/docs/requirement-template.md +341 -0
  70. package/package.json +81 -0
package/cockpit/app.js ADDED
@@ -0,0 +1,1710 @@
1
+ import { createMarkdownEditor } from "./markdown-editor.js";
2
+
3
+ const els = {
4
+ title: document.getElementById("pack-title"),
5
+ going: document.getElementById("how-going"),
6
+ next: document.getElementById("next-action"),
7
+ hint: document.getElementById("next-hint"),
8
+ graph: document.getElementById("pipeline-graph"),
9
+ stageNav: document.getElementById("stage-nav"),
10
+ viewDefine: document.getElementById("view-define"),
11
+ viewSpec: document.getElementById("view-spec"),
12
+ viewJudgment: document.getElementById("view-judgment"),
13
+ viewImplement: document.getElementById("view-implement"),
14
+ viewQa: document.getElementById("view-qa"),
15
+ specStatus: document.getElementById("spec-status"),
16
+ specSections: document.getElementById("spec-sections"),
17
+ specFindings: document.getElementById("spec-findings"),
18
+ judgmentBadge: document.getElementById("judgment-badge"),
19
+ judgmentFindings: document.getElementById("judgment-findings"),
20
+ implementStatus: document.getElementById("implement-status"),
21
+ qaStatus: document.getElementById("qa-status"),
22
+ implementActivity: document.getElementById("implement-activity"),
23
+ qaActivity: document.getElementById("qa-activity"),
24
+ proofReport: document.getElementById("proof-report"),
25
+ actionReady: document.getElementById("action-ready"),
26
+ actionBuild: document.getElementById("action-build"),
27
+ actionBuildIgnore: document.getElementById("action-build-ignore"),
28
+ actionBuildStop: document.getElementById("action-build-stop"),
29
+ actionProof: document.getElementById("action-proof"),
30
+ actionFixProof: document.getElementById("action-fix-proof"),
31
+ ignoreDialog: document.getElementById("ignore-build-dialog"),
32
+ ignoreYes: document.getElementById("ignore-build-yes"),
33
+ ignoreNo: document.getElementById("ignore-build-no"),
34
+ ignoreCancel: document.getElementById("ignore-build-cancel"),
35
+ editor: document.getElementById("editor"),
36
+ save: document.getElementById("save-state"),
37
+ createBar: document.getElementById("create-bar"),
38
+ newId: document.getElementById("new-id"),
39
+ createNew: document.getElementById("create-new"),
40
+ createError: document.getElementById("create-error"),
41
+ homeBtn: document.getElementById("home-btn"),
42
+ allRequirements: document.getElementById("all-requirements"),
43
+ packHome: document.getElementById("pack-home"),
44
+ packWorkspace: document.getElementById("pack-workspace"),
45
+ packList: document.getElementById("pack-list"),
46
+ packEmpty: document.getElementById("pack-empty"),
47
+ packMenu: document.getElementById("pack-menu"),
48
+ packMenuDelete: document.getElementById("pack-menu-delete"),
49
+ deleteDialog: document.getElementById("delete-pack-dialog"),
50
+ deleteCopy: document.getElementById("delete-pack-copy"),
51
+ deleteCancel: document.getElementById("delete-pack-cancel"),
52
+ deleteConfirm: document.getElementById("delete-pack-confirm"),
53
+ stackGate: document.getElementById("stack-gate"),
54
+ setupTitle: document.getElementById("setup-title"),
55
+ setupCopy: document.getElementById("setup-copy"),
56
+ codingSection: document.getElementById("coding-section"),
57
+ stackSection: document.getElementById("stack-section"),
58
+ stackBar: document.getElementById("stack-bar"),
59
+ stackError: document.getElementById("stack-error"),
60
+ stackNextjs: document.getElementById("stack-nextjs"),
61
+ stackAmplify: document.getElementById("stack-amplify"),
62
+ codingManual: document.getElementById("coding-manual"),
63
+ codingCursor: document.getElementById("coding-cursor"),
64
+ codingCopilot: document.getElementById("coding-copilot"),
65
+ cockpitApp: document.getElementById("cockpit-app"),
66
+ workspace: document.getElementById("view-define"),
67
+ workspaceLabel: document.getElementById("workspace-label"),
68
+ reviewActions: document.getElementById("review-actions"),
69
+ reviewDiff: document.getElementById("review-diff"),
70
+ reviewAccept: document.getElementById("review-accept"),
71
+ reviewReject: document.getElementById("review-reject"),
72
+ };
73
+
74
+ let state = null;
75
+ let saveTimer;
76
+ let applying = false;
77
+
78
+ const markdownEditor = createMarkdownEditor(document.getElementById("editor"), {
79
+ onChange: () => {
80
+ if (applying) return;
81
+ applying = true;
82
+ els.save.textContent = "Saving…";
83
+ clearTimeout(saveTimer);
84
+ saveTimer = setTimeout(() => {
85
+ void saveMarkdown();
86
+ }, 280);
87
+ },
88
+ });
89
+ let currentView = "define";
90
+ let defineOpen = true;
91
+ let focusedSection = "Business Rules";
92
+ let actionNotice = "";
93
+ let actionBusy = false;
94
+ let headerBusyLabel = "";
95
+ let activityLines = [];
96
+ let lastActivityKey = "";
97
+ let loadInFlight = false;
98
+ let loadAgain = false;
99
+ let loadTimer;
100
+ let stateEpoch = 0;
101
+
102
+ function takeState(next) {
103
+ stateEpoch += 1;
104
+ state = next;
105
+ if (Array.isArray(state.activity)) activityLines = state.activity;
106
+ }
107
+
108
+ async function load() {
109
+ if (loadInFlight) {
110
+ loadAgain = true;
111
+ return;
112
+ }
113
+ loadInFlight = true;
114
+ const epoch = stateEpoch;
115
+ try {
116
+ const res = await fetch("/api/state", { signal: AbortSignal.timeout(8000) });
117
+ const body = await res.json();
118
+ if (epoch !== stateEpoch) return;
119
+ state = body;
120
+ if (Array.isArray(state.activity)) activityLines = state.activity;
121
+ render();
122
+ } catch (err) {
123
+ if (els.going) {
124
+ els.going.hidden = false;
125
+ els.going.textContent = err instanceof Error ? err.message : "Could not load the cockpit.";
126
+ }
127
+ } finally {
128
+ loadInFlight = false;
129
+ if (loadAgain) {
130
+ loadAgain = false;
131
+ void load();
132
+ }
133
+ }
134
+ }
135
+
136
+ function scheduleLoad() {
137
+ clearTimeout(loadTimer);
138
+ loadTimer = setTimeout(() => {
139
+ void load();
140
+ }, 250);
141
+ }
142
+
143
+ let pendingCoding = null;
144
+
145
+ function recordedAdapter() {
146
+ const repo = state?.productRepo;
147
+ if (!repo?.implement) return "manual";
148
+ if (repo.adapter === "copilot" || repo.adapter === "manual") return repo.adapter;
149
+ return "cursor";
150
+ }
151
+
152
+ function adapterLabel(id) {
153
+ if (id === "copilot") return "Copilot";
154
+ if (id === "manual") return "Manual";
155
+ return "Cursor";
156
+ }
157
+
158
+ function needsSetupGate(snapshot) {
159
+ const repo = snapshot?.productRepo;
160
+ if (!repo?.root) return false;
161
+ if (repo.implement && repo.adapterRecorded === false) return true;
162
+ return Boolean(repo.implement && repo.empty && !repo.recorded);
163
+ }
164
+
165
+ function renderSetupGate(snapshot) {
166
+ const repo = snapshot?.productRepo;
167
+ const needCoding = Boolean(repo?.implement && repo?.adapterRecorded === false);
168
+ const needStack = Boolean(repo?.implement && repo?.empty && !repo?.recorded);
169
+ const showStack = needStack && (!needCoding || Boolean(pendingCoding));
170
+ els.codingSection?.classList.toggle("hidden", !needCoding);
171
+ els.stackSection?.classList.toggle("hidden", !showStack);
172
+ for (const btn of [els.codingManual, els.codingCursor, els.codingCopilot]) {
173
+ if (!btn) continue;
174
+ btn.classList.toggle("is-selected", btn.dataset.coding === pendingCoding);
175
+ btn.disabled = false;
176
+ }
177
+ if (els.stackNextjs) els.stackNextjs.disabled = false;
178
+ if (els.stackAmplify) els.stackAmplify.disabled = false;
179
+ if (els.setupTitle) {
180
+ els.setupTitle.textContent = needCoding ? "Set up this project" : "Choose a stack";
181
+ }
182
+ if (els.setupCopy) {
183
+ els.setupCopy.textContent = needCoding
184
+ ? "Req0 writes your choices to req0.json. You can change them later by editing that file."
185
+ : "This product repo is empty and no stack is recorded yet. Pick one to continue. Amplify also writes a names-only .env.example if that file is missing.";
186
+ }
187
+ }
188
+
189
+ function render() {
190
+ const health = state.health;
191
+ const packId = state.packId;
192
+ const onHome = !packId;
193
+ const packList = Array.isArray(state.packList) ? state.packList : [];
194
+ els.title.textContent = packId ? `Requirement: ${packId.replaceAll("-", " ")}` : "Requirements";
195
+ els.going.textContent = packId
196
+ ? (health?.howThisIsGoing ?? "")
197
+ : packList.length
198
+ ? `${packList.length} requirement${packList.length === 1 ? "" : "s"}`
199
+ : "Create a requirement pack to begin.";
200
+ els.going.hidden = !els.going.textContent.trim();
201
+
202
+ const action = health?.nextAction;
203
+ const review = state.improveReview;
204
+ if (review?.files?.length) actionNotice = "";
205
+ const canStop = action?.id === "stop-implement";
206
+ const nextEnabled = Boolean(action?.enabled) && !(actionBusy && !canStop && !review?.files?.length);
207
+ const nextLabel =
208
+ actionBusy && headerBusyLabel && !canStop && !review?.files?.length
209
+ ? headerBusyLabel
210
+ : action?.label ?? "Create a requirement";
211
+ paintActionButton(els.next, {
212
+ id: action?.id ?? "create",
213
+ label: nextLabel,
214
+ hint: review ? action?.hint || "" : actionNotice || action?.hint || "",
215
+ enabled: nextEnabled,
216
+ primary: true,
217
+ hidden: false,
218
+ });
219
+ setStageButtons(health, action?.id);
220
+
221
+ const gated = needsSetupGate(state);
222
+ els.stackGate?.classList.toggle("hidden", !gated);
223
+ els.cockpitApp?.classList.toggle("hidden", gated);
224
+ els.next.hidden = gated || onHome;
225
+ els.packHome?.classList.toggle("hidden", !onHome);
226
+ els.packWorkspace?.classList.toggle("hidden", onHome);
227
+ els.allRequirements?.classList.toggle("hidden", onHome);
228
+ els.createBar?.classList.toggle("hidden", !onHome);
229
+ if (!onHome) hidePackMenu();
230
+ if (els.hint) els.hint.hidden = true;
231
+ if (gated) {
232
+ renderSetupGate(state);
233
+ return;
234
+ }
235
+
236
+ renderPackList(packList);
237
+
238
+ if (onHome) return;
239
+
240
+ if (review && currentView !== "define") currentView = "define";
241
+ if (currentView === "implement" && health?.build?.owned === false) currentView = "define";
242
+
243
+ if (!applying && !state.improveReview) {
244
+ applying = true;
245
+ markdownEditor.setValue(state.markdown ?? "");
246
+ applying = false;
247
+ }
248
+
249
+ renderPipeline();
250
+ renderStageNav();
251
+ showView(currentView);
252
+ renderReview();
253
+ renderSpecPane();
254
+ renderJudgmentPane();
255
+ renderRunStatus();
256
+ renderProofReport();
257
+ renderActivity();
258
+ }
259
+
260
+ function renderPackList(items) {
261
+ if (!els.packList) return;
262
+ const signature = JSON.stringify(items);
263
+ els.packEmpty?.classList.toggle("hidden", items.length > 0);
264
+ if (els.packList.dataset.sig === signature) return;
265
+ hidePackMenu();
266
+ els.packList.dataset.sig = signature;
267
+ els.packList.innerHTML = "";
268
+ for (const item of items) {
269
+ const li = document.createElement("li");
270
+ const btn = document.createElement("button");
271
+ btn.type = "button";
272
+ btn.className = "pack-row";
273
+ btn.dataset.id = item.id;
274
+ const copy = document.createElement("span");
275
+ copy.className = "pack-row-copy";
276
+ const title = document.createElement("strong");
277
+ title.textContent = item.title || item.id;
278
+ const id = document.createElement("span");
279
+ id.className = "pack-row-id";
280
+ id.textContent = item.id;
281
+ copy.append(title, id);
282
+ const meters = document.createElement("span");
283
+ meters.className = "pack-row-meters";
284
+ for (const meter of item.meters ?? []) {
285
+ const chip = document.createElement("span");
286
+ chip.className = "pack-meter";
287
+ chip.dataset.tone = meter.tone ?? "idle";
288
+ const name = document.createElement("span");
289
+ name.className = "pack-meter-name";
290
+ name.textContent = meter.label;
291
+ chip.append(name, document.createTextNode(meter.badge ?? ""));
292
+ meters.append(chip);
293
+ }
294
+ btn.append(copy, meters);
295
+ btn.addEventListener("click", () => {
296
+ hidePackMenu();
297
+ void selectPack(item.id);
298
+ });
299
+ btn.addEventListener("contextmenu", (event) => {
300
+ event.preventDefault();
301
+ event.stopPropagation();
302
+ showPackMenu(event, item);
303
+ });
304
+ li.append(btn);
305
+ els.packList.append(li);
306
+ }
307
+ }
308
+
309
+ let pendingDelete = null;
310
+
311
+ function hidePackMenu() {
312
+ if (!els.packMenu) return;
313
+ els.packMenu.classList.add("hidden");
314
+ els.packMenu.hidden = true;
315
+ }
316
+
317
+ function showPackMenu(event, item) {
318
+ if (!els.packMenu) return;
319
+ pendingDelete = item;
320
+ els.packMenu.classList.remove("hidden");
321
+ els.packMenu.hidden = false;
322
+ els.packMenu.style.left = `${event.clientX}px`;
323
+ els.packMenu.style.top = `${event.clientY}px`;
324
+ const rect = els.packMenu.getBoundingClientRect();
325
+ const left = Math.min(event.clientX, window.innerWidth - rect.width - 8);
326
+ const top = Math.min(event.clientY, window.innerHeight - rect.height - 8);
327
+ els.packMenu.style.left = `${Math.max(8, left)}px`;
328
+ els.packMenu.style.top = `${Math.max(8, top)}px`;
329
+ els.packMenuDelete?.focus({ preventScroll: true });
330
+ }
331
+
332
+ function openDeleteDialog() {
333
+ hidePackMenu();
334
+ if (!pendingDelete || !els.deleteDialog) return;
335
+ const name = pendingDelete.title || pendingDelete.id;
336
+ if (els.deleteCopy) {
337
+ els.deleteCopy.textContent = `Delete “${name}”? The pack folder is removed from this repo.`;
338
+ }
339
+ els.deleteDialog.showModal();
340
+ }
341
+
342
+ let deletingPack = false;
343
+
344
+ async function confirmDeletePack() {
345
+ const item = pendingDelete;
346
+ if (!item?.id || deletingPack) return;
347
+ deletingPack = true;
348
+ if (els.deleteConfirm) els.deleteConfirm.disabled = true;
349
+ els.deleteDialog?.close();
350
+ try {
351
+ const res = await fetch("/api/delete", {
352
+ method: "POST",
353
+ headers: { "Content-Type": "application/json" },
354
+ body: JSON.stringify({ id: item.id }),
355
+ });
356
+ const body = await res.json();
357
+ if (!res.ok) {
358
+ if (els.createError) els.createError.textContent = body.error ?? "Could not delete that requirement.";
359
+ return;
360
+ }
361
+ pendingDelete = null;
362
+ takeState(body);
363
+ currentView = "define";
364
+ actionNotice = "";
365
+ render();
366
+ } finally {
367
+ deletingPack = false;
368
+ if (els.deleteConfirm) els.deleteConfirm.disabled = false;
369
+ }
370
+ }
371
+
372
+ async function selectPack(id) {
373
+ const res = await fetch("/api/select", {
374
+ method: "POST",
375
+ headers: { "Content-Type": "application/json" },
376
+ body: JSON.stringify({ id }),
377
+ });
378
+ const body = await res.json();
379
+ if (!res.ok) {
380
+ if (els.going) els.going.textContent = body.error ?? "Could not open that requirement.";
381
+ return;
382
+ }
383
+ takeState(body);
384
+ currentView = "define";
385
+ actionNotice = "";
386
+ render();
387
+ }
388
+
389
+ async function goHome() {
390
+ if (!state?.packId) return;
391
+ const res = await fetch("/api/home", { method: "POST" });
392
+ const body = await res.json();
393
+ if (!res.ok) {
394
+ if (els.going) els.going.textContent = body.error ?? "Could not return to the list.";
395
+ return;
396
+ }
397
+ takeState(body);
398
+ currentView = "define";
399
+ actionNotice = "";
400
+ render();
401
+ }
402
+
403
+ function renderReview() {
404
+ const review = state.improveReview;
405
+ const reviewing = Boolean(review);
406
+ const hasDiff = Boolean(review?.files?.length);
407
+ els.workspace?.classList.toggle("is-review", reviewing);
408
+ markdownEditor.setHidden(reviewing);
409
+ if (els.save) els.save.classList.toggle("hidden", reviewing);
410
+ if (!els.reviewActions || !els.reviewDiff) return;
411
+ els.reviewActions.classList.toggle("hidden", !reviewing);
412
+ els.reviewDiff.classList.toggle("hidden", !reviewing);
413
+ els.reviewDiff.hidden = !reviewing;
414
+ if (els.workspaceLabel) {
415
+ els.workspaceLabel.textContent = hasDiff ? "Improve patch" : reviewing ? "Waiting for the patch" : "requirement.md";
416
+ }
417
+ const lintOk = review?.lint?.ok !== false;
418
+ paintActionButton(els.reviewAccept, {
419
+ id: "review-improve",
420
+ label: "Accept",
421
+ hint: lintOk ? "Apply the Improve patch to requirement.md." : (review?.lint?.messages ?? []).join(" "),
422
+ enabled: hasDiff && lintOk && !actionBusy,
423
+ primary: true,
424
+ hidden: !reviewing,
425
+ });
426
+ paintActionButton(els.reviewReject, {
427
+ id: "reject-improve",
428
+ label: "Reject",
429
+ hint: "Restore the snapshot and discard the patch.",
430
+ enabled: reviewing && !actionBusy,
431
+ primary: false,
432
+ hidden: !reviewing,
433
+ });
434
+ if (!reviewing) {
435
+ els.reviewDiff.innerHTML = "";
436
+ return;
437
+ }
438
+ if (!hasDiff) {
439
+ els.reviewDiff.innerHTML = `<p class="review-waiting">The writer has the brief. This updates when requirement.md or fixtures/personas.yaml changes.</p>`;
440
+ return;
441
+ }
442
+ const lint = !lintOk
443
+ ? `<p class="review-waiting review-lint">${(review.lint.messages ?? [])
444
+ .map((message) => escapeHtml(message))
445
+ .join("<br />")}</p>`
446
+ : "";
447
+ els.reviewDiff.innerHTML = `${lint}${review.files.map(renderReviewFile).join("")}`;
448
+ }
449
+
450
+ function renderReviewFile(file) {
451
+ const hunks = (file.hunks ?? []).map(renderHunk).join("");
452
+ return `<article class="review-file">
453
+ <header class="review-file-head">
454
+ <span class="review-file-name">${escapeHtml(file.relative)}</span>
455
+ <span class="review-file-stat">${escapeHtml(file.status)} <span class="add">+${file.additions ?? 0}</span> <span class="del">−${file.deletions ?? 0}</span></span>
456
+ </header>
457
+ <table class="diff-table">${hunks}</table>
458
+ </article>`;
459
+ }
460
+
461
+ function renderHunk(hunk) {
462
+ const rows = (hunk.lines ?? [])
463
+ .map((line) => {
464
+ const kind = line.kind === "add" ? "diff-add" : line.kind === "del" ? "diff-del" : "";
465
+ const mark = line.kind === "add" ? "+" : line.kind === "del" ? "−" : " ";
466
+ return `<tr class="${kind}">
467
+ <td class="diff-gutter">${line.oldNo ?? ""}</td>
468
+ <td class="diff-gutter">${line.newNo ?? ""}</td>
469
+ <td class="diff-code">${escapeHtml(mark + line.text)}</td>
470
+ </tr>`;
471
+ })
472
+ .join("");
473
+ return `<tr class="diff-hunk"><td class="diff-gutter"></td><td class="diff-gutter"></td><td class="diff-code">${escapeHtml(hunk.header)}</td></tr>${rows}`;
474
+ }
475
+
476
+ function escapeHtml(value) {
477
+ return String(value ?? "").replace(/[&<>"']/g, (char) => ({
478
+ "&": "&amp;",
479
+ "<": "&lt;",
480
+ ">": "&gt;",
481
+ '"': "&quot;",
482
+ "'": "&#39;",
483
+ })[char]);
484
+ }
485
+
486
+ function iconSvg(paths) {
487
+ return `<svg viewBox="0 0 16 16" aria-hidden="true">${paths}</svg>`;
488
+ }
489
+
490
+ function actionGlyph(id, label = "") {
491
+ if (id === "create") {
492
+ return iconSvg(
493
+ `<path d="M8 3.2v9.6M3.2 8h9.6" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>`,
494
+ );
495
+ }
496
+ if (id === "fix-spec") {
497
+ return iconSvg(
498
+ `<path d="M3.2 12.8 6 12l6.4-6.4a1.6 1.6 0 0 0-2.2-2.2L3.8 9.8z" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/>`,
499
+ );
500
+ }
501
+ if (id === "check-jev") {
502
+ return iconSvg(
503
+ `<circle cx="7.2" cy="7.2" r="3.6" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="m9.8 9.8 3 3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>`,
504
+ );
505
+ }
506
+ if (id === "improve") {
507
+ return iconSvg(
508
+ `<path d="M8 2.6 9 6l3.4 1L9 8l-1 3.4L7 8 3.6 7 7 6zM12.4 10.2l.5 1.6 1.6.5-1.6.5-.5 1.6-.5-1.6-1.6-.5 1.6-.5z" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/>`,
509
+ );
510
+ }
511
+ if (id === "review-improve") {
512
+ return iconSvg(
513
+ `<path d="M2.8 8.2 6.1 11.4 13.2 4.4" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>`,
514
+ );
515
+ }
516
+ if (id === "reject-improve" || id === "stop-implement") {
517
+ return id === "stop-implement"
518
+ ? iconSvg(`<rect x="4.2" y="4.2" width="7.6" height="7.6" rx="1.2" fill="currentColor"/>`)
519
+ : iconSvg(
520
+ `<path d="M4 4l8 8M12 4l-8 8" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>`,
521
+ );
522
+ }
523
+ if (id === "implement") {
524
+ return /rebuild/i.test(label)
525
+ ? iconSvg(
526
+ `<path d="M12.6 8A4.6 4.6 0 1 1 10.2 4.1" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M10 2.6v2.6h2.6" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>`,
527
+ )
528
+ : iconSvg(
529
+ `<path d="M5.2 3.6v8.8L13 8z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/>`,
530
+ );
531
+ }
532
+ if (id === "ignore-build") {
533
+ return iconSvg(
534
+ `<path d="M3.2 4.4 8 8l-4.8 3.6zM8.8 4.4 13.6 8l-4.8 3.6z" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/>`,
535
+ );
536
+ }
537
+ if (id === "prove") {
538
+ return iconSvg(
539
+ `<path d="M5.2 2.8h5.6L9.2 8.2v4.2l-2.4 1V8.2z" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/>`,
540
+ );
541
+ }
542
+ if (id === "fix-from-proof") {
543
+ return iconSvg(
544
+ `<path d="M10.6 3.4a2.2 2.2 0 0 1 2 2.1c0 .6-.2 1.1-.6 1.5L7.4 11.6 4.4 12.6l1-3 4.6-4.6c.4-.4.9-.6 1.5-.6z" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/>`,
545
+ );
546
+ }
547
+ return iconSvg(
548
+ `<circle cx="8" cy="8" r="5.2" fill="none" stroke="currentColor" stroke-width="1.5"/>`,
549
+ );
550
+ }
551
+
552
+ function paintActionButton(btn, { id, label, hint, enabled, primary, hidden }) {
553
+ if (!btn) return;
554
+ btn.hidden = Boolean(hidden);
555
+ btn.classList.toggle("hidden", Boolean(hidden));
556
+ if (hidden) return;
557
+ btn.disabled = false;
558
+ btn.dataset.enabled = enabled ? "1" : "0";
559
+ btn.dataset.action = id ?? "";
560
+ if (hint) btn.dataset.hint = hint;
561
+ else delete btn.dataset.hint;
562
+ btn.removeAttribute("title");
563
+ btn.setAttribute("aria-disabled", enabled ? "false" : "true");
564
+ btn.setAttribute("aria-label", hint ? `${label}. ${hint}` : label);
565
+ btn.classList.toggle("is-disabled", !enabled);
566
+ btn.classList.toggle("cta-primary", Boolean(primary && enabled));
567
+ btn.classList.toggle("cta-danger", id === "reject-improve");
568
+ btn.innerHTML = `${actionGlyph(id, label)}<span>${escapeHtml(label)}</span>`;
569
+ }
570
+
571
+ function setActionHint(message) {
572
+ if (els.next) {
573
+ if (message) els.next.dataset.hint = message;
574
+ else delete els.next.dataset.hint;
575
+ }
576
+ }
577
+
578
+ function setMeter() {
579
+ renderPipeline();
580
+ }
581
+
582
+ function readyLabel(ready) {
583
+ if (!ready) return "Not yet";
584
+ const status = ready.state === "blocked" ? "Blocked" : ready.state === "ready" ? "Clear" : "Not yet";
585
+ if (ready.jevCurrent && typeof ready.packNoul === "number") {
586
+ return `${status} · ${Number(ready.packNoul).toFixed(2)}`;
587
+ }
588
+ return status;
589
+ }
590
+
591
+ function setStageButtons(health, primaryId) {
592
+ setStageButton(els.actionReady, health?.stages?.ready, primaryId);
593
+ setStageButton(els.actionBuild, health?.stages?.build, primaryId);
594
+ setStageButton(els.actionBuildIgnore, health?.stages?.ignoreBuild, primaryId);
595
+ setStageButton(els.actionBuildStop, health?.stages?.stopImplement, primaryId);
596
+ setStageButton(els.actionProof, health?.stages?.proof, primaryId);
597
+ setStageButton(els.actionFixProof, health?.stages?.fixFromProof, primaryId);
598
+ hideEmptyWorkspaceHeads();
599
+ }
600
+
601
+ function showView(view) {
602
+ currentView = view;
603
+ if (view === "spec" || view === "judgment") defineOpen = true;
604
+ const views = {
605
+ define: els.viewDefine,
606
+ spec: els.viewSpec,
607
+ judgment: els.viewJudgment,
608
+ implement: els.viewImplement,
609
+ qa: els.viewQa,
610
+ };
611
+ for (const [id, pane] of Object.entries(views)) {
612
+ if (!pane) continue;
613
+ const on = id === view;
614
+ pane.classList.toggle("hidden", !on);
615
+ pane.hidden = !on;
616
+ }
617
+ }
618
+
619
+ function renderPipeline() {
620
+ if (!els.graph) return;
621
+ const pipeline = state?.pipeline;
622
+ const nodes = (pipeline?.nodes ?? []).filter((node) => !node.hidden);
623
+ const signature = nodes
624
+ .map((node) => {
625
+ const kids = (node.id === "define" ? defineChildren(node) : [])
626
+ .map((child) => `${child.id}|${child.tone}|${child.badge ?? ""}|${currentView === child.view ? "1" : "0"}`)
627
+ .join(",");
628
+ return `${node.id}|${node.tone}|${node.badge ?? ""}|${currentView === node.view ? "1" : "0"}|${kids}`;
629
+ })
630
+ .join(";");
631
+ if (els.graph.dataset.sig === signature) {
632
+ paintPipelineRails();
633
+ return;
634
+ }
635
+ els.graph.dataset.sig = signature;
636
+ els.graph.innerHTML = "";
637
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
638
+ svg.classList.add("pipeline-svg");
639
+ svg.setAttribute("aria-hidden", "true");
640
+ els.graph.append(svg);
641
+ const trunk = document.createElement("div");
642
+ trunk.className = "pipeline-trunk";
643
+ nodes.forEach((node) => {
644
+ const col = document.createElement("div");
645
+ col.className = "pipeline-col";
646
+ col.dataset.id = node.id;
647
+ col.append(makeGraphNode(node, node.id === "start" || node.id === "end"));
648
+ const children = node.id === "define" ? defineChildren(node) : [];
649
+ if (children.length) {
650
+ col.classList.add("has-children");
651
+ const branch = document.createElement("div");
652
+ branch.className = "pipeline-branch";
653
+ for (const child of children) {
654
+ branch.append(makeGraphNode(child, false));
655
+ }
656
+ col.append(branch);
657
+ }
658
+ trunk.append(col);
659
+ });
660
+ els.graph.append(trunk);
661
+ requestAnimationFrame(paintPipelineRails);
662
+ }
663
+
664
+ function paintPipelineRails() {
665
+ const graph = els.graph;
666
+ if (!graph) return;
667
+ const svg = graph.querySelector(".pipeline-svg");
668
+ if (!svg) return;
669
+ const box = graph.getBoundingClientRect();
670
+ const width = Math.max(1, Math.round(graph.clientWidth));
671
+ const height = Math.max(1, Math.round(graph.clientHeight));
672
+ svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
673
+ svg.setAttribute("width", String(width));
674
+ svg.setAttribute("height", String(height));
675
+ const center = (el) => {
676
+ const r = el.getBoundingClientRect();
677
+ return {
678
+ x: r.left + r.width / 2 - box.left + graph.scrollLeft,
679
+ y: r.top + r.height / 2 - box.top + graph.scrollTop,
680
+ };
681
+ };
682
+ const trunkDots = [...graph.querySelectorAll(".pipeline-col > .pipeline-node .pipeline-node-dot")];
683
+ const lines = [];
684
+ if (trunkDots.length >= 2) {
685
+ const first = center(trunkDots[0]);
686
+ const last = center(trunkDots[trunkDots.length - 1]);
687
+ lines.push(`<line x1="${first.x}" y1="${first.y}" x2="${last.x}" y2="${last.y}" />`);
688
+ }
689
+ const defineDot = graph.querySelector('.pipeline-node[data-id="define"] .pipeline-node-dot');
690
+ const childDots = [...graph.querySelectorAll(".pipeline-branch .pipeline-node-dot")];
691
+ if (defineDot && childDots.length) {
692
+ const parent = center(defineDot);
693
+ for (const kid of childDots.map(center)) {
694
+ const midY = parent.y + (kid.y - parent.y) / 2;
695
+ lines.push(
696
+ `<path d="M ${parent.x} ${parent.y} C ${parent.x} ${midY}, ${kid.x} ${midY}, ${kid.x} ${kid.y}" />`,
697
+ );
698
+ }
699
+ }
700
+ svg.innerHTML = lines.join("");
701
+ }
702
+
703
+ function makeGraphNode(node, terminal) {
704
+ const btn = document.createElement("button");
705
+ btn.type = "button";
706
+ btn.className = `pipeline-node${terminal ? " is-terminal" : ""}`;
707
+ btn.dataset.tone = node.tone;
708
+ btn.dataset.view = node.view;
709
+ btn.dataset.id = node.id;
710
+ btn.classList.toggle("is-active", currentView === node.view && node.id !== "start" && node.id !== "end");
711
+ btn.title = node.badge ? `${node.label} — ${node.badge}` : node.label;
712
+ btn.innerHTML = `<span class="pipeline-node-label">${escapeHtml(node.label)}</span><span class="pipeline-node-dot">${toneGlyph(node.tone, node.mark)}</span>`;
713
+ btn.addEventListener("click", () => {
714
+ if (node.id === "start" && !state?.packId) {
715
+ els.createBar?.classList.remove("hidden");
716
+ els.newId?.focus();
717
+ return;
718
+ }
719
+ showView(node.view);
720
+ renderStageNav();
721
+ renderPipeline();
722
+ });
723
+ return btn;
724
+ }
725
+
726
+ function defineChildren(node) {
727
+ if (node?.children?.length) return node.children;
728
+ const specState = state?.health?.spec?.state ?? "empty";
729
+ const ready = state?.health?.ready;
730
+ const specTone =
731
+ specState === "empty" ? "idle" : specState === "drafting" ? "draft" : specState === "valid" ? "ok" : "draft";
732
+ const specBadge =
733
+ specState === "empty" ? "Empty" : specState === "drafting" ? "Drafting" : specState === "valid" ? "Valid" : specState;
734
+ const judgmentTone =
735
+ ready?.state === "blocked" ? "bad" : ready?.state === "ready" ? "ok" : specState === "valid" ? "draft" : "idle";
736
+ return [
737
+ { id: "spec", label: "Spec", view: "spec", tone: specTone, badge: specBadge },
738
+ {
739
+ id: "judgment",
740
+ label: "Judgment",
741
+ view: "judgment",
742
+ tone: judgmentTone,
743
+ badge: ready ? readyLabel(ready) : "Not yet",
744
+ mark: judgmentTone === "bad" ? "block" : undefined,
745
+ },
746
+ ];
747
+ }
748
+
749
+ function toneGlyph(tone, mark) {
750
+ if (tone === "ok") {
751
+ return `<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M2.4 6.3 4.9 8.7 9.6 3.3" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
752
+ }
753
+ if (tone === "bad" && mark === "block") {
754
+ return `<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M3 6h6" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>`;
755
+ }
756
+ if (tone === "bad") {
757
+ return `<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M3.2 3.2 8.8 8.8M8.8 3.2 3.2 8.8" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>`;
758
+ }
759
+ return "";
760
+ }
761
+
762
+ function renderStageNav() {
763
+ if (!els.stageNav) return;
764
+ const owned = state?.pipeline?.implementOwned !== false && state?.health?.build?.owned !== false;
765
+ const byId = Object.fromEntries((state?.pipeline?.nodes ?? []).map((node) => [node.id, node]));
766
+ const defineKids = defineChildren(byId.define);
767
+ const items = [
768
+ {
769
+ view: "define",
770
+ label: "Define",
771
+ child: false,
772
+ tone: byId.define?.tone ?? "idle",
773
+ badge: byId.define?.badge,
774
+ mark: byId.define?.mark,
775
+ },
776
+ ...defineKids.map((child) => ({
777
+ view: child.view,
778
+ label: child.label,
779
+ child: true,
780
+ tone: child.tone,
781
+ badge: child.badge,
782
+ mark: child.mark,
783
+ })),
784
+ ...(owned
785
+ ? [
786
+ {
787
+ view: "implement",
788
+ label: "Implement",
789
+ child: false,
790
+ tone: byId.implement?.tone ?? "idle",
791
+ badge: byId.implement?.badge,
792
+ mark: byId.implement?.mark,
793
+ },
794
+ ]
795
+ : []),
796
+ { view: "qa", label: "QA", child: false, tone: byId.qa?.tone ?? "idle", badge: byId.qa?.badge, mark: byId.qa?.mark },
797
+ ];
798
+ const signature = items
799
+ .map(
800
+ (item) =>
801
+ `${item.view}|${item.child ? "1" : "0"}|${item.tone}|${item.mark ?? ""}|${item.badge ?? ""}|${currentView === item.view ? "1" : "0"}`,
802
+ )
803
+ .join(";") + `|define:${defineOpen ? "1" : "0"}`;
804
+ if (els.stageNav.dataset.sig === signature) return;
805
+ els.stageNav.dataset.sig = signature;
806
+ els.stageNav.innerHTML = "";
807
+ for (const item of items) {
808
+ if (item.child && !defineOpen) continue;
809
+ const btn = document.createElement("button");
810
+ btn.type = "button";
811
+ btn.className = `nav-item${item.child ? " stage-nav-child" : ""}`;
812
+ btn.dataset.tone = item.tone;
813
+ btn.classList.toggle("active", currentView === item.view);
814
+ if (item.view === "define") {
815
+ btn.classList.toggle("is-open", defineOpen);
816
+ btn.setAttribute("aria-expanded", defineOpen ? "true" : "false");
817
+ }
818
+ btn.innerHTML = `<span class="nav-mark">${toneGlyph(item.tone, item.mark)}</span><span class="nav-name">${escapeHtml(item.label)}</span>${
819
+ item.badge ? `<span class="nav-badge">${escapeHtml(item.badge)}</span>` : ""
820
+ }${item.view === "define" ? `<span class="nav-chevron" aria-hidden="true"></span>` : ""}`;
821
+ btn.addEventListener("click", (event) => {
822
+ if (item.view === "define" && event.target.closest(".nav-chevron")) {
823
+ defineOpen = !defineOpen;
824
+ renderStageNav();
825
+ return;
826
+ }
827
+ if (item.view === "spec" || item.view === "judgment") defineOpen = true;
828
+ showView(item.view);
829
+ renderStageNav();
830
+ renderPipeline();
831
+ });
832
+ els.stageNav.append(btn);
833
+ }
834
+ }
835
+
836
+ function setStageButton(btn, action, primaryId) {
837
+ const keepEnabled = action?.id === "stop-implement";
838
+ paintActionButton(btn, {
839
+ id: action?.id,
840
+ label: action?.label ?? "",
841
+ hint: action?.hint ?? "",
842
+ enabled: Boolean(action?.enabled) && (!actionBusy || keepEnabled),
843
+ primary: Boolean(action?.enabled && action.id === primaryId),
844
+ hidden: !action || action.hidden,
845
+ });
846
+ }
847
+
848
+ function headingPresent(markdown, name) {
849
+ return new RegExp(`^##\\s+${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*$`, "m").test(markdown);
850
+ }
851
+
852
+ function statusIcon(name) {
853
+ if (name === "clock") {
854
+ return `<svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="8" r="5.4" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M8 5.2v3.1l2.1 1.3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>`;
855
+ }
856
+ if (name === "compile") {
857
+ return `<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4.2 2.6h5.2L12 5.2v8.2H4.2z" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/><path d="M9.2 2.6v2.8H12M6 8.2h4.2M6 10.6h3.2" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>`;
858
+ }
859
+ if (name === "list") {
860
+ return `<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M3.2 4.4h9.6M3.2 8h9.6M3.2 11.6h6.4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>`;
861
+ }
862
+ if (name === "monitor") {
863
+ return `<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="2.4" y="3.2" width="11.2" height="7.4" rx="1.2" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M6.2 13h3.6M8 10.6V13" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>`;
864
+ }
865
+ return `<svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="8" r="5.2" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>`;
866
+ }
867
+
868
+ function statusMark(tone, mark) {
869
+ const glyph = toneGlyph(tone, mark);
870
+ return glyph || `<svg viewBox="0 0 12 12" aria-hidden="true"><circle cx="6" cy="6" r="3.4" fill="none" stroke="currentColor" stroke-width="1.6"/></svg>`;
871
+ }
872
+
873
+ function renderStatusBar(el, { tone, title, items, mark }) {
874
+ if (!el) return;
875
+ const meta = items.filter((item) => item?.text);
876
+ const sig = `${tone}|${mark ?? ""}|${title}|${meta.map((item) => `${item.icon}:${item.text}`).join(";")}`;
877
+ if (el.dataset.sig === sig) return;
878
+ el.dataset.sig = sig;
879
+ el.dataset.tone = tone;
880
+ el.innerHTML = `<span class="status-bar-lead"><span class="status-bar-mark">${statusMark(tone, mark)}</span><span class="status-bar-title">${escapeHtml(
881
+ title,
882
+ )}</span></span><span class="status-bar-meta">${meta
883
+ .map(
884
+ (item) =>
885
+ `<span class="status-bar-item"><span class="status-bar-icon">${statusIcon(item.icon)}</span><span>${escapeHtml(
886
+ item.text,
887
+ )}</span></span>`,
888
+ )
889
+ .join("")}</span>`;
890
+ }
891
+
892
+ function hideEmptyWorkspaceHeads() {
893
+ for (const head of document.querySelectorAll(".workspace-head")) {
894
+ const actions = head.querySelector(".stage-actions");
895
+ if (!actions) continue;
896
+ const visible = [...actions.querySelectorAll("button")].some((btn) => !btn.hidden);
897
+ actions.classList.toggle("hidden", !visible);
898
+ if (!head.querySelector(".editor-label")) head.classList.toggle("hidden", !visible);
899
+ }
900
+ }
901
+
902
+ function renderSpecPane() {
903
+ if (!els.specSections) return;
904
+ const markdown = state?.markdown ?? markdownEditor.getValue();
905
+ const spec = state?.health?.spec;
906
+ const findings = spec?.findings ?? [];
907
+ const specState = spec?.state ?? "empty";
908
+ const label = specState === "valid" ? "Valid" : specState === "drafting" ? "Drafting" : "Empty";
909
+ const specTone =
910
+ specState === "valid" ? "ok" : findings.some((f) => f.severity === "error") ? "bad" : specState === "drafting" ? "draft" : "idle";
911
+ renderStatusBar(els.specStatus, {
912
+ tone: specTone,
913
+ title: "Spec",
914
+ items: [
915
+ { icon: "clock", text: label },
916
+ { icon: "compile", text: "compile" },
917
+ {
918
+ icon: "list",
919
+ text: findings.length
920
+ ? `${findings.length} finding${findings.length === 1 ? "" : "s"}`
921
+ : "No findings",
922
+ },
923
+ ],
924
+ });
925
+ const catalog = state?.sections ?? [];
926
+ els.specSections.innerHTML = "";
927
+ for (const section of catalog) {
928
+ const present = headingPresent(markdown, section.name);
929
+ const errored = findings.some((f) => f.message.includes(section.name));
930
+ const status = errored ? "error" : present ? "present" : "missing";
931
+ const li = document.createElement("li");
932
+ li.className = "list-row spec-section";
933
+ li.dataset.status = status;
934
+ li.innerHTML = `<div class="spec-section-head"><span class="spec-section-name">${escapeHtml(section.name)}</span><span class="spec-section-mark">${status}</span></div><p class="spec-section-purpose">${escapeHtml(section.purpose)}${section.required ? " Required." : " Optional."}</p>`;
935
+ li.addEventListener("click", () => {
936
+ focusedSection = section.name;
937
+ openDefine();
938
+ jumpToSection(section.name);
939
+ });
940
+ els.specSections.append(li);
941
+ }
942
+
943
+ if (!els.specFindings) return;
944
+ els.specFindings.innerHTML = "";
945
+ if (!findings.length) {
946
+ const li = document.createElement("li");
947
+ li.className = "list-row list-row-ok";
948
+ li.textContent = specState === "valid" ? "Grammar is valid." : "No compile findings.";
949
+ els.specFindings.append(li);
950
+ return;
951
+ }
952
+ for (const f of findings) {
953
+ const li = document.createElement("li");
954
+ li.className = "list-row list-row-bad";
955
+ li.textContent = f.line ? `L${f.line} ${f.message}` : f.message;
956
+ if (f.line) {
957
+ li.addEventListener("click", () => {
958
+ openDefine();
959
+ jumpToLine(f.line);
960
+ });
961
+ }
962
+ els.specFindings.append(li);
963
+ }
964
+ }
965
+
966
+ function renderJudgmentPane() {
967
+ const ready = state?.health?.ready;
968
+ const judgmentTone =
969
+ ready?.state === "blocked" ? "bad" : ready?.state === "ready" ? "ok" : state?.health?.spec?.state === "valid" ? "draft" : "idle";
970
+ const blockers = ready?.blockers ?? 0;
971
+ const nits = ready?.nits ?? 0;
972
+ renderStatusBar(els.judgmentBadge, {
973
+ tone: judgmentTone,
974
+ mark: judgmentTone === "bad" ? "block" : undefined,
975
+ title: "Judgment",
976
+ items: [
977
+ { icon: "clock", text: readyLabel(ready) },
978
+ ...(ready && (blockers || nits)
979
+ ? [{ icon: "list", text: `${blockers} blocker${blockers === 1 ? "" : "s"}, ${nits} nit${nits === 1 ? "" : "s"}` }]
980
+ : [{ icon: "list", text: ready?.state === "ready" ? "No findings" : "Not checked" }]),
981
+ ],
982
+ });
983
+ if (!els.judgmentFindings) return;
984
+ const findings = state?.health?.ready?.findings ?? [];
985
+ els.judgmentFindings.innerHTML = "";
986
+ if (!findings.length) {
987
+ const li = document.createElement("li");
988
+ li.className = "list-row list-row-ok";
989
+ li.textContent = state?.health?.ready?.state === "ready" ? "Clear. No Judgment findings." : "No Judgment findings yet. Check when Spec is valid.";
990
+ els.judgmentFindings.append(li);
991
+ return;
992
+ }
993
+ for (const f of findings) {
994
+ const li = document.createElement("li");
995
+ li.className = f.severity === "blocker" ? "list-row list-row-bad" : "list-row list-row-nit";
996
+ li.textContent = f.specId ? `${f.specId} — ${f.message}` : f.message;
997
+ li.addEventListener("click", () => {
998
+ openDefine();
999
+ if (f.line) jumpToLine(f.line);
1000
+ else jumpToSpecId(f.specId);
1001
+ });
1002
+ els.judgmentFindings.append(li);
1003
+ }
1004
+ }
1005
+
1006
+ function renderRunStatus() {
1007
+ const build = state?.health?.build;
1008
+ const buildLabel =
1009
+ build?.state === "running"
1010
+ ? "Implementing"
1011
+ : build?.state === "succeeded"
1012
+ ? "Succeeded"
1013
+ : build?.state === "failed"
1014
+ ? "Failed"
1015
+ : build?.state === "stale"
1016
+ ? "Stale"
1017
+ : "Not yet";
1018
+ const buildTone =
1019
+ build?.state === "succeeded"
1020
+ ? "ok"
1021
+ : build?.state === "failed"
1022
+ ? "bad"
1023
+ : build?.state === "running"
1024
+ ? "progress"
1025
+ : build?.state === "stale"
1026
+ ? "draft"
1027
+ : "idle";
1028
+ renderStatusBar(els.implementStatus, {
1029
+ tone: buildTone,
1030
+ mark: buildTone === "bad" ? "fail" : undefined,
1031
+ title: "Implement",
1032
+ items: [
1033
+ { icon: "clock", text: buildLabel },
1034
+ ...(build?.ignored ? [{ icon: "list", text: "Ignored" }] : []),
1035
+ ...(build?.adapter ? [{ icon: "monitor", text: adapterLabel(build.adapter) }] : []),
1036
+ ],
1037
+ });
1038
+
1039
+ const proof = state?.health?.proof;
1040
+ const proofLabel =
1041
+ proof?.state === "passed"
1042
+ ? "Passed"
1043
+ : proof?.state === "failed"
1044
+ ? "Failed"
1045
+ : proof?.state === "needs_review"
1046
+ ? "Needs review"
1047
+ : proof?.state === "stale"
1048
+ ? "Stale"
1049
+ : "Not yet";
1050
+ const proofTone =
1051
+ proof?.state === "passed"
1052
+ ? "ok"
1053
+ : proof?.state === "failed"
1054
+ ? "bad"
1055
+ : proof?.state === "needs_review" || proof?.state === "stale"
1056
+ ? "draft"
1057
+ : "idle";
1058
+ const counts = [];
1059
+ if (typeof proof?.passed === "number") counts.push(`${proof.passed} passed`);
1060
+ if (typeof proof?.failed === "number" && proof.failed) counts.push(`${proof.failed} failed`);
1061
+ if (typeof proof?.review === "number" && proof.review) counts.push(`${proof.review} review`);
1062
+ renderStatusBar(els.qaStatus, {
1063
+ tone: proofTone,
1064
+ mark: proofTone === "bad" ? "fail" : undefined,
1065
+ title: "QA",
1066
+ items: [
1067
+ { icon: "clock", text: proofLabel },
1068
+ { icon: "list", text: counts.length ? counts.join(", ") : proof?.runtime ? "runtime ready" : "No runtime" },
1069
+ ],
1070
+ });
1071
+ }
1072
+
1073
+ function renderProofReport() {
1074
+ if (!els.proofReport) return;
1075
+ const report = state?.proofReport?.trim();
1076
+ if (!report) {
1077
+ els.proofReport.className = "list-rows";
1078
+ els.proofReport.innerHTML = `<div class="list-row list-row-idle">No proof report yet. Prove writes derived/proof-report.md here.</div>`;
1079
+ return;
1080
+ }
1081
+ els.proofReport.className = "proof-report md-preview";
1082
+ els.proofReport.innerHTML = renderProofMarkdown(report);
1083
+ }
1084
+
1085
+ function renderProofMarkdown(source) {
1086
+ const blocks = [];
1087
+ let list = [];
1088
+ const flushList = () => {
1089
+ if (!list.length) return;
1090
+ blocks.push(`<ul>${list.map((item) => `<li>${inlineMd(item)}</li>`).join("")}</ul>`);
1091
+ list = [];
1092
+ };
1093
+ for (const raw of source.split("\n")) {
1094
+ const line = raw.trimEnd();
1095
+ if (/^###\s+/.test(line)) {
1096
+ flushList();
1097
+ blocks.push(`<h3>${inlineMd(line.replace(/^###\s+/, ""))}</h3>`);
1098
+ } else if (/^##\s+/.test(line)) {
1099
+ flushList();
1100
+ blocks.push(`<h2>${inlineMd(line.replace(/^##\s+/, ""))}</h2>`);
1101
+ } else if (/^#\s+/.test(line)) {
1102
+ flushList();
1103
+ blocks.push(`<h1>${inlineMd(line.replace(/^#\s+/, ""))}</h1>`);
1104
+ } else if (/^[-*]\s+/.test(line)) {
1105
+ list.push(line.replace(/^[-*]\s+/, ""));
1106
+ } else if (!line.trim()) {
1107
+ flushList();
1108
+ } else {
1109
+ flushList();
1110
+ blocks.push(`<p>${inlineMd(line)}</p>`);
1111
+ }
1112
+ }
1113
+ flushList();
1114
+ return blocks.join("");
1115
+ }
1116
+
1117
+ function inlineMd(value) {
1118
+ return escapeHtml(value).replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
1119
+ }
1120
+
1121
+ function openView(view) {
1122
+ showView(view);
1123
+ renderStageNav();
1124
+ renderPipeline();
1125
+ }
1126
+
1127
+ function openDefine() {
1128
+ openView("define");
1129
+ }
1130
+
1131
+ function jumpToSection(name) {
1132
+ const marker = `## ${name}`;
1133
+ const idx = markdownEditor.getValue().indexOf(marker);
1134
+ if (idx < 0) return;
1135
+ selectInEditor(idx, idx + marker.length);
1136
+ }
1137
+
1138
+ function jumpToSpecId(id) {
1139
+ if (!id) return false;
1140
+ for (const marker of [`Id: ${id}`, `## ${id}`, id]) {
1141
+ const idx = markdownEditor.getValue().indexOf(marker);
1142
+ if (idx < 0) continue;
1143
+ selectInEditor(idx, idx + marker.length);
1144
+ return true;
1145
+ }
1146
+ return false;
1147
+ }
1148
+
1149
+ function renderActivity() {
1150
+ const logs = [els.implementActivity, els.qaActivity].filter(Boolean);
1151
+ if (!logs.length) return;
1152
+ const lines = activityLines.length
1153
+ ? activityLines
1154
+ : [{ level: "info", message: "No activity yet. Implement and Prove write progress here." }];
1155
+ const key = lines.map((line) => `${line.level}\0${line.message}`).join("\n");
1156
+ if (key === lastActivityKey && logs.every((log) => log.childElementCount === lines.length)) return;
1157
+ lastActivityKey = key;
1158
+ for (const log of logs) {
1159
+ const pinned = log.scrollHeight - log.scrollTop - log.clientHeight < 16;
1160
+ const savedTop = log.scrollTop;
1161
+ log.innerHTML = "";
1162
+ for (const line of lines) {
1163
+ const li = document.createElement("li");
1164
+ const kind = line.level === "error" ? "bad" : line.level === "ok" ? "ok" : "idle";
1165
+ li.className = `list-row list-row-${kind}`;
1166
+ li.textContent = line.message;
1167
+ log.append(li);
1168
+ }
1169
+ log.scrollTop = pinned ? log.scrollHeight : savedTop;
1170
+ }
1171
+ }
1172
+
1173
+ function appendActivity(line) {
1174
+ activityLines = [...activityLines, line].slice(-80);
1175
+ if (line.message) {
1176
+ actionNotice = line.message;
1177
+ setActionHint(line.message);
1178
+ }
1179
+ renderActivity();
1180
+ }
1181
+
1182
+ function jumpToLine(line) {
1183
+ const lines = markdownEditor.getValue().split("\n");
1184
+ let start = 0;
1185
+ for (let i = 0; i < line - 1; i++) start += (lines[i]?.length ?? 0) + 1;
1186
+ const end = start + (lines[line - 1]?.length ?? 0);
1187
+ selectInEditor(start, end);
1188
+ }
1189
+
1190
+ function selectInEditor(start, end) {
1191
+ requestAnimationFrame(() => {
1192
+ markdownEditor.select(start, end);
1193
+ });
1194
+ }
1195
+
1196
+ async function saveMarkdown() {
1197
+ actionNotice = "";
1198
+ try {
1199
+ const res = await fetch("/api/requirement", {
1200
+ method: "PUT",
1201
+ headers: { "Content-Type": "application/json" },
1202
+ body: JSON.stringify({ markdown: markdownEditor.getValue() }),
1203
+ });
1204
+ state = await res.json();
1205
+ els.save.textContent = `Compiled · Spec ${state.health?.spec.state ?? ""}`;
1206
+ render();
1207
+ } catch {
1208
+ els.save.textContent = "Save failed";
1209
+ } finally {
1210
+ applying = false;
1211
+ }
1212
+ }
1213
+
1214
+ function onEnabledClick(btn, fn) {
1215
+ btn?.addEventListener("click", (event) => {
1216
+ if (btn.dataset.enabled === "0") {
1217
+ event.preventDefault();
1218
+ return;
1219
+ }
1220
+ fn();
1221
+ });
1222
+ }
1223
+
1224
+ onEnabledClick(els.reviewAccept, () => {
1225
+ void runNextAction("Accepting…", "/api/improve/accept");
1226
+ });
1227
+ onEnabledClick(els.reviewReject, () => {
1228
+ void runNextAction("Rejecting…", "/api/improve/reject");
1229
+ });
1230
+ onEnabledClick(els.next, () => {
1231
+ void runStageAction(state.health?.nextAction?.id);
1232
+ });
1233
+ onEnabledClick(els.actionReady, () => void runStageAction(els.actionReady.dataset.action));
1234
+ onEnabledClick(els.actionBuild, () => void runStageAction(els.actionBuild.dataset.action));
1235
+ onEnabledClick(els.actionBuildIgnore, () => void runStageAction(els.actionBuildIgnore.dataset.action));
1236
+ onEnabledClick(els.actionBuildStop, () => void runStageAction(els.actionBuildStop.dataset.action));
1237
+ onEnabledClick(els.actionProof, () => void runStageAction(els.actionProof.dataset.action));
1238
+ onEnabledClick(els.actionFixProof, () => void runStageAction(els.actionFixProof.dataset.action));
1239
+ els.ignoreYes?.addEventListener("click", () => closeIgnoreDialog("yes"));
1240
+ els.ignoreNo?.addEventListener("click", () => closeIgnoreDialog("no"));
1241
+ els.ignoreCancel?.addEventListener("click", () => closeIgnoreDialog("cancel"));
1242
+
1243
+ let ignoreDialogResolve = null;
1244
+
1245
+ function closeIgnoreDialog(value) {
1246
+ if (els.ignoreDialog?.open) els.ignoreDialog.close(value);
1247
+ }
1248
+
1249
+ function askIgnoreBuild() {
1250
+ if (!els.ignoreDialog) return Promise.resolve(null);
1251
+ return new Promise((resolve) => {
1252
+ ignoreDialogResolve = resolve;
1253
+ const onClose = () => {
1254
+ els.ignoreDialog.removeEventListener("close", onClose);
1255
+ const answer = els.ignoreDialog.returnValue;
1256
+ const done = ignoreDialogResolve;
1257
+ ignoreDialogResolve = null;
1258
+ done?.(answer === "yes" ? true : answer === "no" ? false : null);
1259
+ };
1260
+ els.ignoreDialog.addEventListener("close", onClose);
1261
+ els.ignoreDialog.returnValue = "";
1262
+ els.ignoreDialog.showModal();
1263
+ });
1264
+ }
1265
+
1266
+ function viewForAction(id) {
1267
+ if (id === "check-jev") return "judgment";
1268
+ if (id === "improve" || id === "review-improve" || id === "fix-spec" || id === "create") return "define";
1269
+ if (id === "implement" || id === "stop-implement" || id === "ignore-build" || id === "fix-from-proof") {
1270
+ return state?.health?.build?.owned === false ? null : "implement";
1271
+ }
1272
+ if (id === "prove") return "qa";
1273
+ return null;
1274
+ }
1275
+
1276
+ async function runStageAction(id) {
1277
+ actionNotice = "";
1278
+ const nextView = viewForAction(id);
1279
+ if (nextView) openView(nextView);
1280
+ if (id === "create") {
1281
+ if (!state.packId) {
1282
+ els.createBar.classList.remove("hidden");
1283
+ els.newId.focus();
1284
+ return;
1285
+ }
1286
+ const res = await fetch("/api/create-in-place", { method: "POST" });
1287
+ takeState(await res.json());
1288
+ focusedSection = "Business Rules";
1289
+ render();
1290
+ jumpToSection("Business Rules");
1291
+ return;
1292
+ }
1293
+ if (id === "fix-spec") {
1294
+ const first = state.health?.spec.findings?.[0];
1295
+ if (first) jumpToLine(first.line);
1296
+ return;
1297
+ }
1298
+ if (id === "improve") {
1299
+ activityLines = [{ level: "info", message: "Improve started." }];
1300
+ actionNotice = "Writing the improve brief…";
1301
+ setActionHint(actionNotice);
1302
+ renderActivity();
1303
+ await runBackgroundAction("Improving…", "/api/improve", { adapter: recordedAdapter() }, "improve");
1304
+ return;
1305
+ }
1306
+ if (id === "review-improve") {
1307
+ await runNextAction("Accepting…", "/api/improve/accept");
1308
+ return;
1309
+ }
1310
+ if (id === "check-jev") {
1311
+ await runNextAction("Checking…", "/api/check-jev");
1312
+ return;
1313
+ }
1314
+ if (id === "stop-implement") {
1315
+ actionNotice = "Stopping…";
1316
+ setActionHint(actionNotice);
1317
+ try {
1318
+ const res = await fetch("/api/stop-implement", {
1319
+ method: "POST",
1320
+ headers: { "Content-Type": "application/json" },
1321
+ body: "{}",
1322
+ });
1323
+ const payload = await res.json();
1324
+ if (payload.health || payload.packId) state = { ...state, ...payload };
1325
+ if (Array.isArray(payload.activity)) activityLines = payload.activity;
1326
+ actionNotice = payload.error ?? payload.message ?? "Owner stopped Implement.";
1327
+ } catch (err) {
1328
+ actionNotice = err instanceof Error ? err.message : "Stop failed.";
1329
+ }
1330
+ setActionHint(actionNotice);
1331
+ render();
1332
+ return;
1333
+ }
1334
+ if (id === "implement") {
1335
+ activityLines = [{ level: "info", message: "Implement started." }];
1336
+ actionNotice = "Implement started.";
1337
+ setMeter("build", "running");
1338
+ renderActivity();
1339
+ setActionHint(actionNotice);
1340
+ await runBackgroundAction("Implementing…", "/api/implement", { adapter: recordedAdapter() }, "implement");
1341
+ return;
1342
+ }
1343
+ if (id === "ignore-build") {
1344
+ const successful = await askIgnoreBuild();
1345
+ if (successful === null) return;
1346
+ actionNotice = "Ignoring failed Build…";
1347
+ setActionHint(actionNotice);
1348
+ const ignored = await runNextAction("Ignoring…", "/api/ignore-build", { successful });
1349
+ if (ignored === false) return;
1350
+ await runProveAction();
1351
+ return;
1352
+ }
1353
+ if (id === "fix-from-proof") {
1354
+ activityLines = [{ level: "info", message: "Fix from proof started." }];
1355
+ actionNotice = "Fix from proof started.";
1356
+ setMeter("build", "running");
1357
+ renderActivity();
1358
+ setActionHint(actionNotice);
1359
+ await runBackgroundAction(
1360
+ "Fixing from proof…",
1361
+ "/api/implement",
1362
+ { adapter: recordedAdapter(), fromProof: true },
1363
+ "implement",
1364
+ );
1365
+ return;
1366
+ }
1367
+ if (id === "prove") {
1368
+ activityLines = [{ level: "info", message: "Prove started." }];
1369
+ actionNotice = "Prove started.";
1370
+ setMeter("proof", "running");
1371
+ renderActivity();
1372
+ setActionHint(actionNotice);
1373
+ await runProveAction();
1374
+ }
1375
+ }
1376
+
1377
+ async function runProveAction() {
1378
+ actionBusy = true;
1379
+ headerBusyLabel = "Proving…";
1380
+ paintActionButton(els.next, {
1381
+ id: "prove",
1382
+ label: headerBusyLabel,
1383
+ hint: actionNotice,
1384
+ enabled: false,
1385
+ primary: true,
1386
+ });
1387
+ const poll = window.setInterval(() => {
1388
+ void refreshActivity();
1389
+ }, 750);
1390
+ try {
1391
+ const res = await fetch("/api/prove", {
1392
+ method: "POST",
1393
+ headers: { "Content-Type": "application/json" },
1394
+ body: "{}",
1395
+ });
1396
+ const payload = await res.json();
1397
+ if (Array.isArray(payload.activity) && payload.activity.length) {
1398
+ activityLines = payload.activity;
1399
+ renderActivity();
1400
+ }
1401
+ if (!res.ok && !payload.started) {
1402
+ actionNotice = payload.error ?? "Prove failed.";
1403
+ setActionHint(actionNotice);
1404
+ return;
1405
+ }
1406
+ await waitWhileBusy("prove");
1407
+ await load();
1408
+ } catch (err) {
1409
+ actionNotice = err instanceof Error ? err.message : "Failed to fetch";
1410
+ setActionHint(actionNotice);
1411
+ await refreshActivity();
1412
+ await waitWhileBusy("prove");
1413
+ await load();
1414
+ } finally {
1415
+ window.clearInterval(poll);
1416
+ actionBusy = false;
1417
+ render();
1418
+ }
1419
+ }
1420
+
1421
+ async function waitWhileBusy(kind) {
1422
+ const deadline = Date.now() + 10 * 60 * 1000;
1423
+ while (Date.now() < deadline) {
1424
+ try {
1425
+ const res = await fetch("/api/state");
1426
+ const data = await res.json();
1427
+ if (data.health || data.packId || data.improveReview) state = { ...state, ...data };
1428
+ if (Array.isArray(data.activity)) activityLines = data.activity;
1429
+ if (data.improveReview?.files?.length) {
1430
+ actionNotice = "";
1431
+ render();
1432
+ return;
1433
+ }
1434
+ const last = activityLines[activityLines.length - 1];
1435
+ if (last?.message && !data.improveReview) {
1436
+ actionNotice = last.message;
1437
+ setActionHint(last.message);
1438
+ }
1439
+ render();
1440
+ if (data.busy !== kind) return;
1441
+ } catch {
1442
+ // keep polling through a brief disconnect
1443
+ }
1444
+ await new Promise((resolve) => setTimeout(resolve, 750));
1445
+ }
1446
+ }
1447
+
1448
+ async function refreshActivity() {
1449
+ try {
1450
+ const res = await fetch("/api/state");
1451
+ const data = await res.json();
1452
+ if (data.health || data.packId || data.improveReview) state = { ...state, ...data };
1453
+ if (Array.isArray(data.activity)) activityLines = data.activity;
1454
+ if (data.improveReview?.files?.length) actionNotice = "";
1455
+ else {
1456
+ const last = activityLines[activityLines.length - 1];
1457
+ if (last?.message) {
1458
+ actionNotice = last.message;
1459
+ setActionHint(last.message);
1460
+ }
1461
+ }
1462
+ render();
1463
+ } catch {
1464
+ // keep the last lines if the poll loses a race with Prove
1465
+ }
1466
+ }
1467
+
1468
+ async function runBackgroundAction(busyLabel, url, body, kind) {
1469
+ actionBusy = true;
1470
+ headerBusyLabel = busyLabel;
1471
+ paintActionButton(els.next, {
1472
+ id: state.health?.nextAction?.id,
1473
+ label: busyLabel,
1474
+ hint: actionNotice,
1475
+ enabled: false,
1476
+ primary: true,
1477
+ });
1478
+ setStageButtons(state.health, state.health?.nextAction?.id);
1479
+ const poll = window.setInterval(() => {
1480
+ void refreshActivity();
1481
+ }, 750);
1482
+ try {
1483
+ const res = await fetch(url, {
1484
+ method: "POST",
1485
+ headers: { "Content-Type": "application/json" },
1486
+ body: JSON.stringify(body ?? {}),
1487
+ });
1488
+ const payload = await res.json();
1489
+ if (payload.health || payload.packId) state = { ...state, ...payload };
1490
+ if (Array.isArray(payload.activity) && payload.activity.length) {
1491
+ activityLines = payload.activity;
1492
+ renderActivity();
1493
+ }
1494
+ if (!res.ok && !payload.started) {
1495
+ actionNotice = payload.error ?? "Request failed.";
1496
+ setActionHint(actionNotice);
1497
+ return;
1498
+ }
1499
+ if (payload.message) {
1500
+ actionNotice = payload.message;
1501
+ setActionHint(actionNotice);
1502
+ }
1503
+ if (payload.started || payload.busy === kind) {
1504
+ await waitWhileBusy(kind);
1505
+ await load();
1506
+ }
1507
+ } catch (err) {
1508
+ actionNotice = err instanceof Error ? err.message : "Request failed.";
1509
+ setActionHint(actionNotice);
1510
+ await refreshActivity();
1511
+ await waitWhileBusy(kind);
1512
+ await load();
1513
+ } finally {
1514
+ window.clearInterval(poll);
1515
+ actionBusy = false;
1516
+ render();
1517
+ }
1518
+ }
1519
+
1520
+ async function runNextAction(busyLabel, url, body) {
1521
+ actionBusy = true;
1522
+ headerBusyLabel = busyLabel;
1523
+ paintActionButton(els.next, {
1524
+ id: state.health?.nextAction?.id,
1525
+ label: busyLabel,
1526
+ hint: actionNotice,
1527
+ enabled: false,
1528
+ primary: true,
1529
+ });
1530
+ setStageButtons(state.health, state.health?.nextAction?.id);
1531
+ try {
1532
+ const res = await fetch(url, {
1533
+ method: "POST",
1534
+ headers: { "Content-Type": "application/json" },
1535
+ body: JSON.stringify(body ?? {}),
1536
+ });
1537
+ const payload = await res.json();
1538
+ if (payload.health || payload.packId) state = { ...state, ...payload };
1539
+ if (Array.isArray(payload.activity)) activityLines = payload.activity;
1540
+ if (!res.ok || payload.error) {
1541
+ actionNotice = payload.error ?? "Request failed.";
1542
+ actionBusy = false;
1543
+ render();
1544
+ return false;
1545
+ }
1546
+ if (payload.message) actionNotice = payload.message;
1547
+ actionBusy = false;
1548
+ render();
1549
+ return true;
1550
+ } catch (err) {
1551
+ actionNotice = err instanceof Error ? err.message : "Request failed.";
1552
+ actionBusy = false;
1553
+ render();
1554
+ return false;
1555
+ }
1556
+ }
1557
+
1558
+ async function recordSetup(body) {
1559
+ if (els.stackError) els.stackError.textContent = "";
1560
+ for (const btn of [els.codingManual, els.codingCursor, els.codingCopilot, els.stackNextjs, els.stackAmplify]) {
1561
+ if (btn) btn.disabled = true;
1562
+ }
1563
+ const res = await fetch("/api/setup", {
1564
+ method: "POST",
1565
+ headers: { "Content-Type": "application/json" },
1566
+ body: JSON.stringify(body),
1567
+ });
1568
+ const payload = await res.json();
1569
+ if (!res.ok) {
1570
+ for (const btn of [els.codingManual, els.codingCursor, els.codingCopilot, els.stackNextjs, els.stackAmplify]) {
1571
+ if (btn) btn.disabled = false;
1572
+ }
1573
+ if (els.stackError) els.stackError.textContent = payload.error ?? "Could not record setup.";
1574
+ return;
1575
+ }
1576
+ pendingCoding = null;
1577
+ state = payload;
1578
+ actionNotice = "";
1579
+ render();
1580
+ }
1581
+
1582
+ async function onCodingChoice(coding) {
1583
+ const repo = state?.productRepo;
1584
+ const needStack = Boolean(repo?.implement && repo?.empty && !repo?.recorded);
1585
+ if (coding === "manual") {
1586
+ pendingCoding = null;
1587
+ await recordSetup({ coding: "manual" });
1588
+ return;
1589
+ }
1590
+ if (needStack) {
1591
+ pendingCoding = coding;
1592
+ renderSetupGate(state);
1593
+ return;
1594
+ }
1595
+ await recordSetup({ coding });
1596
+ }
1597
+
1598
+ async function recordStack(id) {
1599
+ if (els.stackError) els.stackError.textContent = "";
1600
+ const repo = state?.productRepo;
1601
+ const needCoding = Boolean(repo?.implement && repo?.adapterRecorded === false);
1602
+ if (needCoding || pendingCoding) {
1603
+ const coding = pendingCoding ?? "cursor";
1604
+ await recordSetup({ coding, stack: id });
1605
+ return;
1606
+ }
1607
+ if (els.stackNextjs) els.stackNextjs.disabled = true;
1608
+ if (els.stackAmplify) els.stackAmplify.disabled = true;
1609
+ const res = await fetch("/api/stack", {
1610
+ method: "POST",
1611
+ headers: { "Content-Type": "application/json" },
1612
+ body: JSON.stringify({ id }),
1613
+ });
1614
+ const body = await res.json();
1615
+ if (!res.ok) {
1616
+ if (els.stackNextjs) els.stackNextjs.disabled = false;
1617
+ if (els.stackAmplify) els.stackAmplify.disabled = false;
1618
+ if (els.stackError) els.stackError.textContent = body.error ?? "Could not record stack.";
1619
+ return;
1620
+ }
1621
+ state = body;
1622
+ actionNotice = "";
1623
+ render();
1624
+ }
1625
+
1626
+ els.codingManual?.addEventListener("click", () => void onCodingChoice("manual"));
1627
+ els.codingCursor?.addEventListener("click", () => void onCodingChoice("cursor"));
1628
+ els.codingCopilot?.addEventListener("click", () => void onCodingChoice("copilot"));
1629
+ els.stackNextjs?.addEventListener("click", () => void recordStack("nextjs-default"));
1630
+ els.stackAmplify?.addEventListener("click", () => void recordStack("amplify-gen2"));
1631
+
1632
+ els.homeBtn?.addEventListener("click", () => void goHome());
1633
+ els.allRequirements?.addEventListener("click", () => void goHome());
1634
+ els.packMenu?.addEventListener("contextmenu", (event) => event.preventDefault());
1635
+ els.packMenuDelete?.addEventListener("click", () => openDeleteDialog());
1636
+ els.deleteCancel?.addEventListener("click", () => els.deleteDialog?.close());
1637
+ els.deleteConfirm?.addEventListener("click", () => void confirmDeletePack());
1638
+ els.deleteDialog?.addEventListener("cancel", () => els.deleteDialog?.close());
1639
+ document.addEventListener("pointerdown", (event) => {
1640
+ if (els.packMenu?.contains(event.target)) return;
1641
+ if (event.button === 2) return;
1642
+ hidePackMenu();
1643
+ });
1644
+ document.addEventListener("contextmenu", (event) => {
1645
+ if (els.packMenu?.contains(event.target)) return;
1646
+ if (event.target instanceof Element && event.target.closest(".pack-row")) return;
1647
+ hidePackMenu();
1648
+ });
1649
+ document.addEventListener("keydown", (event) => {
1650
+ if (event.key === "Escape") hidePackMenu();
1651
+ });
1652
+ window.addEventListener("resize", hidePackMenu);
1653
+ window.addEventListener("scroll", hidePackMenu);
1654
+
1655
+ els.createNew.addEventListener("click", async () => {
1656
+ els.createError.textContent = "";
1657
+ const res = await fetch("/api/create", {
1658
+ method: "POST",
1659
+ headers: { "Content-Type": "application/json" },
1660
+ body: JSON.stringify({ id: els.newId.value.trim() }),
1661
+ });
1662
+ const body = await res.json();
1663
+ if (!res.ok) {
1664
+ els.createError.textContent = body.error ?? "Could not create.";
1665
+ return;
1666
+ }
1667
+ takeState(body);
1668
+ currentView = "define";
1669
+ actionNotice = "";
1670
+ if (els.newId) els.newId.value = "";
1671
+ render();
1672
+ jumpToSection("Business Rules");
1673
+ });
1674
+
1675
+ let pollTimer = null;
1676
+
1677
+ function startPolling() {
1678
+ stopPolling();
1679
+ // Poll /api/state. Never EventSource — a hanging stream pins browser refresh.
1680
+ pollTimer = window.setInterval(() => {
1681
+ if (document.visibilityState !== "visible") return;
1682
+ if (applying || actionBusy) return;
1683
+ void load();
1684
+ }, 2000);
1685
+ }
1686
+
1687
+ function stopPolling() {
1688
+ if (pollTimer !== null) window.clearInterval(pollTimer);
1689
+ pollTimer = null;
1690
+ }
1691
+
1692
+ document.addEventListener("visibilitychange", () => {
1693
+ if (document.visibilityState === "hidden") stopPolling();
1694
+ else {
1695
+ startPolling();
1696
+ void load();
1697
+ }
1698
+ });
1699
+ window.addEventListener("pagehide", stopPolling);
1700
+ window.addEventListener("beforeunload", stopPolling);
1701
+
1702
+ if (els.graph) {
1703
+ const redraw = () => paintPipelineRails();
1704
+ new ResizeObserver(redraw).observe(els.graph);
1705
+ window.addEventListener("resize", redraw);
1706
+ }
1707
+
1708
+ void load().finally(() => {
1709
+ if (document.visibilityState === "visible") startPolling();
1710
+ });