/* Oracle7 Workbench - page logic. Talks only to the local server that served it (127.0.0.1). */ (function () { "use strict"; const $ = id => document.getElementById(id); const esc = s => String(s == null ? "" : s).replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); const newId = () => (crypto.getRandomValues(new Uint32Array(2)).join("") + "abcdefgh").replace(/[^0-9a-z]/g, "").slice(0, 16); const store = { get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }, set(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* private mode */ } } }; // the conversation id is also the core's session: reopening a conversation carries on its context let SID = /^[a-z0-9]{6,40}$/.test(store.get("o7wb.conv") || "") ? store.get("o7wb.conv") : newId(); store.set("o7wb.conv", SID); const turns = []; let head = "", explorer = null, specData = null, pendingExamples = [], filmTurns = new Set(), filmSeen = new Set(); async function api(path, body) { const r = await fetch(path, body === undefined ? {} : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); const j = await r.json().catch(() => ({ error: "bad reply" })); if (!r.ok) throw new Error(j.error || ("HTTP " + r.status)); return j; } // ------------------------------------------------------------------ log pane function log(kind, text, cls) { const li = document.createElement("li"); const t = new Date().toTimeString().slice(0, 8); li.innerHTML = `${esc(kind)}${esc(text)}`; const ol = $("log"); ol.appendChild(li); while (ol.children.length > 400) ol.removeChild(ol.firstChild); ol.scrollTop = ol.scrollHeight; } $("log-clear").onclick = () => { $("log").innerHTML = ""; }; // ------------------------------------------------------------------ diagram try { explorer = O7Explorer($("diagram"), { mode: "improve", select: "L2", palette: { accent: 0x946d1e, lit: 0xc0602e, fresh: 0xc0602e, spec: 0x5c4416, hazard: 0xc49132, store: 0x2a3b52 }, onSelect(id) { const s = O7Explorer.data.STAGES.find(x => x.id === id); if (s) log("diagram", s.name + ": " + s.blurb); } }); } catch (e) { $("diagram").insertAdjacentHTML("beforeend", `
The diagram needs WebGL (${esc(e.message)}).
`); } document.querySelectorAll(".views [data-view]").forEach(b => b.onclick = () => { document.querySelectorAll(".views [data-view]").forEach(x => x.classList.toggle("on", x === b)); explorer && explorer.setView(b.dataset.view); }); let allLabels = false; $("labels-all").onclick = () => { allLabels = !allLabels; explorer && explorer.setShowAll(allLabels); $("labels-all").classList.toggle("on", allLabels); }; // ------------------------------------------------------------------ state async function refreshState() { const s = await api("/api/state"); head = s.head; $("f-head").textContent = "core " + String(s.head).replace("oracle_release_runtime_", ""); $("f-yours").textContent = s.yours.length + " of yours"; $("f-journal").textContent = s.journal ? "gap journal on" : "gap journal off"; $("f-journal").classList.toggle("on", s.journal); $("g-on").checked = s.journal; s.yours.forEach(id => explorer && explorer.addModule("S", "Yours: " + id)); return s; } // ------------------------------------------------------------------ ask function renderAnswer(text) { const t = String(text || ""); if (t.includes("```")) return t.split("```").map((p, i) => i % 2 ? `${esc(p.replace(/^[a-z]*\n/, ""))}` : esc(p)).join("");
const m = t.match(/^([\s\S]*?)((?:^|\n)(?:def |import |from |class )[\s\S]*)$/);
return m ? esc(m[1]) + `${esc(m[2].replace(/^\n/, ""))}` : esc(t);
}
const stepNames = tr => (tr || []).filter(x => x[1]).map(x => x[1]);
// one turn's answer, its path and its controls: used live and when a saved conversation is reopened
function renderTurn(box, t, live) {
const declined = t.status !== "answered";
box.classList.toggle("declined", declined);
box.querySelector(".a").className = "a";
box.querySelector(".a").innerHTML = renderAnswer(t.response || (declined ? "(declined)" : ""));
const lit = live && explorer ? explorer.trace(t.trace, declined) : [];
const mine = /^yours:([a-z0-9-]+)/.exec(t.path || "");
const when = t.t ? new Date(t.t * 1000).toLocaleString([], { dateStyle: "medium", timeStyle: "short" }) + " · " : "";
box.insertAdjacentHTML("beforeend", `${t.why ? `${block}
`; }).join("").replace(/\*\*(.+?)\*\*/g, "$1").replace(/`([^`]+)`/g, "$1");
let group = "All";
function renderSpecs() {
const f = $("s-find").value.trim().toLowerCase();
const items = specData.items.filter(x => (group === "All" || x.group === group) &&
(!f || (x.name + " " + x.id + " " + x.takes.join(" ")).toLowerCase().includes(f)));
const yours = group === "All" || group === "Yours" ? specData.yours.filter(x => !f || x.id.includes(f)) : [];
$("s-list").innerHTML = yours.map(x => `No specialist matches.
`); $("s-list").querySelectorAll("[data-id]").forEach(el => el.onclick = () => openCard(el.dataset.id)); $("s-list").querySelectorAll("[data-mine]").forEach(el => el.onclick = () => { showTab("build"); openEditor(el.dataset.mine); }); } async function openCard(id) { const x = specData.items.find(i => i.id === id); const c = $("s-card"); c.hidden = false; let body = ""; if (x.card) { try { body = md((await api("/api/card?id=" + encodeURIComponent(x.card))).md); } catch (e) { body = ""; } } if (!body) body = `${x.group === "Relation readers" ? "Reads one family of Wikidata relations (" + esc(x.takes.join(", ")) + ") from the relation store and answers with the record it read, both ends with ids." : "Takes: " + esc(x.takes.join(", "))}
`; c.innerHTML = body + (x.heldout ? `Held-out exam, seen once: ${x.heldout[0]} of ${x.heldout[2]} right with it, ${x.heldout[1]} with the core alone. Admitted ${esc(x.admitted)}.
` : ""); c.scrollIntoView({ block: "nearest" }); log("card", x.name); } async function loadSpecs() { specData = await api("/api/specialists"); const counts = {}; specData.items.forEach(x => { counts[x.group] = (counts[x.group] || 0) + 1; }); const gs = [["All", specData.items.length]].concat(Object.entries(counts).sort((a, b) => b[1] - a[1])).concat([["Yours", specData.yours.length]]); $("s-groups").innerHTML = gs.map(([g, n]) => ``).join(""); $("s-groups").querySelectorAll("button").forEach(b => b.onclick = () => { group = b.dataset.g; $("s-groups").querySelectorAll("button").forEach(x => x.classList.toggle("on", x === b)); renderSpecs(); }); $("f-spec").textContent = specData.items.length + " specialists"; renderSpecs(); } $("s-find").oninput = renderSpecs; async function loadSystems() { const s = await api("/api/systems"); $("sys-about").textContent = s.about; $("sys-list").innerHTML = s.items.map(x => `${esc(x.does)}
None yet. Start one, or add the worked example.
`; $("b-list").innerHTML = rows; $("b-list").querySelectorAll("[data-id]").forEach(el => el.onclick = () => openEditor(el.dataset.id)); $("sh-list").innerHTML = specData.yours.map(x => `Build or import a specialist first.
`; $("sh-list").querySelectorAll("[data-pack]").forEach(b => b.onclick = () => pack(b.dataset.pack)); $("sh-list").querySelectorAll("[data-reg]").forEach(b => b.onclick = () => solanaRecord(b.dataset.reg, "register")); $("sh-list").querySelectorAll("[data-att]").forEach(b => b.onclick = () => solanaRecord(b.dataset.att, "attest")); $("sh-list").querySelectorAll("[data-chk]").forEach(b => b.onclick = () => solanaCheck(b.dataset.chk)); } async function openEditor(id, file) { const r = await api("/api/files?id=" + encodeURIComponent(id)); edId = id; $("b-editor").hidden = false; $("b-title").textContent = id; const st = r.status; $("b-state").className = "state " + st.state; $("b-state").textContent = st.state; const files = r.files.filter(f => !/^(verdict_|shared_verdict_|exam_log)/.test(f)); const organ = files.find(f => /^organ_/.test(f)); file = file || edFile && files.includes(edFile) && edId === id ? file || edFile : organ || files[0]; $("b-files").innerHTML = files.map(f => ``).join(""); $("b-files").querySelectorAll("button").forEach(b => b.onclick = () => openEditor(id, b.dataset.f)); edFile = file; $("b-text").value = (await api(`/api/file?id=${encodeURIComponent(id)}&name=${encodeURIComponent(file)}`)).text; renderVerdict(st.verdict); } async function save() { if (!edId) return; const r = await api("/api/file", { id: edId, name: edFile, text: $("b-text").value }); $("b-state").className = "state " + r.status.state; $("b-state").textContent = r.status.state; log("saved", `${edId}/${edFile}${r.status.state === "changed" ? " - changed after its exam: out of your model until a new held-out set passes" : ""}`, "live"); refreshState(); loadYours(); } $("b-save").onclick = save; $("b-text").addEventListener("keydown", e => { if (e.key === "Tab") { e.preventDefault(); const t = e.target, s = t.selectionStart; t.setRangeText(" ", s, t.selectionEnd, "end"); } if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); } }); function renderVerdict(v) { if (!v) { $("b-verdict").innerHTML = `No exam yet. The dev exam is free to repeat; the held-out exam uses its items once.
`; return; } const ok = c => c ? `PASS` : `FAIL`; const gain = v.with_specialist.ok - v.head.ok, wrongCap = Math.max(1, Math.floor(0.02 * v.n)); $("b-verdict").innerHTML = `| Domain | ${ok(gain >= v.gain_needed)} | ${v.with_specialist.ok}/${v.n} with it, ${v.head.ok}/${v.n} core alone: gain ${gain}, needs ${v.gain_needed} |
| No false yes | ${ok(v.with_specialist.fy <= v.head.fy)} | ${v.with_specialist.fy} must-decline answered (core: ${v.head.fy}) |
| Few wrong | ${ok(v.with_specialist.wrong <= wrongCap)} | ${v.with_specialist.wrong} answered wrong, cap ${wrongCap} |
| Stays in lane | ${ok(v.core.taken <= v.core.cap)} | takes ${v.core.taken} of ${v.core.n} general questions, cap ${v.core.cap}${v.core.examples.length ? ": " + esc(v.core.examples.slice(0, 3).join(" | ")) : ""} |
| Self | ${ok(v.self_ok)} | identity questions stay the core's |
| Budget | ${ok(v.p50_ms <= v.budget_ms)} | median ${v.p50_ms} ms, budget ${v.budget_ms} ms |
| ${esc(f.q)} | expected ${esc(f.expected)} | ${esc(f.by)}: ${esc(f.got || f.status)} |
${g.on ? "The journal is on. Ask questions and the gaps appear here." : "The journal is off."}
`; return; } $("g-list").innerHTML = `${g.turns} turns kept, ${g.declined} declined.
` + g.groups.map(gr => `Ask something first; each answer can be filmed.
`; return; } turns.forEach(t => { if (!filmSeen.has(t.n)) { filmSeen.add(t.n); filmTurns.add(t.n); } }); // new answers start ticked $("f-list").innerHTML = turns.map(t => ``).join(""); $("f-list").querySelectorAll("input").forEach(c => c.onchange = () => { c.checked ? filmTurns.add(+c.dataset.n) : filmTurns.delete(+c.dataset.n); }); } // the film shows the answer without the chat's internal markers ([ev:direct], [enwiki_...], [specialist]) const clean = t => String(t || "").replace(/\[(?:ev|vessel):[^\]]*\]\s*/g, "").replace(/\s*\[(?:enwiki|simplewiki|dbpedia)_[0-9a-f]+\]/g, "").replace(/\s*\[[a-z0-9-]+\]\s*$/, "").trim(); function wrap(ctx, text, x, y, w, lh, maxLines) { const words = String(text).split(/\s+/); let line = "", n = 0; for (const word of words) { const t = line ? line + " " + word : word; if (ctx.measureText(t).width > w && line) { ctx.fillText(line, x, y + n * lh); n++; line = word; if (n >= maxLines - 1) { line = line + " …"; break; } } else line = t; } if (line) { ctx.fillText(line, x, y + n * lh); n++; } return n; } async function record() { const sel = turns.filter(t => filmTurns.has(t.n)); if (!sel.length || !explorer || !window.MediaRecorder) { $("f-prog").textContent = !explorer ? "the diagram is not available" : "nothing selected"; return; } const W = 1280, H = 720, LW = 760, cv = document.createElement("canvas"); cv.width = W; cv.height = H; const ctx = cv.getContext("2d"), src = explorer.canvas, host = $("diagram"); // optional ElevenLabs narration + sound bed, fetched before recording starts let ac = null, dest = null, voices = [], bed = null, pics = []; if (el.on && $("el-img").checked) { const model = $("el-img-model").value, style = $("el-img-style").value.trim() || "engraved plate illustration, warm parchment and burnt orange palette, no text"; for (let i = 0; i < sel.length; i++) { $("f-prog").textContent = `illustrating ${i + 1} of ${sel.length}… (up to a minute each)`; try { pics[i] = { bmp: await createImageBitmap(new Blob([await elAudio("/api/el/image", { prompt: `${style}. Subject: ${sel[i].q}`, model })])), model }; log("image", `illustration ${i + 1} made (${model})`, "live"); } catch (e) { log("image", e.message, "no"); } } } if (el.on && ($("el-narrate").checked || $("el-sound").value.trim())) { ac = new AudioContext(); dest = ac.createMediaStreamDestination(); try { if ($("el-narrate").checked) for (let i = 0; i < sel.length; i++) { $("f-prog").textContent = `narrating ${i + 1} of ${sel.length}…`; const t = sel[i], text = `${t.q} ... ${clean(t.response).replace(/\s+/g, " ").slice(0, 700)}`; voices.push(await ac.decodeAudioData(await elAudio("/api/el/speech", { text, voice: $("el-voice").value }))); log("voice", `narration ${i + 1}: ${voices[i].duration.toFixed(1)} s`, "live"); } if ($("el-sound").value.trim()) { $("f-prog").textContent = "making the sound…"; bed = await ac.decodeAudioData(await elAudio("/api/el/sound", { prompt: $("el-sound").value.trim(), seconds: 20 })); log("voice", `sound bed ${bed.duration.toFixed(1)} s`, "live"); } } catch (e) { log("voice", e.message, "no"); $("f-prog").textContent = e.message; ac.close(); ac = null; voices = []; bed = null; } } const stream = cv.captureStream(30); if (ac) dest.stream.getAudioTracks().forEach(tr => stream.addTrack(tr)); if (bed) { const s = ac.createBufferSource(), g = ac.createGain(); s.buffer = bed; s.loop = true; g.gain.value = voices.length ? 0.16 : 0.5; s.connect(g).connect(dest); s.start(); } const type = (ac ? ["video/webm;codecs=vp9,opus", "video/webm;codecs=vp8,opus"] : []).concat(["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"]).find(t => MediaRecorder.isTypeSupported(t)); const rec = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: 6e6 }), chunks = []; rec.ondataavailable = e => e.data.size && chunks.push(e.data); const done = new Promise(r => { rec.onstop = r; }); rec.start(250); $("f-rec").disabled = true; log("film", `recording ${sel.length} answer(s)`, "live"); // film time runs on drawn frames only; a hidden tab pauses the recording (and its sound) instead of losing the segment let last = performance.now(); const tick = now => { const dt = Math.min(now - last, 50); last = now; return dt; }; const onVis = () => { if (document.hidden) { if (rec.state === "recording") rec.pause(); if (ac) ac.suspend(); $("f-prog").textContent = "paused: the tab is hidden"; log("film", "paused while the tab is hidden", ""); } else { last = performance.now(); if (rec.state === "paused") rec.resume(); if (ac) ac.resume(); } }; document.addEventListener("visibilitychange", onVis); for (let k = 0; k < sel.length; k++) { const t = sel[k], declined = t.status !== "answered"; if (pics[k]) await new Promise(resolve => { // the illustration card, labelled as a generated image const p = pics[k]; let ce = 0; const card = now => { ce += tick(now); const b = p.bmp, sc = Math.max(W / b.width, H / b.height), e = ce / 2800; ctx.drawImage(b, (W - b.width * sc * (1 + e * 0.04)) / 2, (H - b.height * sc * (1 + e * 0.04)) / 2, b.width * sc * (1 + e * 0.04), b.height * sc * (1 + e * 0.04)); const g = ctx.createLinearGradient(0, H * 0.55, 0, H); g.addColorStop(0, "rgba(21,16,13,0)"); g.addColorStop(1, "rgba(21,16,13,.82)"); ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); ctx.fillStyle = "#fffaf0"; ctx.font = "italic 34px 'EB Garamond', Georgia, serif"; wrap(ctx, t.q, 60, H - 110, W - 120, 40, 2); ctx.font = "11px 'JetBrains Mono', monospace"; ctx.fillStyle = "rgba(255,250,240,.75)"; ctx.fillText("GENERATED IMAGE · ELEVENLABS · " + p.model.toUpperCase(), 60, H - 28); if (ce < 2800) requestAnimationFrame(card); else resolve(); }; requestAnimationFrame(card); }); const lit = explorer.trace(t.trace, declined); let dur = Math.max(5, lit.length * 0.75 + 3.5) * 1000; if (voices[k]) { const s = ac.createBufferSource(); s.buffer = voices[k]; s.connect(dest); s.start(ac.currentTime + 0.4); dur = Math.max(dur, (voices[k].duration + 1.2) * 1000); } let el = 0; await new Promise(resolve => { const frame = now => { el += tick(now); ctx.fillStyle = "#f5efe1"; ctx.fillRect(0, 0, W, H); // diagram, contained in the left panel // the diagram fills the left panel: scaled up around its centre and clipped to the panel const sw = src.width, sh = src.height, s = Math.min(LW / sw, (H - 60) / sh) * 1.75, dw = sw * s, dh = sh * s, dx = (LW - dw) / 2, dy = (H - dh) / 2; ctx.save(); ctx.beginPath(); ctx.rect(0, 0, LW, H); ctx.clip(); ctx.drawImage(src, dx, dy, dw, dh); const k2 = dw / host.clientWidth; explorer.labelsOnScreen().forEach(L => { if (!/lit|layer|mine/.test(L.cls)) return; const x = dx + L.x * k2, y = dy + L.y * k2, layer = /layer/.test(L.cls), on = /lit/.test(L.cls); ctx.font = layer ? "600 13px Cinzel, Georgia, serif" : "600 12px 'JetBrains Mono', monospace"; const w = ctx.measureText(L.text).width; if (layer) { ctx.fillStyle = "#6a5a47"; ctx.fillText(L.text.toUpperCase(), x, y + 4); return; } ctx.fillStyle = on ? "#c0602e" : "rgba(250,246,236,.92)"; ctx.fillRect(x - w / 2 - 5, y - 26, w + 10, 18); ctx.fillStyle = on ? "#fffaf0" : "#9a4a20"; ctx.fillText(L.text, x - w / 2, y - 13); }); ctx.restore(); // right panel: question, answer, path ctx.fillStyle = "#efe6cf"; ctx.fillRect(LW, 0, W - LW, H); ctx.fillStyle = "rgba(21,16,13,.24)"; ctx.fillRect(LW, 0, 1, H); const X = LW + 36, RW = W - LW - 72; ctx.fillStyle = "#5c4416"; ctx.font = "700 20px Cinzel, Georgia, serif"; ctx.fillText("ORACLE", X, 58); ctx.fillStyle = "#c0602e"; ctx.fillText("7", X + ctx.measureText("ORACLE").width + 2, 58); ctx.fillStyle = "#946d1e"; ctx.font = "500 12px 'JetBrains Mono', monospace"; ctx.fillText("QUESTION", X, 104); ctx.fillStyle = "#342820"; ctx.font = "italic 24px 'EB Garamond', Georgia, serif"; let n = wrap(ctx, t.q, X, 136, RW, 30, 3); let y = 136 + n * 30 + 28; ctx.fillStyle = "#946d1e"; ctx.font = "500 12px 'JetBrains Mono', monospace"; ctx.fillText(declined ? "DECLINED" : "ANSWER", X, y); ctx.fillStyle = declined ? "#5c4416" : "#15100d"; ctx.font = "21px 'EB Garamond', Georgia, serif"; const shown = el > 900 ? clean(t.response) : ""; n = wrap(ctx, shown, X, y + 32, RW, 27, 7); y = y + 32 + Math.max(1, n) * 27 + 26; ctx.fillStyle = "#946d1e"; ctx.font = "500 12px 'JetBrains Mono', monospace"; ctx.fillText("PATH", X, y); const steps = Math.min(lit.length, Math.floor(el / 750) + 1); lit.forEach((p, i) => { ctx.fillStyle = i < steps ? "#c0602e" : "rgba(106,90,71,.45)"; ctx.font = (i < steps ? "600 " : "") + "13px 'JetBrains Mono', monospace"; if (y + 26 + i * 22 < H - 50) ctx.fillText((i + 1) + " " + p[0] + " · " + p[1], X, y + 26 + i * 22); }); ctx.fillStyle = "#6a5a47"; ctx.font = "11px 'JetBrains Mono', monospace"; ctx.fillText(`${String(head).replace("oracle_release_runtime_", "core ")} · path traced live on this machine`, X, H - 30); $("f-prog").textContent = `answer ${k + 1} of ${sel.length}`; if (el < dur) requestAnimationFrame(frame); else resolve(); }; requestAnimationFrame(frame); }); } document.removeEventListener("visibilitychange", onVis); rec.stop(); await done; $("f-rec").disabled = false; if (ac) ac.close(); const blob = new Blob(chunks, { type: "video/webm" }), url = URL.createObjectURL(blob); $("f-video").src = url; $("f-video").hidden = false; $("f-dl").href = url; $("f-dl").hidden = false; $("f-prog").textContent = `done · ${(blob.size / 1e6).toFixed(1)} MB`; log("film", `film ready (${(blob.size / 1e6).toFixed(1)} MB)`, "ok"); } $("f-rec").onclick = record; // ElevenLabs (optional): the key lives in this variable, or on this computer if "remember" is ticked const el = { on: false, key: "" }; async function elAudio(path, body) { const r = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...body, key: el.key }) }); if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || "ElevenLabs request failed"); return r.arrayBuffer(); } async function elConnect(remembered) { $("el-connect").disabled = true; try { el.key = remembered ? "" : $("el-key").value.trim(); const r = await api("/api/el/connect", { key: el.key, remember: $("el-remember").checked || remembered }); el.on = true; $("el-opts").hidden = false; $("el-forget").hidden = false; $("el-key").value = ""; $("el-key").placeholder = "connected"; $("el-voice").innerHTML = r.voices.map(v => ``).join(""); log("voice", `ElevenLabs connected · ${r.voices.length} voices${r.remembered ? " · key remembered on this computer" : " · key kept in this page only"}`, "ok"); } catch (e) { log("voice", e.message, "no"); if (!remembered) alert(e.message); } $("el-connect").disabled = false; } $("el-connect").onclick = () => elConnect(false); $("el-forget").onclick = async () => { await api("/api/el/forget", {}); el.on = false; el.key = ""; $("el-opts").hidden = true; $("el-forget").hidden = true; $("el-key").placeholder = "ElevenLabs API key"; log("voice", "ElevenLabs disconnected; key removed", "live"); }; // ------------------------------------------------------------------ share // ------------------------------------------------------------------ $ORACLE7 registry: one specialist, one burned $ORACLE7 const MEMO_PROGRAM = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"; function loadWeb3() { if (window.solanaWeb3) return Promise.resolve(window.solanaWeb3); return new Promise((ok, no) => { const s = document.createElement("script"); s.src = "/static/vendor/solana-web3-1.95.3.iife.min.js"; s.onload = () => ok(window.solanaWeb3); s.onerror = () => no(new Error("could not load the Solana library")); document.head.appendChild(s); }); } // the transaction one wallet signs: [burn exactly 1 $ORACLE7 (register only)] + [memo with the specialist's fingerprint] async function buildRegistryTx(w, conn, owner, m, kind) { const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash("finalized"); const tx = new w.Transaction({ feePayer: owner, blockhash, lastValidBlockHeight }); if (kind === "register") { const mint = new w.PublicKey(m.mint); const accs = await conn.getParsedTokenAccountsByOwner(owner, { mint }); const acc = accs.value.find(a => BigInt(a.account.data.parsed.info.tokenAmount.amount) >= BigInt(m.burn_raw)); if (!acc) throw new Error("this wallet holds less than 1 $ORACLE7, so it cannot register a specialist"); const data = new Uint8Array(10); data[0] = 15; // BurnChecked: amount (u64 LE), decimals (u8) new DataView(data.buffer).setBigUint64(1, BigInt(m.burn_raw), true); data[9] = m.decimals; tx.add(new w.TransactionInstruction({ programId: acc.account.owner, data, keys: [{ pubkey: acc.pubkey, isSigner: false, isWritable: true }, { pubkey: mint, isSigner: false, isWritable: true }, { pubkey: owner, isSigner: true, isWritable: false }] })); } tx.add(new w.TransactionInstruction({ programId: new w.PublicKey(MEMO_PROGRAM), data: new TextEncoder().encode(m.memo), keys: [{ pubkey: owner, isSigner: true, isWritable: false }] })); return { tx, blockhash, lastValidBlockHeight }; } async function simulateTx(tx) { const b64 = tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString("base64"); const r = await api("/api/solana/rpc", { jsonrpc: "2.0", id: 1, method: "simulateTransaction", params: [b64, { encoding: "base64", sigVerify: false, replaceRecentBlockhash: true, commitment: "confirmed" }] }); if (r.error) throw new Error("Solana: " + (r.error.message || JSON.stringify(r.error))); return r.result.value; } async function solanaRecord(id, kind) { const out = $("reg-" + id); try { const m = await api(`/api/registry/memo?id=${encodeURIComponent(id)}&kind=${kind}`); if (kind === "register" && !confirm(`Register ${id} on Solana?\n\nYour wallet will be asked to sign ONE transaction that burns exactly 1 $ORACLE7 and records:\n${m.memo}\n\nThe burn cannot be undone.`)) return; const w = await loadWeb3(); const p = (window.phantom && window.phantom.solana) || (window.solana && window.solana.isPhantom ? window.solana : null); if (!p) throw new Error("no Phantom wallet in this browser (install it, or sign the memo from the CLI: registry-memo " + id + ")"); out.textContent = "connecting to your wallet…"; const owner = (await p.connect()).publicKey; const conn = new w.Connection(location.origin + "/api/solana/rpc", { commitment: "confirmed" }); // relayed by the local server const { tx, lastValidBlockHeight } = await buildRegistryTx(w, conn, owner, m, kind); out.textContent = "checking the transaction on Solana before your wallet sees it…"; const sim = await simulateTx(tx); // the exact transaction, executed on a copy of mainnet state if (sim.err) throw new Error("this transaction would fail on Solana, so it was not sent: " + JSON.stringify(sim.err) + (sim.logs || []).filter(l => /Error|error|insufficient/i.test(l)).slice(0, 2).join(" ")); out.textContent = "approve it in your wallet…"; const { signature } = await p.signAndSendTransaction(tx); out.textContent = "sent; waiting for confirmation… " + signature; let done = false; // poll the status (no websocket through the relay) for (let i = 0; i < 60 && !done; i++) { await new Promise(r => setTimeout(r, 2000)); const st = (await conn.getSignatureStatuses([signature])).value[0]; if (st && st.err) throw new Error("the transaction failed on Solana: " + JSON.stringify(st.err)); done = !!(st && (st.confirmationStatus === "confirmed" || st.confirmationStatus === "finalized")); if (!done && !st && (await conn.getBlockHeight()) > lastValidBlockHeight) throw new Error("the transaction expired before it landed; try again"); } if (!done) throw new Error("not confirmed after 2 minutes; check it on Solana Explorer: " + signature); const r = await api("/api/registry/record", { id, kind, signature }); out.innerHTML = `${kind === "register" ? "Registered: 1 $ORACLE7 burned" : "Attested"} · transaction · ${r.records.length} record(s)`; log("registry", `${id}: ${kind} confirmed on Solana (${signature.slice(0, 12)}…)`, "ok"); } catch (e) { out.textContent = e.message; log("registry", id + ": " + e.message, "no"); } } async function solanaCheck(id) { const out = $("reg-" + id); out.textContent = "reading the chain…"; try { const c = await api("/api/registry/check", { id }); out.innerHTML = `${c.registered ? "Verified on Solana" : "Not registered"} · ${c.attestations} attestation(s) · ${c.oracle7_burned} $ORACLE7 burned · vouching wallets hold ${c.vouching_oracle7} $ORACLE7` + (c.records.length ? "| ${esc(r.entity)} · ${esc(r.signal)} | ${esc(r.text)} | ${esc(r.source)} |
| ${esc(t.description)} | ${esc((t.required || []).join(", ") || "no arguments")} |
No sensors yet. Connect one below, or try the simulated garden node.
`; return; } const tiles = await Promise.all(r.items.map(async s => { const qs = await Promise.all(Object.entries(s.latest).map(async ([q, l]) => { const pts = (await api(`/api/sensor/series?id=${encodeURIComponent(s.id)}&q=${encodeURIComponent(q)}`)).points; return `no readings yet
'}` + `| ${esc(x.path)} | ${esc(x.value)} |
Hashing every shipped part…
`; log("verify", "recomputing the release hashes on this computer", "live"); try { const v = await api("/api/verify", {}); const ok = v.root_matches && !v.changed.length; $("v-out").innerHTML = `published root ${esc(v.published_root)}
computed root ${esc(v.computed_root)}
Changed: ${esc(v.changed.join(", "))}
` : "") + (v.missing.length ? `Missing: ${esc(v.missing.join(", "))}
` : "") + (v.extra_local.length ? `Not in the release (yours or added): ${esc(v.extra_local.join(", "))}
` : "") + (v.anchor && v.anchor.signature ? ` read-only; asks a public Solana RPC` : `The on-chain anchor for this release is not recorded in RELEASE_HASHES.json.
`); log("verify", `${ok ? "verified" : "mismatch"}: ${v.verified}/${v.parts} parts; root ${v.computed_root.slice(0, 16)}…`, ok ? "ok" : "no"); const b = $("v-chain"); if (b) b.onclick = async () => { b.disabled = true; log("verify", "reading the anchor transaction on Solana", "live"); try { const c = await api("/api/verify/chain", {}); b.insertAdjacentHTML("afterend", `${c.root_on_chain ? "The root is on-chain" : "The root is NOT in that transaction"}: slot ${c.slot}, ${c.block_time ? new Date(c.block_time * 1000).toUTCString() : ""} · view the transaction
`); log("verify", c.root_on_chain ? "anchor confirmed on Solana, slot " + c.slot : "anchor does not carry this root", c.root_on_chain ? "ok" : "no"); } catch (e) { b.insertAdjacentHTML("afterend", `${esc(e.message)}
`); log("verify", e.message, "no"); } }; } catch (e) { $("v-out").innerHTML = `${esc(e.message)}
`; log("verify", e.message, "no"); } } $("v-run").onclick = doVerify; // ------------------------------------------------------------------ conversations panel (collapsible; kept on this computer) let convItems = []; function setSide(open) { document.body.classList.toggle("side-open", open); $("side-toggle").setAttribute("aria-expanded", String(open)); store.set("o7wb.side", open ? "1" : "0"); } $("side-toggle").onclick = () => setSide(!document.body.classList.contains("side-open")); async function loadConvs() { try { const r = await api("/api/convs"); convItems = r.items; $("cv-keep").checked = r.keep; renderConvs(); } catch (e) { log("history", e.message, "no"); } } function renderConvs() { const f = $("cv-find").value.trim().toLowerCase(); const items = convItems.filter(c => !f || c.title.toLowerCase().includes(f)); $("cv-list").innerHTML = items.map(c => `