-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfinalize_hook.tsx
More file actions
executable file
·204 lines (176 loc) · 7.63 KB
/
Copy pathfinalize_hook.tsx
File metadata and controls
executable file
·204 lines (176 loc) · 7.63 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
// finalize-shim.js
// Shim to finalize sha256-genesis-rehashed entropy-ordered assembly + sha128 + md5 backtrace.
// Drop this file into your project and include it after your main orchestrator script.
/* global md5, quantumEditor */
(function(window){
const CDN_MD5 = 'https://cdnjs.cloudflare.com/ajax/libs/blueimp-md5/2.19.0/js/md5.min.js';
// Load blueimp-md5 if not present
async function ensureMD5() {
if (typeof window.md5 === 'function') return;
return new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = CDN_MD5;
s.async = true;
s.onload = () => {
if (typeof window.md5 === 'function') resolve();
else reject(new Error('MD5 lib loaded but md5() missing'));
};
s.onerror = (e) => reject(new Error('Failed to load MD5 lib: ' + e));
document.head.appendChild(s);
});
}
// SHA-256 -> hex
async function sha256Hex(message) {
const enc = new TextEncoder();
const data = enc.encode(message);
const digest = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2,'0')).join('');
}
// SHA-128 (first 16 bytes of SHA-256, presented as 32 hex chars)
function sha128FromSha256Hex(sha256hex) {
if (!sha256hex || sha256hex.length < 32) return sha256hex;
return sha256hex.slice(0, 32); // 128 bits (16 bytes)
}
// entropy approximation: popcount / max bits
function entropyFromHex(hex) {
let bits = 0;
for (let i = 0; i < hex.length; i += 2) {
const byte = parseInt(hex.slice(i, i+2), 16) || 0;
// popcount
let x = byte;
x = x - ((x >> 1) & 0x55);
x = (x & 0x33) + ((x >> 2) & 0x33);
bits += (((x + (x >> 4)) & 0x0F) * 1);
}
const maxBits = (hex.length/2) * 8;
return maxBits ? bits / maxBits : 0;
}
// safe JSON read helpers
function readJSON(key, fallback) {
try { return JSON.parse(localStorage.getItem(key) || 'null') || fallback; }
catch(e){ return fallback; }
}
// Convert hex string to BigInt for tiebreaker ordering (returns Number if small)
function hexToBigInt(hex) {
try { return BigInt('0x' + hex); }
catch(e) {
// fallback: use numeric portion
return Number.parseInt(hex.slice(0, 15), 16) || 0;
}
}
// Assemble final HTML document from ordered fragments
function buildHtmlFromFragments(meta, fragments) {
const { genesis } = meta || {};
const header = `<!-- Generated by Quantum Fractal AI-Editor shim -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Quantum-Assembly - final answer</title>
<!-- genesis: ${genesis || 'unknown'} -->
</head>
<body>
<!-- Assembled fragments below -->\n`;
const footer = `\n</body>\n</html>`;
// Concatenate JS fragments as <script> blocks; preserve agent provenance as comment
const bodyParts = fragments.map((f, i) => {
const metaLine = `/* FRAG ${i+1} - agent:${f.agent} model:${f.model} entropy:${f.entropy.toFixed(4)} sha128:${f.sha128} md5:${f.md5} */`;
// ensure candidate is safe text
const code = (f.candidate || '').replace(/\u0000/g, '');
return `<section id="frag-${i+1}">\n<!-- ${metaLine} -->\n<pre style="display:none;">${metaLine}</pre>\n<script type="text/javascript">\n// ${metaLine}\n${code}\n</script>\n</section>`;
}).join('\n\n');
return header + bodyParts + footer;
}
// Finalizer: fetch fragments, compute hashes/scores, sort, assemble, inject / download
async function finalizeAndInject(opts = {}) {
opts = Object.assign({ maxFragments: 8, injectToEditor: true, openNewTab: true }, opts);
await ensureMD5();
// Read stored orchestrator data
const genesis = localStorage.getItem('quantum_genesisHash') || null;
const realstream = readJSON('quantum_realstream', []);
const originFragments = readJSON('quantum_origin_fragments', {});
if (!realstream || !Array.isArray(realstream) || realstream.length === 0) {
console.warn('quantum-shim: no fragments found in localStorage: quantum_realstream');
// still allow user to proceed
}
// Compute per-fragment fingerprints and combined score
const computed = [];
for (let frag of realstream) {
const candidate = frag.candidate || '';
// compute sha256 of candidate
const s256 = await sha256Hex(candidate);
const s128 = sha128FromSha256Hex(s256);
const md5hash = (typeof window.md5 === 'function') ? window.md5(candidate) : ('md5-unavailable');
const entropy = entropyFromHex(s256);
// small backtrace score: combine entropy + normalized numeric sha128 + md5
const sha128num = Number((hexToBigInt(s128) % BigInt(Number.MAX_SAFE_INTEGER)).toString());
const md5num = Number(parseInt((md5hash || '').slice(0,12) || '0', 16) || 0);
// combined score: entropy primary, then sha128num, then md5num (descending)
const combined = entropy * 1e6 + (sha128num % 1000000) * 0.5 + (md5num % 1000000) * 0.1;
computed.push(Object.assign({}, frag, {
sha256: s256,
sha128: s128,
md5: md5hash,
entropy,
combined
}));
}
// Sort by combined (desc). This implements "sha256-genesis-rehashed entropy ordered sort of sha128 + md5 backtraced"
computed.sort((a,b) => {
if (b.combined !== a.combined) return b.combined - a.combined;
// final tie-breaker deterministic by sha256 hex compare
return (b.sha256 || '').localeCompare(a.sha256 || '');
});
// Limit top fragments
const top = computed.slice(0, Math.max(1, Math.min(opts.maxFragments, computed.length)));
// Attempt to attach genesis/origin metadata to each fragment for provenance
for (let f of top) {
const originMeta = originFragments[f.agent] || null;
f.originMeta = originMeta;
}
// Build final HTML
const finalHtml = buildHtmlFromFragments({ genesis }, top);
// Inject to editor if available
if (opts.injectToEditor && window.quantumEditor && typeof quantumEditor.setContent === 'function') {
try {
quantumEditor.setContent(finalHtml, 'html');
console.log('quantum-shim: injected assembled HTML into quantumEditor.');
} catch(e) {
console.warn('quantum-shim: failed to inject into quantumEditor:', e);
}
}
// Open new tab
if (opts.openNewTab) {
const blob = new Blob([finalHtml], {type: 'text/html'});
const url = URL.createObjectURL(blob);
window.open(url, '_blank');
}
// Offer download
const filename = `quantum-assembly-${(new Date()).toISOString().replace(/[:.]/g,'-')}.html`;
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([finalHtml], {type:'text/html'}));
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
a.remove();
// persist final assembly pointer
localStorage.setItem('quantum_final_assembly', JSON.stringify({
ts: Date.now(),
genesis,
topFragments: top.map(f => ({agent:f.agent, model:f.model, entropy:f.entropy, sha128:f.sha128, md5:f.md5}))
}));
console.log('quantum-shim: finalize complete - assembled fragments:', top.length);
return { assembled: top, html: finalHtml };
}
// Expose API
window.quantumShim = {
finalizeAndInject,
_internal: {
ensureMD5, sha256Hex, sha128FromSha256Hex, entropyFromHex
}
};
// Auto-detect: if fragments already present and user wants auto-run, don't run automatically by default.
console.log('quantum-shim loaded. Call window.quantumShim.finalizeAndInject(opts) to build & inject the assembled HTML.');
})(window);