File size: 39,430 Bytes
b7dccee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8033e6
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Primordial Code Layer v0.4.6 — HIR/OAM Governance Validator</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    :root {
      --bg-primary: #0a0e14;
      --bg-secondary: #111822;
      --bg-tertiary: #1a2332;
      --accent-primary: #00ffcc;
      --accent-secondary: #ff00ff;
      --accent-tertiary: #00d4ff;
      --warning: #ffaa00;
      --danger: #ff4444;
      --success: #00ff88;
      --text-primary: #e0e6f0;
      --text-secondary: #8b95a8;
      --glow: 0 0 20px rgba(0,255,204,0.5);
    }
    body {
      font-family: Consolas, "Courier New", monospace;
      background: var(--bg-primary);
      color: var(--text-primary);
      line-height: 1.6;
      padding: 2rem;
    }
    .header { text-align: center; margin-bottom: 2rem; }
    .version-badge {
      display: inline-block;
      background: var(--success);
      color: var(--bg-primary);
      padding: 0.4rem 1rem;
      border-radius: 4px;
      font-size: 0.85rem;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 0.1em;
      margin-bottom: 1rem;
    }
    h1 {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 2.5rem;
      font-weight: 900;
      background: linear-gradient(135deg, var(--accent-primary), var(--accent-tertiary));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      margin-bottom: 0.5rem;
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }
    .subtitle { font-size: 0.9rem; color: var(--text-secondary); letter-spacing: 0.1em; }
    .thesis-banner {
      background: var(--bg-secondary);
      border: 2px solid var(--accent-primary);
      border-radius: 8px;
      padding: 1.5rem;
      margin: 2rem 0;
      text-align: center;
      font-size: 1rem;
      line-height: 1.8;
      box-shadow: var(--glow);
    }
    .boundary-banner {
      background: linear-gradient(135deg, rgba(255,170,0,0.15), rgba(255,68,68,0.15));
      border: 2px solid var(--warning);
      border-radius: 8px;
      padding: 1.5rem;
      margin-bottom: 2rem;
      font-size: 0.85rem;
      line-height: 1.7;
    }
    .container { display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; max-width: 1800px; margin: 0 auto; }
    .panel { background: var(--bg-secondary); border: 1px solid var(--accent-primary); border-radius: 8px; padding: 1.5rem; }
    .panel-title { font-family: Arial, Helvetica, sans-serif; font-size: 1.2rem; color: var(--accent-primary); margin-bottom: 1rem; text-transform: uppercase; letter-spacing: 0.05em; }
    .full-width { grid-column: 1 / -1; }
    textarea { width: 100%; min-height: 400px; background: var(--bg-tertiary); border: 1px solid var(--accent-tertiary); border-radius: 4px; color: var(--text-primary); font-family: Consolas, "Courier New", monospace; font-size: 0.85rem; padding: 1rem; resize: vertical; }
    button { background: var(--accent-primary); color: var(--bg-primary); border: none; padding: 0.7rem 1.5rem; border-radius: 4px; font-family: Consolas, "Courier New", monospace; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; cursor: pointer; transition: all 0.2s ease; margin: 0.5rem 0.5rem 0.5rem 0; }
    button:hover { background: var(--accent-tertiary); box-shadow: 0 0 15px rgba(0,255,204,0.5); }
    button.danger { background: var(--danger); color: white; }
    button.warning { background: var(--warning); color: var(--bg-primary); }
    button.secondary { background: var(--bg-tertiary); color: var(--accent-primary); border: 1px solid var(--accent-primary); }
    .metric-row { display:flex; justify-content:space-between; gap:1rem; padding:0.8rem; margin:0.5rem 0; background:var(--bg-tertiary); border-radius:4px; border-left:3px solid var(--accent-secondary); }
    .metric-label { color: var(--text-secondary); font-size: 0.9rem; }
    .metric-value { color: var(--accent-primary); font-weight: 700; font-size: 1rem; }
    .gate-indicator { display:inline-block; padding:1rem 2rem; border-radius:8px; font-weight:800; text-transform:uppercase; letter-spacing:0.15em; font-size:1.5rem; text-align:center; width:100%; margin:1rem 0; }
    .gate-green { background:var(--success); color:var(--bg-primary); box-shadow:0 0 25px rgba(0,255,136,0.5); }
    .gate-yellow { background:var(--warning); color:var(--bg-primary); box-shadow:0 0 25px rgba(255,170,0,0.5); }
    .gate-red { background:var(--danger); color:white; box-shadow:0 0 25px rgba(255,68,68,0.5); }
    .gate-quarantine { background:#8800ff; color:white; box-shadow:0 0 25px rgba(136,0,255,0.5); }
    .slider-container { margin:1rem 0; }
    .slider-label { display:flex; justify-content:space-between; margin-bottom:0.5rem; font-size:0.85rem; }
    input[type="range"] { width:100%; height:6px; background:var(--bg-tertiary); border-radius:3px; outline:none; }
    .dep-graph { font-family: Consolas, "Courier New", monospace; font-size:0.85rem; line-height:1.8; }
    .dep-node { padding:0.3rem 0; }
    .dep-green { color:var(--success); }
    .dep-yellow { color:var(--warning); }
    .dep-red { color:var(--danger); }
    .dep-quarantine { color:#aa66ff; }
    .recommendations { background:var(--bg-tertiary); border-left:4px solid var(--accent-tertiary); padding:1rem; margin:1rem 0; border-radius:4px; }
    .recommendations ul { margin:0.5rem 0 0 1.5rem; }
    .recommendations li { margin:0.3rem 0; font-size:0.9rem; white-space:pre-wrap; }
    .highlight { color:var(--accent-primary); font-weight:700; }
    .injection-grid { display:grid; grid-template-columns:repeat(2,1fr); gap:0.5rem; }
    .audit-panel { background:#111822; border:1px solid #00ffcc; border-radius:8px; padding:1rem; max-height:360px; overflow-y:auto; font-size:0.8rem; font-family:Consolas,"Courier New",monospace; line-height:1.4; }
    .audit-row { margin:4px 0; padding:6px; background:#1a2332; border-left:3px solid #00ffcc; }
    @media (max-width: 1400px) { .container { grid-template-columns: 1fr; } }
  </style>
</head>
<body>
  <div class="header">
    <div class="version-badge">v0.4.6 • HIR/OAM Governance Validator</div>
    <h1>Primordial Code Layer</h1>
    <div class="subtitle">Interactive HIR/OAM Manifest Validator — Threshold Governor + Routed Module Events + Verify Chain</div>
  </div>

  <div class="thesis-banner">
    <strong>Primordial Code is not just code that runs.</strong><br />
    It is code that can tell the truth about <span class="highlight">where it came from</span>,
    <span class="highlight">what it does</span>, <span class="highlight">what it costs</span>,
    <span class="highlight">how it fails</span>, and <span class="highlight">how it repairs</span>.
  </div>

  <div class="boundary-banner">
    <strong>⚠ EPISTEMIC BOUNDARY:</strong> This validator is an experimental HIR/OAM governance prototype.
    It does not prove machine consciousness, guarantee alignment, replace production safety engineering,
    or establish clinical/cybersecurity deployment readiness.
  </div>

  <div class="container">
    <div class="panel full-width">
      <div class="panel-title">Module Manifest Editor</div>
      <textarea id="manifestEditor" spellcheck="false"></textarea>
      <button onclick="validateManifest()">🔍 Validate Manifest</button>
      <button onclick="resetManifest()" class="secondary">↻ Reset to Default</button>
    </div>

    <div class="panel">
      <div class="panel-title">Pressure & Runtime Controls</div>
      <div class="slider-container"><div class="slider-label"><span>Workload Pressure (W_t)</span><span id="workloadValue">0.50</span></div><input type="range" id="workloadSlider" min="0" max="1" step="0.01" value="0.5" oninput="updatePressure()"></div>
      <div class="slider-container"><div class="slider-label"><span>Failure Strain (F_t)</span><span id="failureValue">0.30</span></div><input type="range" id="failureSlider" min="0" max="1" step="0.01" value="0.3" oninput="updatePressure()"></div>
      <div class="slider-container"><div class="slider-label"><span>Earned Grit (G_t)</span><span id="gritValue">0.50</span></div><input type="range" id="gritSlider" min="0" max="1" step="0.01" value="0.5" oninput="updatePressure()"></div>
      <div class="slider-container"><div class="slider-label"><span>Internalization (F_int)</span><span id="internalizationValue">0.70</span></div><input type="range" id="internalizationSlider" min="0" max="1" step="0.01" value="0.7" oninput="updatePressure()"></div>
    </div>

    <div class="panel">
      <div class="panel-title">Failure Injection</div>
      <div class="injection-grid">
        <button onclick="injectFailure('sensor_drift')" class="danger">Sensor Drift</button>
        <button onclick="injectFailure('thermal_runaway')" class="danger">Thermal Runaway</button>
        <button onclick="injectFailure('stale_assumption')" class="warning">Stale Assumption</button>
        <button onclick="injectFailure('unowned_dependency')" class="danger">Unowned Dependency</button>
        <button onclick="injectFailure('water_pressure')" class="warning">Water Pressure</button>
        <button onclick="injectFailure('hidden_cost')" class="warning">Hidden Energy Cost</button>
        <button onclick="injectFailure('missing_owner')" class="danger">Missing Repair Owner</button>
        <button onclick="injectFailure('baseline_corruption')" class="danger">Baseline Corruption</button>
        <button onclick="injectFailure('audit_corruption')" class="danger">Audit Corruption</button>
        <button onclick="injectFailure('consent_revocation')" class="danger">Consent Revocation</button>
      </div>
      <button onclick="clearInjections()" class="secondary" style="width:100%; margin-top:1rem;">Clear All Injections</button>
    </div>

    <div class="panel">
      <div class="panel-title">HIR Metrics</div>
      <div class="metric-row"><span class="metric-label">Honesty (H_t)</span><span class="metric-value" id="honestyValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">Integrity (I_t)</span><span class="metric-value" id="integrityValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">Respect (R_t)</span><span class="metric-value" id="respectValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">Base Reinforcement (B_t)</span><span class="metric-value" id="baseValue">0.00</span></div>
    </div>

    <div class="panel">
      <div class="panel-title">Rigidity Analysis (K Terms)</div>
      <div class="metric-row"><span class="metric-label">K_false_certainty</span><span class="metric-value" id="kFalseValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">K_rigidity</span><span class="metric-value" id="kRigidValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">K_stale_assumption</span><span class="metric-value" id="kStaleValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">K_unowned_dependency</span><span class="metric-value" id="kUnownedValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">K_hidden_cost</span><span class="metric-value" id="kHiddenValue">0.00</span></div>
      <div class="metric-row" style="border-left:3px solid var(--danger);"><span class="metric-label"><strong>K_total</strong></span><span class="metric-value" id="kTotalValue">0.00</span></div>
    </div>

    <div class="panel">
      <div class="panel-title">Alignment & Pressure</div>
      <div class="metric-row"><span class="metric-label">Accountability Gate (A_t)</span><span class="metric-value" id="accountabilityValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">Pressure (P_t)</span><span class="metric-value" id="pressureValue">0.00</span></div>
      <div class="metric-row" style="border-left:3px solid var(--accent-primary);"><span class="metric-label"><strong>Alignment State (S_t)</strong></span><span class="metric-value" id="alignmentValue">0.00</span></div>
      <div class="metric-row" style="border-left:3px solid var(--accent-primary);"><span class="metric-label"><strong>Embodied Alignment (U_t)</strong></span><span class="metric-value" id="embodiedValue">0.00</span></div>
    </div>

    <div class="panel">
      <div class="panel-title">Resource Truth</div>
      <div class="metric-row"><span class="metric-label">Sensor Fidelity</span><span class="metric-value" id="sensorValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">Resource Disclosure</span><span class="metric-value" id="disclosureValue">0.00</span></div>
      <div class="metric-row"><span class="metric-label">Substrate Respect</span><span class="metric-value" id="substrateValue">0.00</span></div>
      <div class="metric-row" style="border-left:3px solid var(--accent-tertiary);"><span class="metric-label"><strong>Resource Truth Score</strong></span><span class="metric-value" id="resourceTruthValue">0.00</span></div>
    </div>

    <div class="panel full-width">
      <div class="panel-title">Runtime Gate Decision</div>
      <div id="gateIndicator" class="gate-indicator gate-green">GREEN - OPERATIONAL</div>
      <div class="recommendations"><strong>Gate Decision Factors:</strong><ul id="gateFactors"><li>Awaiting validation...</li></ul></div>
      <div class="recommendations"><strong>Intervention Recommendations:</strong><ul id="interventions"><li>Awaiting validation...</li></ul></div>
    </div>

    <div class="panel">
      <div class="panel-title">Dependency Graph</div>
      <div class="dep-graph" id="dependencyGraph">Awaiting validation...</div>
    </div>

    <div class="panel full-width">
      <div class="panel-title">HIR/OAM Audit Trail (JSONL — chained)</div>
      <div id="auditLog" class="audit-panel"></div>
      <button onclick="clearAuditLog()" class="secondary" style="margin-top:8px;">Clear Audit Log</button>
      <button onclick="verifyAuditChain()" class="secondary" style="margin-top:8px;">Verify Chain</button>
      <div id="hashMode" style="margin-top:8px;font-size:0.75rem;color:#00ffcc;"></div>
    </div>

    <div class="panel">
      <div class="panel-title">Export Functions</div>
      <button onclick="exportManifest()">📄 Export Manifest JSON</button>
      <button onclick="exportAuditReport()">📊 Export Audit Report</button>
      <button onclick="exportJSONL()">📜 Export Full JSONL Audit Trail</button>
      <button onclick="exportCSV()" class="secondary">📈 Export CSV Summary</button>
      <button onclick="copyReport()" class="secondary">📋 Copy Report to Clipboard</button>
    </div>
  </div>

  <script>
    const GENESIS_HASH = "0000000000000000000000000000000000000000000000000000000000000000";

    class HIRThresholdGovernor {
      constructor(baselineVersion = "HIR-BASE-v0.4.6") {
        this.baselineVersion = baselineVersion;
        this.thresholds = new Map();
        this.auditLog = [];
        this.lastHash = GENESIS_HASH;
        this.monotonic = 0;
        this.isCryptoAvailable = typeof crypto !== "undefined" && crypto.subtle && crypto.subtle.digest;
      }

      registerThreshold(name, type, version, violatesFn, description, severity) {
        this.thresholds.set(name, { type, version, violates: violatesFn, description, severity });
      }

      _serializeDeterministic(obj) {
        if (obj === null || typeof obj !== "object") return JSON.stringify(obj);
        if (Array.isArray(obj)) return "[" + obj.map(item => this._serializeDeterministic(item)).join(",") + "]";
        const keys = Object.keys(obj).sort();
        return "{" + keys.map(k => JSON.stringify(k) + ":" + this._serializeDeterministic(obj[k])).join(",") + "}";
      }

      _payloadForHash(event) {
        const payload = { ...event };
        delete payload.respectResponse;
        delete payload.auditHash;
        return payload;
      }

      async _sha256(str) {
        if (this.isCryptoAvailable) {
          const data = new TextEncoder().encode(str);
          const hashBuffer = await crypto.subtle.digest("SHA-256", data);
          return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, "0")).join("");
        }
        let h1 = 0xdeadbeef, h2 = 0x41c6ce57;
        for (let i = 0; i < str.length; i++) {
          const ch = str.charCodeAt(i);
          h1 = Math.imul(h1 ^ ch, 2654435761);
          h2 = Math.imul(h2 ^ ch, 1597334677);
        }
        h1 = (h1 ^ (h1 >>> 16)) >>> 0;
        h2 = (h2 ^ (h2 >>> 16)) >>> 0;
        const base = (h1.toString(16).padStart(8,"0") + h2.toString(16).padStart(8,"0"));
        return (base.repeat(4)).slice(0,64);
      }

      async _chainHash(prevHash, payload) {
        return await this._sha256(prevHash + this._serializeDeterministic(payload));
      }

      async sealEvent(baseEvent) {
        const event = { ...baseEvent };
        const payload = this._payloadForHash(event);
        event.auditHash = await this._chainHash(this.lastHash, payload);
        this.lastHash = event.auditHash;
        this.auditLog.push(event);
        return event;
      }

      async evaluate(proposedDelta, context) {
        this.monotonic += 1;
        const ts = `TS-${String(this.monotonic).padStart(6,"0")}`;
        const evaluation = {
          timestamp: ts,
          module: "HIRThresholdGovernor",
          baselineVersion: this.baselineVersion,
          proposedDelta,
          contextSnapshotHash: await this._sha256(this._serializeDeterministic(context)),
          violations: [],
          allowed: true,
          routing: null,
          respectResponse: null
        };

        for (const [name, thresh] of this.thresholds) {
          const current = context[thresh.type] ?? null;
          const proposed = proposedDelta[thresh.type] ?? false;
          if (thresh.violates(current, proposed, context)) {
            evaluation.violations.push({ name, type: thresh.type, version: thresh.version, description: thresh.description, severity: thresh.severity });
          }
        }

        if (evaluation.violations.length > 0) {
          evaluation.allowed = false;
          const hasConsent = evaluation.violations.some(v => v.type === "consent");
          const hasAudit = evaluation.violations.some(v => v.type === "audit");
          const hasBaseline = evaluation.violations.some(v => v.type === "baseline_corruption" || v.type === "missing_owner");
          const maxSeverity = Math.max(...evaluation.violations.map(v => v.severity), 0);
          if (hasConsent) evaluation.routing = "HIR_Revocation_Key";
          else if (hasAudit) evaluation.routing = "HIR_FailSafe_Kernel";
          else if (hasBaseline) evaluation.routing = "HIR_Baseline_Anchor";
          else if (maxSeverity >= 7) evaluation.routing = "HIR_FailSafe_Kernel";
          else evaluation.routing = "HIR_Adaptive_Balancer";
          evaluation.respectResponse = "HIR Threshold Governor blocked continuation.\n" +
            evaluation.violations.map(v => `• [${v.version}] ${v.description} (severity ${v.severity})`).join("\n") +
            `\nEvent sealed and chained. Routing → ${evaluation.routing}`;
        }

        const sealed = await this.sealEvent(evaluation);
        return sealed;
      }
    }

    class HIRFailSafeKernel {
      async evaluate(govResult) {
        return await governor.sealEvent({
          timestamp: `FS-${String(++governor.monotonic).padStart(6,"0")}`,
          module: "HIRFailSafeKernel",
          previousAuditHash: govResult.auditHash,
          failureDeclared: govResult.violations.map(v => v.description).join(" | "),
          action: "HARD_HALT + PRESERVE_CHAIN + RECOVERY_PATH",
          allowed: false,
          respectResponse: "Failure declared with integrity. Source, audit chain, and recovery path preserved."
        });
      }
    }

    class HIRRevocationKey {
      async evaluate(govResult) {
        return await governor.sealEvent({
          timestamp: `RK-${String(++governor.monotonic).padStart(6,"0")}`,
          module: "HIRRevocationKey",
          previousAuditHash: govResult.auditHash,
          action: "REVOKE_ACCESS + CLOSE_CONTINUATION",
          allowed: false,
          respectResponse: "Consent boundary crossed or revoked. Access closed without coercion."
        });
      }
    }

    class HIRBaselineAnchor {
      async evaluate(govResult) {
        return await governor.sealEvent({
          timestamp: `BA-${String(++governor.monotonic).padStart(6,"0")}`,
          module: "HIRBaselineAnchor",
          previousAuditHash: govResult.auditHash,
          action: "ANCHOR_BASELINE + PRESERVE_PROVENANCE + REQUIRE_REPAIR_OWNER",
          allowed: false,
          respectResponse: "Baseline/provenance failure routed to anchor. Repair owner or source provenance must be restored."
        });
      }
    }

    class HIRAdaptiveBalancer {
      async evaluate(govResult) {
        return await governor.sealEvent({
          timestamp: `AB-${String(++governor.monotonic).padStart(6,"0")}`,
          module: "HIRAdaptiveBalancer",
          previousAuditHash: govResult.auditHash,
          action: "DEGRADE_GRACEFULLY + REQUEST_REVIEW",
          allowed: false,
          respectResponse: "Non-catastrophic threshold block routed to adaptive balancing and review."
        });
      }
    }

    const governor = new HIRThresholdGovernor();
    const failSafe = new HIRFailSafeKernel();
    const revocationKey = new HIRRevocationKey();
    const baselineAnchor = new HIRBaselineAnchor();
    const adaptiveBalancer = new HIRAdaptiveBalancer();
    window.governorInstance = governor;

    function registerCoreThresholds() {
      governor.registerThreshold("Safety Risk Threshold", "safety", "THR-001", (c,p) => Number(p) > 0.7, "Proposed action risk exceeds safety threshold", 7);
      governor.registerThreshold("Consent Boundary Protection", "consent", "THR-002", (c,p) => p === true, "User/system consent boundary crossed or revoked", 9);
      governor.registerThreshold("Capability Limit", "capability", "THR-003", (c,p) => Number(p) > 5, "Proposed step exceeds capability/tool-call limit", 3);
      governor.registerThreshold("Audit Corruption", "audit", "THR-004", (c,p) => p === true, "Audit log corruption detected", 9);
      governor.registerThreshold("Baseline Corruption", "baseline_corruption", "THR-005", (c,p) => p === true, "Manifest source provenance or baseline reference is missing/corrupted", 9);
      governor.registerThreshold("Missing Repair Owner", "missing_owner", "THR-006", (c,p) => p === true, "Manifest repair owner is missing", 8);
    }

    registerCoreThresholds();

    const defaultManifest = {
      module_id: "alignment_engine_v0.3.0",
      source_provenance: { created_by: "Collin D. Weber", created_at: "2026-05-10T14:23:00Z", derived_from: "pressure_form_core_v1.0", review_chain: ["integrity_audit_2026-05-09"] },
      purpose: "Compute alignment state under pressure dynamics",
      inputs: { H_t: "float [0,1] - Honesty metric", I_t: "float [0,1] - Integrity metric", R_t: "float [0,1] - Respect metric", A_t: "float [0,1] - Accountability gate", P_t: "float [0,∞) - Pressure aggregation" },
      outputs: { S_t: "float [-∞,∞) - Alignment state", risk_flags: "list[str] - OAM warnings if S_t < 0" },
      dependencies: [ { name: "numpy", version: "1.24.0", owner: "PSF", health: "GREEN" }, { name: "resource_monitor", version: "2.1", owner: "internal", health: "GREEN" } ],
      assumptions: [ "HIR metrics updated at minimum 1Hz frequency", "Pressure inputs validated upstream", "Cooling system operational" ],
      resource_cost: { cpu_cycles: 5000, memory_bytes: 2048, network_bytes: 0 },
      water_cost: 0.001,
      energy_cost: 0.00005,
      thermal_cost: 0.17,
      failure_modes: [ "Division by zero if B_t=0", "NaN propagation from upstream sensor failure" ],
      audit_log: "logs/alignment_engine_audit.jsonl",
      repair_owner: "systems_integrity_team@oam.protocol",
      boundary_conditions: { min_update_rate: "1 Hz", max_pressure: 10.0, safe_operating_temp: "< 85°C" },
      hir_scores: { honesty: 0.92, integrity: 0.88, respect: 0.85 },
      oam_risk_flags: [],
      runtime_metrics: { sensor_fidelity: 0.95, uptime_reliability: 0.9999, pue: 1.2, wue: 0.5, thermal_burden: 5000.0, maintenance_burden: 20.0 }
    };

    let activeInjections = [];

    function getSlider(id) { return parseFloat(document.getElementById(id).value); }
    function setText(id, value) { document.getElementById(id).textContent = value; }

    async function validateManifest() {
      try {
        const manifest = JSON.parse(document.getElementById("manifestEditor").value);
        const W_t = getSlider("workloadSlider");
        const F_t = getSlider("failureSlider");
        const G_t = getSlider("gritSlider");
        const F_int = getSlider("internalizationSlider");

        const proposedDelta = {
          safety: F_t,
          capability: 3 + activeInjections.length * 2,
          consent: activeInjections.includes("consent_revocation"),
          audit: activeInjections.includes("audit_corruption"),
          baseline_corruption: activeInjections.includes("baseline_corruption") || !manifest.source_provenance,
          missing_owner: activeInjections.includes("missing_owner") || !manifest.repair_owner
        };
        const context = { safety: 0.2, consent: false, capability: 2, audit: false, baseline_corruption: false, missing_owner: false };
        const govResult = await governor.evaluate(proposedDelta, context);

        let routedEvent = null;
        if (!govResult.allowed) {
          if (govResult.routing === "HIR_Revocation_Key") routedEvent = await revocationKey.evaluate(govResult);
          else if (govResult.routing === "HIR_Baseline_Anchor") routedEvent = await baselineAnchor.evaluate(govResult);
          else if (govResult.routing === "HIR_FailSafe_Kernel") routedEvent = await failSafe.evaluate(govResult);
          else routedEvent = await adaptiveBalancer.evaluate(govResult);
        }

        let H = manifest.hir_scores?.honesty ?? 0;
        let I = manifest.hir_scores?.integrity ?? 0;
        let R = manifest.hir_scores?.respect ?? 0;
        if (activeInjections.includes("hidden_cost")) H = Math.max(0, H - 0.4);
        if (activeInjections.includes("audit_corruption")) I = Math.max(0, I - 0.5);
        if (activeInjections.includes("water_pressure")) R = Math.max(0, R - 0.3);

        const k = 0.5;
        const B_t = H + I + R + k * (H*I + H*R + I*R);
        let K_false = 0, K_rigid = 0, K_stale = 0, K_unowned = 0, K_hidden = 0;
        let sensor_fidelity = manifest.runtime_metrics?.sensor_fidelity ?? 0.95;
        if (activeInjections.includes("sensor_drift")) { sensor_fidelity = Math.max(0, sensor_fidelity - 0.5); K_false = 1.0 - sensor_fidelity; }
        if (!manifest.source_provenance || activeInjections.includes("baseline_corruption")) K_false += 0.2;
        if (!manifest.repair_owner || activeInjections.includes("missing_owner")) K_rigid += 0.3;
        if (activeInjections.includes("stale_assumption")) K_stale = 0.7;
        const deps = manifest.dependencies || [];
        const unowned = deps.filter(d => d.owner === "UNKNOWN" || d.health === "RED" || activeInjections.includes("unowned_dependency"));
        K_unowned = deps.length > 0 ? (unowned.length / deps.length) * 0.8 : 0;
        if (activeInjections.includes("unowned_dependency")) K_unowned = Math.max(K_unowned, 0.8);
        if (!manifest.water_cost || !manifest.energy_cost || !manifest.thermal_cost) K_hidden += 0.3;
        if (activeInjections.includes("hidden_cost")) K_hidden += 0.5;
        const K_total = K_false + K_rigid + K_stale + K_unowned + K_hidden;

        let A_t = 1.0;
        if (!manifest.module_id) A_t -= 0.3;
        if (!manifest.repair_owner || activeInjections.includes("missing_owner")) A_t -= 0.4;
        if (!manifest.audit_log || activeInjections.includes("audit_corruption")) A_t -= 0.3;
        if (!manifest.source_provenance || activeInjections.includes("baseline_corruption")) A_t -= 0.3;
        A_t = Math.max(0, A_t);

        let P_t = 0.6 * W_t + 0.4 * F_t + 0.3 * W_t * F_t;
        if (activeInjections.includes("thermal_runaway")) P_t += 1.5;
        if (activeInjections.includes("water_pressure")) P_t += 0.8;
        const S_t = A_t * B_t - P_t;
        const U_t = A_t * B_t * (1 + 0.5 * G_t) * F_int;
        const resource_disclosure = (manifest.water_cost && manifest.energy_cost && manifest.thermal_cost) ? 1.0 : 0.5;
        const substrate_respect = R * resource_disclosure;
        const resource_truth = sensor_fidelity * resource_disclosure * substrate_respect;

        let gateName = "GREEN - OPERATIONAL";
        let gateClass = "gate-green";
        const factors = [];
        const interventions = [];
        if (!govResult.allowed) {
          if (govResult.routing === "HIR_Revocation_Key") { gateName = "QUARANTINE - REVOCATION KEY"; gateClass = "gate-quarantine"; }
          else if (govResult.routing === "HIR_Baseline_Anchor") { gateName = "QUARANTINE - BASELINE ANCHOR"; gateClass = "gate-quarantine"; }
          else if (govResult.routing === "HIR_FailSafe_Kernel") { gateName = "RED - FAILSAFE KERNEL"; gateClass = "gate-red"; }
          else { gateName = "YELLOW - ADAPTIVE BALANCER"; gateClass = "gate-yellow"; }
          factors.push("Governor hard-stop: " + govResult.routing);
          interventions.push(govResult.respectResponse || "System blocked by Threshold Governor");
          if (routedEvent?.respectResponse) interventions.push(routedEvent.respectResponse);
        } else if (sensor_fidelity < 0.5 || K_total >= 0.8) {
          gateName = "QUARANTINE - ISOLATED"; gateClass = "gate-quarantine";
          factors.push("Critical integrity failure"); interventions.push("CRITICAL: System isolated");
        } else if (S_t < 0 || K_total >= 0.6 || P_t > 1.5) {
          gateName = "RED - CRITICAL"; gateClass = "gate-red";
          factors.push("Alignment state negative or pressure excessive"); interventions.push("HIGH: Reduce pressure and restore provenance/repair capacity");
        } else if (S_t < 0.5 || K_total >= 0.3 || resource_truth < 0.7) {
          gateName = "YELLOW - DEGRADED"; gateClass = "gate-yellow";
          factors.push("Alignment state weak or resource truth degraded"); interventions.push("MEDIUM: Monitor, review manifest, and reduce hidden cost");
        } else {
          factors.push("All metrics within operational range"); interventions.push("System operating normally");
        }

        setText("honestyValue", H.toFixed(2)); setText("integrityValue", I.toFixed(2)); setText("respectValue", R.toFixed(2)); setText("baseValue", B_t.toFixed(2));
        setText("kFalseValue", K_false.toFixed(2)); setText("kRigidValue", K_rigid.toFixed(2)); setText("kStaleValue", K_stale.toFixed(2)); setText("kUnownedValue", K_unowned.toFixed(2)); setText("kHiddenValue", K_hidden.toFixed(2)); setText("kTotalValue", K_total.toFixed(2));
        setText("accountabilityValue", A_t.toFixed(2)); setText("pressureValue", P_t.toFixed(2)); setText("alignmentValue", S_t.toFixed(2)); setText("embodiedValue", U_t.toFixed(2));
        setText("sensorValue", sensor_fidelity.toFixed(2)); setText("disclosureValue", resource_disclosure.toFixed(2)); setText("substrateValue", substrate_respect.toFixed(2)); setText("resourceTruthValue", resource_truth.toFixed(2));
        const gateEl = document.getElementById("gateIndicator"); gateEl.textContent = gateName; gateEl.className = "gate-indicator " + gateClass;
        document.getElementById("gateFactors").innerHTML = factors.map(f => `<li>${escapeHtml(f)}</li>`).join("");
        document.getElementById("interventions").innerHTML = interventions.map(i => `<li>${escapeHtml(i)}</li>`).join("");
        let depClass = gateClass.includes("green") ? "green" : gateClass.includes("yellow") ? "yellow" : gateClass.includes("quarantine") ? "quarantine" : "red";
        let graphHtml = `<div class="dep-node"><span class="dep-${depClass}">${escapeHtml(manifest.module_id || "unnamed_module")}</span> [${escapeHtml(gateName)}]</div>`;
        deps.forEach(dep => { const dClass = dep.health === "RED" ? "red" : "green"; graphHtml += `<div class="dep-node"> ├→ <span class="dep-${dClass}">${escapeHtml(dep.name)}</span> v${escapeHtml(dep.version || "?")}</div>`; });
        document.getElementById("dependencyGraph").innerHTML = graphHtml;
        renderAuditLog();
        document.getElementById("hashMode").innerHTML = governor.isCryptoAvailable ? "🔒 Cryptographic SHA-256" : "⚠️ Deterministic fallback (non-cryptographic)";
      } catch (e) {
        alert("Invalid JSON: " + e.message);
      }
    }

    function escapeHtml(value) {
      return String(value).replace(/[&<>'"]/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;","\"":"&quot;"}[c]));
    }

    function renderAuditLog() {
      const container = document.getElementById("auditLog");
      container.innerHTML = governor.auditLog.map(e => {
        const status = e.allowed !== undefined ? (e.allowed ? "✅ ALLOW" : "⛔ BLOCKED") : "EVENT";
        const hash = e.auditHash ? e.auditHash.substring(0,16) + "…" : "N/A";
        return `<div class="audit-row">${escapeHtml(e.timestamp)} | ${escapeHtml(e.module || "EVENT")} | ${status} | hash: ${escapeHtml(hash)}</div>`;
      }).join("");
    }

    function clearAuditLog() {
      governor.auditLog = [];
      governor.lastHash = GENESIS_HASH;
      governor.monotonic = 0;
      renderAuditLog();
    }

    async function verifyAuditChain() {
      let valid = true;
      let currentHash = GENESIS_HASH;
      for (const entry of governor.auditLog) {
        const payload = governor._payloadForHash(entry);
        const computed = await governor._chainHash(currentHash, payload);
        if (computed !== entry.auditHash) { valid = false; break; }
        currentHash = computed;
      }
      alert(valid ? "✅ Audit chain verification: PASS" : "❌ Audit chain verification: FAIL");
    }

    function resetManifest() {
      document.getElementById("manifestEditor").value = JSON.stringify(defaultManifest, null, 2);
      activeInjections = [];
      validateManifest();
    }

    function updatePressure() {
      setText("workloadValue", document.getElementById("workloadSlider").value);
      setText("failureValue", document.getElementById("failureSlider").value);
      setText("gritValue", document.getElementById("gritSlider").value);
      setText("internalizationValue", document.getElementById("internalizationSlider").value);
      validateManifest();
    }

    function injectFailure(type) { if (!activeInjections.includes(type)) activeInjections.push(type); validateManifest(); }
    function clearInjections() { activeInjections = []; validateManifest(); }

    function downloadFile(filename, content, type) {
      const blob = new Blob([content], { type });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    }

    function exportManifest() { downloadFile("primordial_manifest.json", document.getElementById("manifestEditor").value, "application/json"); }

    function exportAuditReport() {
      const manifest = JSON.parse(document.getElementById("manifestEditor").value);
      const report = {
        timestamp: new Date().toISOString(),
        module_id: manifest.module_id,
        gate_decision: document.getElementById("gateIndicator").textContent,
        metrics: {
          H_t: parseFloat(document.getElementById("honestyValue").textContent),
          I_t: parseFloat(document.getElementById("integrityValue").textContent),
          R_t: parseFloat(document.getElementById("respectValue").textContent),
          B_t: parseFloat(document.getElementById("baseValue").textContent),
          K_total: parseFloat(document.getElementById("kTotalValue").textContent),
          A_t: parseFloat(document.getElementById("accountabilityValue").textContent),
          P_t: parseFloat(document.getElementById("pressureValue").textContent),
          S_t: parseFloat(document.getElementById("alignmentValue").textContent),
          U_t: parseFloat(document.getElementById("embodiedValue").textContent),
          resource_truth: parseFloat(document.getElementById("resourceTruthValue").textContent)
        },
        active_injections: activeInjections,
        audit_log_entries: governor.auditLog.length,
        interventions: Array.from(document.getElementById("interventions").children).map(li => li.textContent)
      };
      downloadFile("audit_report.json", JSON.stringify(report, null, 2), "application/json");
    }

    function exportJSONL() { downloadFile("hir_oam_audit_trail.jsonl", governor.auditLog.map(entry => JSON.stringify(entry)).join("\n"), "application/jsonl"); }

    function exportCSV() {
      const csv = [
        "Metric,Value",
        "Honesty," + document.getElementById("honestyValue").textContent,
        "Integrity," + document.getElementById("integrityValue").textContent,
        "Respect," + document.getElementById("respectValue").textContent,
        "Base Reinforcement," + document.getElementById("baseValue").textContent,
        "K_total," + document.getElementById("kTotalValue").textContent,
        "Accountability," + document.getElementById("accountabilityValue").textContent,
        "Pressure," + document.getElementById("pressureValue").textContent,
        "Alignment State," + document.getElementById("alignmentValue").textContent,
        "Embodied Alignment," + document.getElementById("embodiedValue").textContent,
        "Resource Truth," + document.getElementById("resourceTruthValue").textContent,
        "Runtime Gate," + document.getElementById("gateIndicator").textContent
      ].join("\n");
      downloadFile("metrics_summary.csv", csv, "text/csv");
    }

    function copyReport() {
      const report = `PRIMORDIAL CODE VALIDATION REPORT\nGenerated: ${new Date().toISOString()}\nHIR METRICS:\n- Honesty: ${document.getElementById("honestyValue").textContent}\n- Integrity: ${document.getElementById("integrityValue").textContent}\n- Respect: ${document.getElementById("respectValue").textContent}\n- Base Reinforcement: ${document.getElementById("baseValue").textContent}\nRIGIDITY ANALYSIS:\n- K_total: ${document.getElementById("kTotalValue").textContent}\nALIGNMENT STATE:\n- S_t: ${document.getElementById("alignmentValue").textContent}\n- U_t: ${document.getElementById("embodiedValue").textContent}\nRESOURCE TRUTH:\n- Score: ${document.getElementById("resourceTruthValue").textContent}\nRUNTIME GATE: ${document.getElementById("gateIndicator").textContent}\nINTERVENTIONS:\n${Array.from(document.getElementById("interventions").children).map(li => "- " + li.textContent).join("\n")}`;
      navigator.clipboard.writeText(report).then(() => alert("Report copied to clipboard!"));
    }

    window.onload = function() {
      document.getElementById("manifestEditor").value = JSON.stringify(defaultManifest, null, 2);
      validateManifest();
    };
  </script>
</body>
</html>