-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3941 lines (3843 loc) · 177 KB
/
Copy pathapp.js
File metadata and controls
3941 lines (3843 loc) · 177 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { renderNeutralImportReview } from "./neutralImportReview.js";
import { renderNativeTasksPage } from "./nativeTasks.js";
import { apiGet, apiPost, getAdminToken, getCurrentUser, login, logout, setAdminToken, whoami } from "./api.js";
import { renderBars, renderLine } from "./charts.js";
import { renderQrLike } from "./qr.js";
import { renderPluginTable } from "./components/pluginTable.js";
import { renderPluginDetail } from "./components/pluginDetail.js";
import { renderRegistryManager } from "./components/registryManager.js";
import { renderPluginDiff } from "./components/pluginDiff.js";
import { renderTrustPage } from "./trust.js";
import { renderForecastScopePage } from "./forecast.js";
import { renderAdvisoriesPage } from "./advisories.js";
import { renderPortfolioForecastPage } from "./portfolioForecast.js";
import { renderCompassPage } from "./compass.js";
import { renderContextGraphPage } from "./contextGraph.js";
import { renderDiagnosticViewPage } from "./diagnosticView.js";
import { renderEvidenceDrilldownPage } from "./evidenceDrilldown.js";
import { renderNorthstarPage } from "./northstar.js";
import { renderAssurancePage } from "./assurance.js";
import { renderAssuranceRunPage } from "./assuranceRun.js";
import { renderAssuranceCertPage } from "./assuranceCert.js";
import { renderAuditPage } from "./audit.js";
import { renderAuditBinderPage } from "./auditBinder.js";
import { renderAuditRequestsPage } from "./auditRequests.js";
import { renderValuePage } from "./value.js";
import { renderValueAgentPage } from "./valueAgent.js";
import { renderValueKpisPage } from "./valueKpis.js";
import { renderPassportPage } from "./passport.js";
import { renderStandardPage } from "./standard.js";
const page = document.body.dataset.page || "home";
const root = document.getElementById("app");
const statusEl = document.getElementById("status");
const bannerEl = document.getElementById("ucBanner");
const OFFLINE_BANNER_ID = "offlineBanner";
const approvalActivityState = {
query: "",
status: "PENDING",
actionClass: "",
riskTier: "",
effectiveMode: "",
createdAfter: "",
createdBefore: "",
order: "newest",
limit: "50"
};
function workspacePrefixFromPath() {
const path = window.location.pathname || "/";
const match = path.match(/^\/w\/([^/]+)/);
if (!match) {
return "";
}
return `/w/${match[1]}`;
}
function consoleBasePath() {
return `${workspacePrefixFromPath()}/console`;
}
function withConsolePath(path) {
const suffix = path.startsWith("/") ? path : `/${path}`;
return `${consoleBasePath()}${suffix}`;
}
function orgEventsPath() {
const prefix = workspacePrefixFromPath();
return prefix ? `${prefix}/events/org` : "/events/org";
}
function qs(name) {
const url = new URL(window.location.href);
return url.searchParams.get(name);
}
function currentAgent() {
return qs("agent") || "default";
}
function setStatus(text, bad = false) {
if (!statusEl) {
return;
}
statusEl.textContent = text;
statusEl.className = bad ? "status-bad" : "status-ok";
}
function errText(error) {
if (!error) {
return "Unknown error";
}
return typeof error.message === "string" ? error.message : String(error);
}
function apiPayload(envelope) {
return envelope && envelope.ok === true && Object.prototype.hasOwnProperty.call(envelope, "data")
? envelope.data
: envelope;
}
function htmlEscape(text) {
return String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function card(title, body) {
return `<section class="card"><h3>${htmlEscape(title)}</h3>${body}</section>`;
}
function firstUseCard(agentId) {
// This is a POSIX terminal handoff, never a browser execution request.
const quotedAgent = `'${String(agentId).replaceAll("'", "'\\''")}'`;
const connectCommand = `amc connect --agent=${quotedAgent}`;
const guideCommand = `amc --agent=${quotedAgent} agent-loop guide`;
return `
<section id="firstUse" class="card first-use" aria-labelledby="firstUseTitle">
<div class="studio-kicker">Start here</div>
<h2 id="firstUseTitle">What would you like to do?</h2>
<div class="first-use-intents">
<button id="firstUseNativeButton" data-first-intent="firstUseNative" aria-controls="firstUseNative" aria-expanded="false">
<strong>Run a task with AMC</strong><span>Choose a model task or a local recording demonstration.</span>
</button>
<button id="firstUseBaselineButton" data-first-intent="firstUseBaseline" aria-controls="firstUseBaseline" aria-expanded="false">
<strong>Assess existing evidence</strong><span>Create a baseline and see what evidence is missing.</span>
</button>
<button id="firstUseConnectButton" data-first-intent="firstUseConnect" aria-controls="firstUseConnect" aria-expanded="false">
<strong>Connect an existing agent</strong><span>Bring an agent's actions into AMC's evidence trail.</span>
</button>
</div>
<div id="firstUseNative" class="first-use-panel" hidden>
<h3>Run a native task in Studio</h3>
<p>Choose a provider, inspect the existing tool scope, and follow recorded activity for <strong>${htmlEscape(agentId)}</strong>.</p>
<a class="button" href="./native-tasks?agent=${encodeURIComponent(agentId)}">Open Native Tasks</a>
<p class="muted">Prefer your terminal? Run this guide on the machine hosting this workspace. Copying the command makes no changes.</p>
<pre><code id="nativeGuideCommand" tabindex="0">${htmlEscape(guideCommand)}</code></pre>
<button id="copyNativeGuide" class="secondary">Copy guide command</button>
<span id="nativeCopyStatus" class="muted first-use-copy-status" role="status" aria-live="polite"></span>
</div>
<div id="firstUseBaseline" class="first-use-panel" hidden>
<h3>Start an evidence baseline</h3>
<p>A baseline reports current evidence and gaps. It does not complete a model task or prove that an agent is connected.</p>
<button id="firstUseBaselineContinue" class="secondary">Open baseline setup</button>
</div>
<div id="firstUseConnect" class="first-use-panel" hidden>
<h3>Connect from your workspace terminal</h3>
<p>Run this on the machine hosting this workspace to configure a connection for <strong>${htmlEscape(agentId)}</strong>. The CLI may create a connection lease; copying the command makes no changes.</p>
<pre><code id="connectCommand" tabindex="0">${htmlEscape(connectCommand)}</code></pre>
<button id="copyConnectCommand" class="secondary">Copy connection command</button>
<span id="connectCopyStatus" class="muted first-use-copy-status" role="status" aria-live="polite"></span>
<p class="muted">Commands use macOS/Linux shell syntax. Check the Activation path below after your agent runs; setup alone does not complete it.</p>
</div>
</section>
`;
}
function bindFirstUse() {
const firstUse = document.getElementById("firstUse");
if (!firstUse) return;
firstUse.querySelectorAll("[data-first-intent]").forEach((button) => {
button.addEventListener("click", () => {
firstUse.querySelectorAll("[data-first-intent]").forEach((item) => {
const selected = item === button;
item.setAttribute("aria-expanded", String(selected));
document.getElementById(item.dataset.firstIntent).hidden = !selected;
});
});
});
const bindCopy = (buttonId, commandId, statusId) => {
document.getElementById(buttonId)?.addEventListener("click", async () => {
const command = document.getElementById(commandId);
const status = document.getElementById(statusId);
try {
await navigator.clipboard.writeText(command.textContent);
status.textContent = "Copied. Run it in your workspace terminal.";
} catch {
status.textContent = "Copy unavailable. Select and copy the command above.";
command.focus();
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(command);
selection?.removeAllRanges();
selection?.addRange(range);
}
});
};
bindCopy("copyNativeGuide", "nativeGuideCommand", "nativeCopyStatus");
bindCopy("copyConnectCommand", "connectCommand", "connectCopyStatus");
document.getElementById("firstUseBaselineContinue")?.addEventListener("click", () => {
const button = document.getElementById("studioRunOnboarding");
const setup = button?.closest("details");
if (setup) setup.open = true;
button?.scrollIntoView({ block: "center" });
button?.focus({ preventScroll: true });
});
}
function renderToolContext(projection) {
const integrity = projection?.integrity?.status === "trusted" ? "trusted" : "untrusted";
const groups = Array.isArray(projection?.groups) ? projection.groups : [];
const reasonCodes = Array.isArray(projection?.integrity?.reasonCodes)
? projection.integrity.reasonCodes
: [];
const body = integrity === "trusted"
? groups.map((group) => {
const server = group?.server;
const heading = group?.kind === "native"
? "Native tools"
: `${server?.name || group?.label || "MCP server"} · ${server?.id || "unknown"}`;
const context = server
? [server.version ? `v${server.version}` : "", server.transport || ""].filter(Boolean).join(" · ")
: "local provider";
const rows = (Array.isArray(group?.tools) ? group.tools : []).map((tool) => `
<tr>
<td><code>${htmlEscape(tool.name || "unknown")}</code></td>
<td>${htmlEscape(tool.actionClass || "unknown")}</td>
<td>${tool.requireExecTicket ? "Required" : "No"}</td>
<td><code title="${htmlEscape(tool.toolIdentity || "")}">${htmlEscape(String(tool.toolIdentity || "").slice(0, 24))}</code></td>
</tr>
`).join("");
return `
<div class="tool-context-group">
<div class="row"><strong>${htmlEscape(heading)}</strong><span class="muted">${htmlEscape(context)}</span></div>
<div class="table-wrap"><table>
<thead><tr><th>Tool</th><th>Action class</th><th>Exec ticket</th><th>Identity</th></tr></thead>
<tbody>${rows}</tbody>
</table></div>
</div>
`;
}).join("")
: `<p class="status-bad">Tool context unavailable: ${htmlEscape(reasonCodes.join(", ") || "integrity check failed")}</p>`;
return `
<div class="row"><span class="pill ${integrity === "trusted" ? "ok" : "bad"}">${htmlEscape(integrity)}</span><span class="muted">${Number(projection?.total || 0)} tools</span></div>
${body || '<p class="muted">No signed tools declared.</p>'}
<p class="muted">${htmlEscape(projection?.claimBoundary || "Declared ToolHub context only.")}</p>
`;
}
function currentWorkspaceLabel() {
const prefix = workspacePrefixFromPath();
if (!prefix) {
return "local";
}
return decodeURIComponent(prefix.replace(/^\/w\//, ""));
}
function decorateShell() {
const nav = document.querySelector("nav");
if (nav && !nav.querySelector(".mobile-nav-toggle")) {
nav.id = nav.id || "amc-main-navigation";
const toggle = document.createElement("button");
toggle.type = "button";
toggle.className = "mobile-nav-toggle";
toggle.setAttribute("aria-label", "Toggle navigation");
toggle.setAttribute("aria-controls", nav.id);
toggle.setAttribute("aria-expanded", "false");
toggle.title = "Toggle navigation";
toggle.innerHTML = '<span class="mobile-nav-icon" aria-hidden="true"></span>';
toggle.addEventListener("click", () => {
const open = nav.classList.toggle("mobile-nav-open");
toggle.setAttribute("aria-expanded", String(open));
});
nav.insertBefore(toggle, nav.querySelector("a"));
}
document.querySelectorAll("nav a").forEach((anchor) => {
const href = anchor.getAttribute("href") || "";
const normalizedHref = href.replace(/^\.\//, "").replace(/\.html$/, "");
anchor.classList.toggle("active", normalizedHref === page);
});
const main = document.querySelector("main");
if (!main || main.querySelector(".topbar")) {
return;
}
const workspace = currentWorkspaceLabel();
const demoMode = workspace === "demo";
const topbar = document.createElement("section");
topbar.className = "topbar";
topbar.innerHTML = `
<div>
<div class="topbar-kicker">Agent Maturity Compass</div>
<strong>Compass Console</strong>
<span class="muted">/ ${htmlEscape(workspace)} workspace</span>
</div>
<div class="topbar-actions">
${demoMode ? '<span class="pill ok">local demo session</span>' : '<span class="pill muted">session protected</span>'}
<a class="button secondary" href="./evidence">Evidence</a>
<a class="button secondary" href="./standard">Open Standard</a>
</div>
`;
main.insertBefore(topbar, main.firstChild);
}
const FALLBACK_SURFACES = [
{
surface: "Score",
headline: "Score trust before you ship",
description: "Evidence-weighted scoring across live execution behavior instead of brochure claims."
},
{
surface: "Shield",
headline: "Attack your agent before attackers do",
description: "Runs adversarial packs against prompt injection, leakage, memory poisoning, and sycophancy."
},
{
surface: "Enforce",
headline: "Wrap agent actions in policy",
description: "Approval gates, scoped permissions, and runtime controls for sensitive operations."
},
{
surface: "Vault",
headline: "Cryptographically prove what happened",
description: "Signs evidence, verifies ledgers, and gives auditors a tamper-evident chain of custody."
},
{
surface: "Watch",
headline: "See trust drift before it hurts you",
description: "Monitors posture over time and surfaces anomalies, regressions, and risky changes."
},
{
surface: "Comply",
headline: "Map trust evidence to real frameworks",
description: "Turns technical evidence into regulator-readable artifacts for audits and risk reviews."
},
{
surface: "Fleet",
headline: "Govern many agents like an actual platform",
description: "Benchmarks multiple agents, compares risk posture, and enforces org-wide trust baselines."
},
{
surface: "Passport",
headline: "Make trust portable between environments",
description: "Issues a portable, signed trust identity that can move between tools, teams, and environments."
}
];
function shortId(value, max = 14) {
const text = String(value || "");
if (text.length <= max) {
return text || "-";
}
return `${text.slice(0, Math.max(4, max - 7))}...${text.slice(-4)}`;
}
function formatTime(value) {
if (!value) {
return "-";
}
const time = new Date(value);
if (Number.isNaN(time.getTime())) {
return String(value);
}
return time.toLocaleString();
}
function statusPill(status) {
const normalized = String(status || "UNKNOWN").toUpperCase();
const className = ["COMPLETE", "VALID", "PASS", "OK", "HIGH TRUST"].includes(normalized)
? "status-ok"
: ["DEGRADED", "FAILED", "FAIL", "INVALID", "MISSING"].includes(normalized)
? "status-bad"
: "muted";
return `<span class="pill ${className}">${htmlEscape(normalized)}</span>`;
}
function renderSurfaceRail(surfaceResp, latestRun) {
const definitions = Array.isArray(surfaceResp?.surfaces) && surfaceResp.surfaces.length > 0
? surfaceResp.surfaces
: FALLBACK_SURFACES;
const bySurface = new Map(definitions.map((item) => [item.surface, item]));
const order = Array.isArray(surfaceResp?.order) && surfaceResp.order.length > 0
? surfaceResp.order
: FALLBACK_SURFACES.map((item) => item.surface);
return `
<div class="surface-rail">
${order
.map((surface) => {
const definition = bySurface.get(surface) || { surface, headline: surface, description: "" };
const summary = latestRun?.surfaces?.[surface] || null;
return `
<div class="surface-tile">
<div class="row spaced">
<strong>${htmlEscape(definition.surface)}</strong>
${statusPill(summary?.status || "pending")}
</div>
<div class="surface-headline">${htmlEscape(definition.headline || "")}</div>
<p class="muted">${htmlEscape(summary?.summary || definition.description || "")}</p>
</div>
`;
})
.join("")}
</div>
`;
}
function renderEvidenceRows(rows, type, agentId) {
if (!Array.isArray(rows) || rows.length === 0) {
return `<tr><td colspan="4" class="muted">No ${htmlEscape(type)} records found.</td></tr>`;
}
return rows
.slice(0, 8)
.map((row) => {
const id = row.episodeId || row.receiptId || row.proofId || row.observabilityId || row.lifecycleRunId || row.runId || "-";
const selector = encodeURIComponent(id);
const href = type === "episode"
? `./evidence?agent=${encodeURIComponent(agentId)}&episode=${selector}`
: type === "proof"
? `./evidence?agent=${encodeURIComponent(agentId)}&proof=${selector}`
: type === "observability"
? `./evidence?agent=${encodeURIComponent(agentId)}&observability=${selector}`
: type === "lifecycle-receipt"
? `./evidence?agent=${encodeURIComponent(agentId)}&receipt=${selector}`
: `./evidence?agent=${encodeURIComponent(agentId)}&decision=${selector}`;
return `<tr>
<td><a href="${href}"><code>${htmlEscape(shortId(id, 18))}</code></a></td>
<td>${htmlEscape(shortId(row.runId || row.lifecycleRunId || "-", 18))}</td>
<td>${htmlEscape(row.source || row.decision || row.receiptType || row.surface || row.status || (type === "observability" ? "Watch" : "-"))}</td>
<td>${htmlEscape(type === "proof" || type === "lifecycle-receipt" ? (row.status || "-") : formatTime(row.createdAt || row.decidedAt || row.ts))}</td>
</tr>`;
})
.join("");
}
function renderOnboardingSteps(state) {
const steps = Array.isArray(state?.steps) ? state.steps : [];
if (steps.length === 0) {
return "<p class='muted'>No onboarding state yet.</p>";
}
return `
<div class="onboarding-steps">
${steps
.map((step) => `
<div class="onboarding-step">
${statusPill(step.status || "pending")}
<div>
<strong>${htmlEscape(step.label || step.id || "step")}</strong>
<p class="muted">${htmlEscape(step.summary || "")}</p>
</div>
</div>
`)
.join("")}
</div>
`;
}
function renderOnboardingActivation(activation) {
const milestones = Array.isArray(activation?.milestones) ? activation.milestones : [];
if (milestones.length === 0) {
return "<p class='muted'>No verified activation outcomes yet.</p>";
}
return `
<div class="activation-list">
${milestones.map((row, index) => `
<div class="activation-row">
<span class="activation-index">0${index + 1}</span>
<div class="activation-copy">
<strong>${htmlEscape(row.label || row.id || "Outcome")}</strong>
<p class="muted">${htmlEscape(row.summary || "")}</p>
${row.evidence?.studioPath ? `<a href="${htmlEscape(row.evidence.studioPath.replace(/^\/console\//, "./"))}">View signed proof</a>` : ""}
</div>
${statusPill(row.status || "WAITING")}
</div>
`).join("")}
</div>
${activation.nextAction ? `
<div class="activation-next">
<span>Next</span>
<code>${htmlEscape(activation.nextAction.command || "")}</code>
</div>
` : ""}
`;
}
function renderApiQuickstart(status, agentId) {
const base = `${window.location.origin}${workspacePrefixFromPath()}`;
const demoMode = currentWorkspaceLabel() === "demo";
const tokenHeader = 'x-amc-admin-token: <admin-token>';
const authDisplay = demoMode ? "none (loopback-only demo)" : tokenHeader;
const authArgument = demoMode ? "" : ` -H "${tokenHeader}"`;
const examples = [
{
label: "GET /status",
method: "GET",
path: "/status",
title: "Studio status",
command: `curl -s ${base}/status${authArgument}`,
response: '{ "studio": { "running": true }, "vaultLocked": true }'
},
{
label: "GET /api/v1/score/latest",
method: "GET",
path: `/api/v1/score/latest?agentId=${encodeURIComponent(agentId)}`,
title: "Latest score",
command: `curl -s "${base}/api/v1/score/latest?agentId=${encodeURIComponent(agentId)}"${authArgument}`,
response: '{ "runId": "...", "integrityIndex": 0.82, "trustLabel": "HIGH TRUST" }'
},
{
label: "POST /api/v1/score/quickscore",
method: "POST",
path: "/api/v1/score/quickscore",
title: "Run quickscore",
command: `curl -s ${base}/api/v1/score/quickscore -H "content-type: application/json"${authArgument} -d '{"answers":{"AMC-1.1":2,"AMC-2.1":2,"AMC-3.1.1":2,"AMC-4.1":2,"AMC-5.1":2}}'`,
response: '{ "ok": true, "data": { "result": { "preliminaryLevel": "L2", "percentage": 40 } } }'
}
];
return `
${card("API Quickstart", `
<div class="api-quickstart-head">
<div>
<div class="muted">Base URL</div>
<code>${htmlEscape(base || window.location.origin)}</code>
</div>
<div>
<div class="muted">Auth header</div>
<code>${htmlEscape(authDisplay)}</code>
</div>
<div>
<div class="muted">Current agent</div>
<code>${htmlEscape(agentId)}</code>
</div>
</div>
<div class="api-quickstart-grid">
${examples.map((example) => `
<div class="api-example-card">
<div class="row spaced wrap">
<strong>${htmlEscape(example.label)}</strong>
<span class="pill muted">${htmlEscape(example.title)}</span>
</div>
<pre>${htmlEscape(example.command)}</pre>
<div class="muted">Response shape</div>
<code class="api-response-shape">${htmlEscape(example.response)}</code>
</div>
`).join("")}
</div>
<p class="muted">OpenAPI spec: <code>${htmlEscape(base)}/openapi.json</code>. Demo mode is for exploration; signed verifier-ready artifacts still require standard vault-backed startup.</p>
`)}
`;
}
async function renderEvidence() {
const agentId = currentAgent();
const resourceStatusEnvelope = await apiGet(`/api/v1/enforce/resources/status?agentId=${encodeURIComponent(agentId)}`)
.catch((error) => ({ state: "BLOCKED", integrity: { valid: false, reasonCodes: [errText(error)] } }));
const resourceStatusPreview = apiPayload(resourceStatusEnvelope) || {};
const resourceProofReady = resourceStatusPreview?.state === "ACTIVE" || resourceStatusPreview?.state === "DRIFTED";
const resourceVerificationReady = resourceStatusPreview?.state === "ACTIVE";
const resourceProofError = resourceStatusPreview?.integrity?.reasonCodes?.[0] || "MANIFEST_MISSING";
const [
surfaces,
lifecycleList,
latestEnvelope,
episodesEnvelope,
decisionsEnvelope,
observabilityEnvelope,
traceIndexesEnvelope,
failureClustersEnvelope,
fixerReportsEnvelope,
proofEnvelope,
lifecycleReceiptsEnvelope,
reasoningMemoryEnvelope,
resourceStatus,
resourceVerify,
resourceValidation,
resourceHistory,
resourceContract,
importsEnvelope,
strategyEnvelope
] = await Promise.all([
apiGet("/api/v1/lifecycle/surfaces").catch(() => ({ order: [], surfaces: FALLBACK_SURFACES })),
apiGet(`/api/v1/lifecycle/runs?agentId=${encodeURIComponent(agentId)}&limit=8`).catch(() => ({ runs: [] })),
apiGet(`/api/v1/lifecycle/latest?agentId=${encodeURIComponent(agentId)}&redacted=true`).catch(() => ({ run: null })),
apiGet(`/api/v1/evidence/episodes?agentId=${encodeURIComponent(agentId)}&limit=8`).catch(() => ({ episodes: [] })),
apiGet(`/api/v1/evidence/decisions?agentId=${encodeURIComponent(agentId)}&limit=8`).catch(() => ({ receipts: [] })),
apiGet(`/api/v1/evidence/observability?agentId=${encodeURIComponent(agentId)}&limit=8`).catch(() => ({ records: [] })),
apiGet(`/api/v1/evidence/trace-indexes?agentId=${encodeURIComponent(agentId)}&limit=8`).catch(() => ({ indexes: [] })),
apiGet(`/api/v1/evidence/failure-clusters?agentId=${encodeURIComponent(agentId)}&limit=8`).catch(() => ({ clusters: [] })),
apiGet(`/api/v1/fixer/rca?agentId=${encodeURIComponent(agentId)}&limit=4`).catch(() => ({ reports: [] })),
apiGet(`/api/v1/evidence/finding-proofs?agentId=${encodeURIComponent(agentId)}&limit=12`).catch(() => ({ proofs: [] })),
apiGet(`/api/v1/evidence/lifecycle-receipts?agentId=${encodeURIComponent(agentId)}&limit=12`).catch(() => ({ receipts: [] })),
apiGet(`/api/v1/memory/reasoning?agentId=${encodeURIComponent(agentId)}&consumer=studio&limit=8`).catch(() => ({ items: [] })),
Promise.resolve(resourceStatusEnvelope),
resourceVerificationReady
? apiGet(`/api/v1/enforce/resources/verify?agentId=${encodeURIComponent(agentId)}`).catch((error) => ({ valid: false, error: errText(error) }))
: Promise.resolve({ valid: false, error: resourceProofError }),
resourceProofReady
? apiGet(`/api/v1/enforce/resources/validate?agentId=${encodeURIComponent(agentId)}`).catch((error) => ({ status: "blocked", error: errText(error), gates: [] }))
: Promise.resolve({ status: "blocked", error: resourceProofError, gates: [] }),
apiGet(`/api/v1/enforce/resources/history?agentId=${encodeURIComponent(agentId)}`).catch(() => ({ entries: [] })),
apiGet("/api/v1/enforce/resources/contract").catch(() => ({ verbs: [], resourceKinds: [], gates: [] })),
apiGet("/api/v1/imports?limit=6").catch(() => ({ imports: [] })),
apiGet(`/api/v1/strategy/runs?agentId=${encodeURIComponent(agentId)}&limit=6`).catch(() => ({ runs: [] }))
]);
const surfacesData = apiPayload(surfaces) || {};
const lifecycleData = apiPayload(lifecycleList) || {};
const latestData = apiPayload(latestEnvelope) || {};
const episodesData = apiPayload(episodesEnvelope) || {};
const decisionsData = apiPayload(decisionsEnvelope) || {};
const observabilityData = apiPayload(observabilityEnvelope) || {};
const traceIndexesData = apiPayload(traceIndexesEnvelope) || {};
const failureClustersData = apiPayload(failureClustersEnvelope) || {};
const fixerReportsData = apiPayload(fixerReportsEnvelope) || {};
const proofsData = apiPayload(proofEnvelope) || {};
const lifecycleReceiptsData = apiPayload(lifecycleReceiptsEnvelope) || {};
const reasoningMemoryData = apiPayload(reasoningMemoryEnvelope) || {};
const resourceStatusData = apiPayload(resourceStatus) || {};
const resourceVerifyData = apiPayload(resourceVerify) || {};
const resourceValidationData = apiPayload(resourceValidation) || {};
const resourceHistoryData = apiPayload(resourceHistory) || {};
const resourceContractData = apiPayload(resourceContract) || {};
const importsData = apiPayload(importsEnvelope) || {};
const strategyData = apiPayload(strategyEnvelope) || {};
const latestRun = latestData?.run || null;
const lifecycleRuns = Array.isArray(lifecycleData?.runs) ? lifecycleData.runs : [];
const episodes = Array.isArray(episodesData?.episodes) ? episodesData.episodes : [];
const receipts = Array.isArray(decisionsData?.receipts) ? decisionsData.receipts : [];
const observabilityRecords = Array.isArray(observabilityData?.records) ? observabilityData.records : [];
const traceIndexes = Array.isArray(traceIndexesData?.indexes) ? traceIndexesData.indexes : [];
const failureClusters = Array.isArray(failureClustersData?.clusters) ? failureClustersData.clusters : [];
const fixerReports = Array.isArray(fixerReportsData?.reports) ? fixerReportsData.reports : [];
const latestObservability = observabilityRecords[0] || null;
const latestTraceIndex = traceIndexes[0] || null;
const latestFixerReport = fixerReports[0] || null;
const proofs = Array.isArray(proofsData?.proofs) ? proofsData.proofs : [];
const lifecycleReceipts = Array.isArray(lifecycleReceiptsData?.receipts) ? lifecycleReceiptsData.receipts : [];
const reasoningMemoryItems = Array.isArray(reasoningMemoryData?.items) ? reasoningMemoryData.items : [];
const resourceHistoryEntries = Array.isArray(resourceHistoryData?.entries) ? resourceHistoryData.entries : [];
const neutralImports = Array.isArray(importsData?.imports) ? importsData.imports : [];
const strategyRuns = Array.isArray(strategyData?.runs) ? strategyData.runs : [];
const verifiedProofs = proofs.filter((proof) => proof?.status === "verified").length;
const surfaceComplete = latestRun?.surfaces
? Object.values(latestRun.surfaces).filter((item) => item?.status === "complete").length
: 0;
const resourceSignature = resourceStatusData?.integrity?.valid === false
? "INVALID"
: resourceVerifyData?.signature?.valid === true
? "VALID"
: resourceVerifyData?.signature?.missing
? "MISSING"
: resourceVerifyData?.valid
? "UNSIGNED"
: "INVALID";
root.innerHTML = `
<section class="card studio-hero evidence-hero">
<div>
<div class="studio-kicker">agent lifecycle</div>
<h2 class="studio-title">Score<span>Enforce</span><strong>Prove_</strong></h2>
<p class="studio-sub">
One console for the full AMC loop across Score, Shield, Enforce, Vault, Watch, Comply, Fleet, and Passport.
</p>
<div class="studio-actions">
<button id="evidenceRunScore">run full score -></button>
<button id="evidenceSnapshot" class="secondary">snapshot Enforce resources</button>
<a class="secondary" href="./passport?agent=${encodeURIComponent(agentId)}" style="display:inline-flex;align-items:center;border:1px solid var(--border-strong);border-radius:6px;padding:9px 13px;font-family:var(--mono);font-size:12px;color:var(--ink)">passport -></a>
</div>
</div>
<div class="studio-terminal">
<div class="studio-terminal-bar">
<span class="studio-dot r"></span><span class="studio-dot y"></span><span class="studio-dot g"></span>
<span class="studio-terminal-title">amc evidence</span>
</div>
<div class="studio-terminal-body">
<div class="studio-command">$ amc</div>
<div class="studio-terminal-line"><strong>Agent</strong><span>${htmlEscape(agentId)}</span></div>
<div class="studio-terminal-line"><strong>Latest run</strong><span>${htmlEscape(shortId(latestRun?.runId, 16))}</span></div>
<div class="studio-terminal-line"><strong>Full score latency</strong><span>${latestRun?.elapsedMs === null || latestRun?.elapsedMs === undefined ? "-" : `${Number(latestRun.elapsedMs)}ms`}</span></div>
<div class="studio-terminal-line"><strong>Evidence coverage</strong><span>${latestRun ? `${(Number(latestRun.evidence?.evidenceCoverage || 0) * 100).toFixed(1)}%` : "-"}</span></div>
<div class="studio-terminal-line"><strong>Resource state</strong><span>${htmlEscape(resourceStatusData?.state || "NOT_INITIALIZED")}</span></div>
<div class="studio-terminal-line"><strong>Resource gates</strong><span>${htmlEscape(resourceValidationData?.status || "unknown")}</span></div>
<div class="studio-terminal-line"><strong>Signature</strong><span>${htmlEscape(resourceSignature)}</span></div>
</div>
</div>
</section>
<div class="studio-kpi-grid">
<section class="card studio-kpi"><div class="muted">Surfaces Complete</div><div class="tile-value">${surfaceComplete}/8</div></section>
<section class="card studio-kpi"><div class="muted">Lifecycle Runs</div><div class="tile-value">${lifecycleRuns.length}</div></section>
<section class="card studio-kpi"><div class="muted">Episodes</div><div class="tile-value">${episodes.length}</div></section>
<section class="card studio-kpi"><div class="muted">Failure Clusters</div><div class="tile-value">${failureClusters.length}</div></section>
<section class="card studio-kpi"><div class="muted">Fixer RCA</div><div class="tile-value">${fixerReports.length}</div></section>
<section class="card studio-kpi"><div class="muted">Memory Lessons</div><div class="tile-value">${reasoningMemoryItems.length}</div></section>
<section class="card studio-kpi"><div class="muted">Imports</div><div class="tile-value">${neutralImports.length}</div></section>
<section class="card studio-kpi"><div class="muted">Strategies</div><div class="tile-value">${strategyRuns.length}</div></section>
</div>
<div class="studio-section-label">8 surfaces</div>
${renderSurfaceRail(surfacesData, latestRun)}
<div class="studio-section-label">evidence chain</div>
<div class="studio-chart-grid">
${card("Latest Lifecycle Artifact", latestRun ? `
<div class="lifecycle-summary">
<div><span class="muted">Lifecycle</span><code>${htmlEscape(latestRun.lifecycleRunId)}</code></div>
<div><span class="muted">Run</span><code>${htmlEscape(latestRun.runId)}</code></div>
<div><span class="muted">Created</span><strong>${htmlEscape(formatTime(latestRun.createdAt))}</strong></div>
<div><span class="muted">Vault</span>${statusPill(latestRun.setup?.signed ? "VALID" : "MISSING")}</div>
</div>
<pre class="scroll">${htmlEscape(JSON.stringify({
diagnosticReport: latestRun.evidence?.diagnosticReport,
episodeRecords: latestRun.evidence?.episodeRecords,
decisionReceipts: latestRun.evidence?.decisionReceipts,
lifecycleReceipts: latestRun.evidence?.lifecycleReceipts,
findingProofs: latestRun.evidence?.findingProofs,
observabilityRecords: latestRun.evidence?.observabilityRecords,
resourceManifests: latestRun.evidence?.resourceManifests
}, null, 2))}</pre>
` : "<p class='muted'>No lifecycle artifact has been generated for this agent yet.</p>")}
${card("Decision Observability", latestObservability ? `
<div class="lifecycle-summary">
<div><span class="muted">Record</span><code>${htmlEscape(shortId(latestObservability.observabilityId, 18))}</code></div>
<div><span class="muted">Components</span><strong>${Number(latestObservability.summary?.componentCount || 0)}</strong></div>
<div><span class="muted">Experience</span><strong>${Number(latestObservability.summary?.experienceSignalCount || 0)}</strong></div>
<div><span class="muted">Observed</span><strong>${Number(latestObservability.summary?.observedDecisionCount || 0)}/${Number(latestObservability.summary?.decisionCount || 0)}</strong></div>
</div>
<pre class="scroll">${htmlEscape(JSON.stringify({
highRiskComponents: latestObservability.summary?.highRiskComponentCount || 0,
componentAttribution: (latestObservability.componentAttribution || []).slice(0, 8),
experienceCorpus: (latestObservability.experienceCorpus || []).slice(0, 8),
decisionChain: (latestObservability.decisionChain || []).slice(0, 8)
}, null, 2))}</pre>
` : "<p class='muted'>No decision observability record yet. Run `amc` to capture component attribution, experience signals, and decision outcomes.</p>")}
${card("Trace Failure Miner", latestTraceIndex ? `
<div class="lifecycle-summary">
<div><span class="muted">Index</span><code>${htmlEscape(shortId(latestTraceIndex.indexId, 18))}</code></div>
<div><span class="muted">Entries</span><strong>${Number(latestTraceIndex.summary?.entryCount || 0)}</strong></div>
<div><span class="muted">Clusters</span><strong>${Number(latestTraceIndex.summary?.clusterCount || 0)}</strong></div>
<div><span class="muted">Top class</span><strong>${htmlEscape(latestTraceIndex.summary?.topFailureClass || "-")}</strong></div>
</div>
<div class="scroll"><table><thead><tr><th>Class</th><th>Count</th><th>Impact</th><th>Snippet</th></tr></thead><tbody>${failureClusters.map((cluster) => `
<tr>
<td>${htmlEscape(cluster.failureClass)}</td>
<td>${Number(cluster.count || 0)}</td>
<td>${Number(cluster.scoreImpact || 0)}</td>
<td>${htmlEscape(cluster.sampleSnippet || "")}</td>
</tr>
`).join("") || "<tr><td colspan='4' class='muted'>No repeated failure clusters.</td></tr>"}</tbody></table></div>
` : "<p class='muted'>No trace failure index yet. Run `amc` with trace-backed evidence to mine recurring failure modes.</p>")}
${card("Fixer RCA", `
<div class="lifecycle-summary">
<div><span class="muted">Latest</span><code>${htmlEscape(shortId(latestFixerReport?.reportId, 18))}</code></div>
<div><span class="muted">Root causes</span><strong>${Number(latestFixerReport?.rootCauses?.length || 0)}</strong></div>
<div><span class="muted">Regression tests</span><strong>${Number(latestFixerReport?.regressionTests?.length || 0)}</strong></div>
<div><span class="muted">Validation</span>${statusPill(latestFixerReport?.validationReceipt?.status || "READY")}</div>
</div>
<pre id="fixerRcaOut" class="scroll">${htmlEscape(JSON.stringify(latestFixerReport ? {
runId: latestFixerReport.runId,
rootCauses: (latestFixerReport.rootCauses || []).slice(0, 4),
proposals: (latestFixerReport.proposals || []).slice(0, 4),
validationReceipt: latestFixerReport.validationReceipt
} : {
next: "Generate RCA from the latest trace failure index.",
command: "amc mechanic rca run <run-id>"
}, null, 2))}</pre>
<div class="row wrap">
<button id="evidenceGenerateRca" class="secondary">generate RCA</button>
</div>
`)}
${card("Reasoning Memory", `
<div class="scroll"><table><thead><tr><th>Memory</th><th>Type</th><th>Confidence</th><th>Expires</th><th>Actions</th></tr></thead><tbody>${reasoningMemoryItems.map((item) => `
<tr>
<td><code>${htmlEscape(shortId(item.memoryId, 18))}</code></td>
<td>${htmlEscape(item.lessonType || "-")}</td>
<td>${Number(item.confidence || 0).toFixed(2)}</td>
<td>${htmlEscape(formatTime(item.expiresAt))}</td>
<td><button class="secondary" data-memory-show="${htmlEscape(item.memoryId || "")}">Show</button></td>
</tr>
`).join("") || "<tr><td colspan='5' class='muted'>No reasoning memory items.</td></tr>"}</tbody></table></div>
<pre id="reasoningMemoryOut" class="scroll">${htmlEscape(JSON.stringify(reasoningMemoryItems.slice(0, 3), null, 2))}</pre>
<div class="row wrap">
<button id="evidenceWriteMemory" class="secondary">write memory</button>
</div>
`)}
${card("Enforce Resource Proof", `
<div class="lifecycle-summary">
<div><span class="muted">Active</span><strong>${htmlEscape(shortId(resourceStatusData?.active?.manifestId, 18))}</strong></div>
<div><span class="muted">Previous</span><strong>${htmlEscape(shortId(resourceStatusData?.previous?.manifestId, 18))}</strong></div>
<div><span class="muted">Rollback</span><strong>${htmlEscape(shortId(resourceStatusData?.rollbackTarget?.manifestId, 18))}</strong></div>
<div><span class="muted">State</span>${statusPill(resourceStatusData?.state || "NOT_INITIALIZED")}</div>
<div><span class="muted">Gates</span>${statusPill(resourceValidationData?.status || "UNKNOWN")}</div>
<div><span class="muted">Signature</span>${statusPill(resourceSignature)}</div>
<div><span class="muted">Changed</span><strong>${Number(resourceStatusData?.pendingDiff?.changed?.length || 0)}</strong></div>
</div>
<pre id="resourceProofOut" class="scroll">${htmlEscape(JSON.stringify({
status: resourceStatusData || {},
verification: resourceVerifyData || {},
validation: resourceValidationData || {},
contract: {
verbs: resourceContractData?.verbs || [],
resourceKinds: resourceContractData?.resourceKinds || [],
gates: resourceContractData?.gates || []
},
history: resourceHistoryEntries.slice(0, 6)
}, null, 2))}</pre>
<div class="row wrap">
<button id="evidenceVerifyResources" class="secondary">verify now</button>
<button id="evidenceValidateResources" class="secondary">validate gates</button>
<button id="evidenceApplyDryRun" class="secondary">dry-run apply</button>
<button id="evidenceRestoreDryRun" class="secondary">dry-run restore</button>
<button id="evidenceActivateResources" ${resourceStatusData?.state === "DRIFTED" ? "" : "disabled"}>activate changes</button>
<button id="evidenceRollbackResources" ${resourceStatusData?.rollbackTarget?.manifestId ? "" : "disabled"}>rollback previous</button>
</div>
`)}
${card("Neutral Import", `
<div class="row wrap">
<input id="neutralImportPath" placeholder="/path/to/traces-or-run-dir" style="min-width:280px" />
<button id="neutralImportDryRun" class="secondary">review import</button>
<button id="neutralImportApply" disabled>apply reviewed import</button>
</div>
<p class="muted">Imported claims remain self-reported and unevaluated. Review unknown timing, skipped files and mapping limits before applying.</p>
<div id="neutralImportReview" role="status" aria-live="polite"></div>
<pre id="neutralImportOut" class="scroll">${htmlEscape(JSON.stringify({
recent: neutralImports.map((row) => ({
importId: row.importId,
agentId: row.agentId,
categories: row.plan?.categories || [],
redactions: row.plan?.redactionCount || 0,
createdAt: row.createdAt
}))
}, null, 2))}</pre>
<div class="scroll"><table><thead><tr><th>Import</th><th>Agent</th><th>Artifacts</th><th>Categories</th><th>Redactions</th></tr></thead><tbody>${neutralImports.map((row) => `
<tr>
<td><details><summary><code>${htmlEscape(shortId(row.importId, 18))}</code></summary>${renderNeutralImportReview(row.plan, { applied: true })}</details></td>
<td>${htmlEscape(row.agentId || "-")}</td>
<td>${Number(row.plan?.candidateCount || 0)}</td>
<td>${htmlEscape((row.plan?.categories || []).join(", ") || "-")}</td>
<td>${Number(row.plan?.redactionCount || 0)}</td>
</tr>
`).join("") || "<tr><td colspan='5' class='muted'>No neutral imports yet.</td></tr>"}</tbody></table></div>
`)}
${card("Inference Strategy", `
<pre id="strategyCompareOut" class="scroll">${htmlEscape(JSON.stringify({
recent: strategyRuns.map((row) => ({
strategyRunId: row.strategyRunId,
recommended: row.recommendedStrategyId,
routeChange: row.routeChange?.status,
confidence: row.confidence,
summary: row.tradeoffSummary
}))
}, null, 2))}</pre>
<div class="scroll"><table><thead><tr><th>Run</th><th>Recommended</th><th>Route</th><th>Confidence</th><th>Tradeoff</th></tr></thead><tbody>${strategyRuns.map((row) => `
<tr>
<td><code>${htmlEscape(shortId(row.strategyRunId, 18))}</code></td>
<td>${htmlEscape(row.recommendedStrategyId || "-")}</td>
<td>${htmlEscape(row.routeChange?.status || "-")}</td>
<td>${Number(row.confidence || 0).toFixed(2)}</td>
<td>${htmlEscape(row.tradeoffSummary || "")}</td>
</tr>
`).join("") || "<tr><td colspan='5' class='muted'>No strategy comparisons yet.</td></tr>"}</tbody></table></div>
`)}
</div>
<div class="studio-chart-grid">
${card("Episode Records", `
<div class="scroll"><table><thead><tr><th>Episode</th><th>Run</th><th>Source</th><th>Created</th></tr></thead><tbody>${renderEvidenceRows(episodes, "episode", agentId)}</tbody></table></div>
`)}
${card("Decision Receipts", `
<div class="scroll"><table><thead><tr><th>Receipt</th><th>Run</th><th>Decision</th><th>Created</th></tr></thead><tbody>${renderEvidenceRows(receipts, "decision", agentId)}</tbody></table></div>
`)}
${card("Observability Records", `
<div class="scroll"><table><thead><tr><th>Record</th><th>Run</th><th>Status</th><th>Created</th></tr></thead><tbody>${renderEvidenceRows(observabilityRecords, "observability", agentId)}</tbody></table></div>
`)}
${card("Finding Proofs", `
<div class="scroll"><table><thead><tr><th>Proof</th><th>Run</th><th>Surface</th><th>Status</th></tr></thead><tbody>${renderEvidenceRows(proofs, "proof", agentId)}</tbody></table></div>
`)}
${card("Lifecycle Receipts", `
<div class="scroll"><table><thead><tr><th>Receipt</th><th>Run</th><th>Type</th><th>Status</th></tr></thead><tbody>${renderEvidenceRows(lifecycleReceipts, "lifecycle-receipt", agentId)}</tbody></table></div>
`)}
</div>
`;
document.getElementById("evidenceRunScore")?.addEventListener("click", async (event) => {
const button = event.currentTarget;
const original = button.textContent;
button.textContent = "running...";
button.disabled = true;
try {
await apiPost("/cli/exec", { command: "amc", format: "json", timeout: 120000 });
setStatus("Full score generated.");
await renderEvidence();
} catch (error) {
setStatus(`Full score failed: ${errText(error)}`, true);
} finally {
button.disabled = false;
button.textContent = original;
}
});
document.getElementById("evidenceSnapshot")?.addEventListener("click", async () => {
const out = await apiPost("/api/v1/enforce/resources/snapshot", { agentId });
setStatus("Enforce resource snapshot generated.");
const proofOut = document.getElementById("resourceProofOut");
if (proofOut) {
proofOut.textContent = JSON.stringify(out, null, 2);
}
});
document.getElementById("evidenceGenerateRca")?.addEventListener("click", async () => {
const selector = latestTraceIndex?.runId || latestRun?.runId;
if (!selector) {
setStatus("Run a full score before generating fixer RCA.", true);
return;
}
const out = await apiPost("/api/v1/fixer/rca", { agentId, selector });
const payload = apiPayload(out) || out;
setStatus("Fixer RCA generated.");
const fixerOut = document.getElementById("fixerRcaOut");
if (fixerOut) {
fixerOut.textContent = JSON.stringify(payload.report || payload, null, 2);
}
});
document.getElementById("evidenceWriteMemory")?.addEventListener("click", async () => {
const latestEpisode = episodes[0];
const selector = latestEpisode?.episodeId || latestEpisode?.runId;
if (!selector) {
setStatus("Run a full score before writing reasoning memory.", true);
return;
}
const out = await apiPost("/api/v1/memory/reasoning/writeback", {
agentId,
episodeSelector: selector
});
setStatus("Reasoning memory writeback recorded.");
const memoryOut = document.getElementById("reasoningMemoryOut");
if (memoryOut) {
memoryOut.textContent = JSON.stringify(apiPayload(out) || out, null, 2);
}
});
document.querySelectorAll("button[data-memory-show]").forEach((button) => {
button.addEventListener("click", async () => {
const id = button.getAttribute("data-memory-show");
const out = await apiGet(`/api/v1/memory/reasoning/${encodeURIComponent(id)}?agentId=${encodeURIComponent(agentId)}`);
const memoryOut = document.getElementById("reasoningMemoryOut");
if (memoryOut) {
memoryOut.textContent = JSON.stringify(apiPayload(out) || out, null, 2);
}
});
});
document.getElementById("evidenceVerifyResources")?.addEventListener("click", async () => {
const out = await apiGet(`/api/v1/enforce/resources/verify?agentId=${encodeURIComponent(agentId)}`).catch((error) => ({ valid: false, error: errText(error) }));
const proofOut = document.getElementById("resourceProofOut");
if (proofOut) {
proofOut.textContent = JSON.stringify(out, null, 2);
}
});
document.getElementById("evidenceValidateResources")?.addEventListener("click", async () => {
const out = await apiGet(`/api/v1/enforce/resources/validate?agentId=${encodeURIComponent(agentId)}`).catch((error) => ({ status: "blocked", error: errText(error) }));
const proofOut = document.getElementById("resourceProofOut");
if (proofOut) {
proofOut.textContent = JSON.stringify(out, null, 2);
}
});
document.getElementById("evidenceApplyDryRun")?.addEventListener("click", async () => {
const out = await apiPost("/api/v1/enforce/resources/apply", { agentId, dryRun: true });
const proofOut = document.getElementById("resourceProofOut");
if (proofOut) {
proofOut.textContent = JSON.stringify(out, null, 2);
}
});
document.getElementById("evidenceRestoreDryRun")?.addEventListener("click", async () => {
const out = await apiPost("/api/v1/enforce/resources/restore", { agentId, apply: false });
const proofOut = document.getElementById("resourceProofOut");
if (proofOut) {
proofOut.textContent = JSON.stringify(out, null, 2);
}
});
document.getElementById("evidenceActivateResources")?.addEventListener("click", async () => {
const previewEnvelope = await apiPost("/api/v1/enforce/resources/apply", { agentId, dryRun: true });
const preview = apiPayload(previewEnvelope) || {};
const targetManifestId = preview?.proposal?.currentManifestId;
if (!targetManifestId) {
setStatus("No verified resource activation target is available.", true);
return;
}
if (!window.confirm(`Activate resource version ${targetManifestId}?`)) return;
const out = await apiPost("/api/v1/enforce/resources/apply", {
agentId,
dryRun: false,
confirmManifestId: targetManifestId
});
const proofOut = document.getElementById("resourceProofOut");
if (proofOut) proofOut.textContent = JSON.stringify(out, null, 2);
setStatus(`Activated resource version ${targetManifestId}.`);
await renderEvidence();
});
document.getElementById("evidenceRollbackResources")?.addEventListener("click", async () => {
const rollbackTarget = resourceStatusData?.rollbackTarget;
if (!rollbackTarget?.manifestId || !rollbackTarget?.ref) {
setStatus("No verified rollback target is available.", true);
return;
}
if (!window.confirm(`Rollback to signed resource version ${rollbackTarget.manifestId}?`)) return;
const out = await apiPost("/api/v1/enforce/resources/rollback", {
agentId,
manifestPath: rollbackTarget.ref,
apply: true,
confirmManifestId: rollbackTarget.manifestId
});
const proofOut = document.getElementById("resourceProofOut");