<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Areev</title>
<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAL60lEQVR42u1be5RVVRn/fXufc+65j3ncecIwzAzD8NAZRtFa4KuVDx4+UCrQBAEthSTLzDIr16rVWpWR4aqlS0vMFDMzxSwUNRIwclFBvAQGGAYGgRma98x9nnP2/vpjoCSBewYYHqv51tr/3H324/fbv/N93/7WucCADdiADdiA/f8anc7Fqr+wGawVjFABSBgf6WetoJLtABG2P/dJeInWft+TOB3AR81eiYsfciEDObCyhwKsDQDWRxubgbxKGMEooheMQ809W899BQSLx6B63kZ4iTYoJz5ESGsGiC4FKHCUxxWYNzLUYiGD2+P/Wg4VS6FhyZxzl4Dq+f+ENPPBWpUKw34WJK7KPIo3M3t3kDDXERE2PFJ8br4CgWgl3NguGMFSkGHN8gceAGgMQd7nJVtML9WJ4KALzk0F1MzfDBHIBliVkQguA+h8/6O5hbV3HUis1W4K7z82/NxSgLRzoFItMIJlILJm9A08AFAhkfzsuAdLwCp17img5os7IUwbgB5GwloG0Ki+z8J7WXuTAdqm3QTef3zkuaMA5cRhZQ0GkXnbiYEHACoDyZuNUAGU03PuKKBm/jYIKwtgriJpLAOo6oQnY65j5UwCYa8Ta0Ld0+PPfgVoN4lg4RBAiNknBR4AiEZDGFOFlY25i8ad/Qqo/sJmyEAOwDySpPUmiIad9KTMf9Ne8nqA2tKdDdix+OqzUwF2/igoJ46cEUMBYcw5JeB7VXARCXOisMIIl3z81EarUznZyNkrYITykWrrHC2E+SMQ5WYYkgbrehDlZVCjJELQS7S9qpyYFyquRdfOpWeXAsKl46HdBIbfVA4S5hwQVWSWtn5Pa/fzAH+QWQXiEzKQdYVh5yJr2NVnnwKqpi+BGSlGR137KCGth/2cPrP6thUufFO7yTIQXZKBAQsAUm11fwSRFjKA+IG/nx0KCBXVQqU6MfgT5SBhzQKJCh+e7R3W7htus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7S4B2McXlBQhkne48YOWl2rH4Mu+6o+A0be/Bzd2AMrpiBCJuQCCfQS/hVnNJ2nVm+ECSDsX7z8+4qRjwp7fz4FKtsFLHNwA1u/4CyQ0yQhGx8tALorG3e+PgOCgWggzCyTDkwG6so9H38qsHhCGvaWrYQWcrn3Y/LPyUxIU401rEYgOh5ld4bL2XgQ47YOBXBLGbO22SO0ljlowOYKA6nmb4CVaoZ1ELpGcD5DdlzDHWi2Y9OiQN7xECyKDL8Tmx6pwKq1l3ZNQyXYoJ76Smf/pM5+4URh5Y4UMo3TCD45PQLCoBsIMgwxrCogu75vy1SvK6XnizS83AEJgy8/HnPLU6IO378e25y6HnTeiA9pb4pOAQhJythvfRKzSMEIFxybA6d4H7cbzCWIeANM/er2NlfNdaWXFhBHE+4+NQn/ZsCnPwun+AFo5fwDrRp8kfMYI19SQjOD8uRuOTQBJC0JaN2S+eh6BvpO195ARLKg7sOo76NzxWr8myPW/uR5Oz350bV+yk1n7vPdSCUHOjA4rAWt1HCdIBABh/8VS3sFa3Zc4uOX3TlcjCsbeicbX7+73W4JhRxGtnsmsvZ+A9SqfEWFWR8P+aiHN4xREmMHAbwhsAVR97EyRHTBvZdbLpB3dZedVglmh7peXnJZrUvyD95A/9nPwEq31rNzbSNB0gKu5938Ih/coD9VeDiNWzLoIgrccMxO84P6Dh8pWAqQZrNzDqjiCJGFHoLULVi7c2AHIQE6/fMZ6PDvvrnWwo1VQTg9ImBg0rghv3fLfvdqFNWRGhiBn+AQCGG5PM8JDx3PDy9P5uKlw7Vf2grXqrQAdQwCsXKTbd4FZY8fiK3Embcy9jZBWBPF9f4MTO/AhxQsAAkYwCjBDuQmwdgEw9rx2OwZswAZswAZswIB/A76DD3Wl5sBCAAAAAElFTkSuQmCC">
<style>
/* ── Console v2 · "cobalt" ────────────────────────────────────────────
Pure white surfaces, one saturated cobalt carrying every action.
Burnt orange = needs attention, red = destructive, teal = content
address. Monospace is reserved for developer mode. Light is
canonical; dark mirrors it token for token. Design source of truth
is the Paper file "Areev", page "Console v2 — Redesign". */
:root {
color-scheme: light;
--bg:#F6F7FB; --surface:#FFFFFF; --raise:#F1F3F8; --well:#F7F8FC;
--line:#E3E6ED; --line2:#D5DAE6; --hair:#EDEFF4;
--ink:#0B0D12; --text:#3E4657; --muted:#5A6072; --dim:#6E7686; --faint:#8B92A3; --ghost:#A8AEBC;
--accent:#2F72E8; --accent-hover:#2861C5; --accent-soft:#EAF1FD; --accent-line:#C5DAF9;
--ok:#0F8A5F; --ok-soft:#E9F6F0; --ok-line:#CBE8DA;
--warn:#C2410C; --warn-soft:#FFF3EC; --warn-line:#FBDCC8;
--danger:#C81E1E; --danger-soft:#FDECEC; --danger-line:#F6CDCD;
--hash:#0E8F82;
--cat-person:#2F72E8; --cat-org:#0E8F82; --cat-project:#7A3BE0;
--cat-thing:#B45309; --cat-note:#F2542D;
--sel:rgba(47,114,232,.20);
--shadow:0 10px 30px rgba(11,13,18,.10);
--card-shadow:0 1px 2px rgba(11,13,18,.04), 0 2px 6px rgba(11,13,18,.05);
--sans:'Inter',-apple-system,system-ui,'Segoe UI',Roboto,sans-serif;
--mono:ui-monospace,'SF Mono',SFMono-Regular,Menlo,Consolas,monospace;
/* Layout measures. Widen with the viewport, but never past the point
where a line of prose becomes tiring to read. */
--col:880px; --wide:1500px;
}
@media (min-width:1500px) { :root { --col:1000px; --wide:1700px; } }
@media (min-width:1800px) { :root { --col:1100px; --wide:1900px; } }
@media (min-width:2200px) { :root { --col:1200px; --wide:2100px; } }
@media (prefers-color-scheme: dark) { :root { color-scheme: dark;
--bg:#0B0E14; --surface:#111621; --raise:#171D2A; --well:#0D121B;
--line:#222A38; --line2:#333C4D; --hair:#1C2431;
--ink:#F2F5FA; --text:#C9D1DE; --muted:#9AA4B7; --dim:#8B95A8; --faint:#79839A; --ghost:#5F6980;
--accent:#7EA8F1; --accent-hover:#A3C1F5; --accent-soft:#122744; --accent-line:#2D4E80;
--ok:#3DD68C; --ok-soft:#12251C; --ok-line:#255140;
--warn:#F59E5B; --warn-soft:#2A1A11; --warn-line:#5A3A22;
--danger:#F87171; --danger-soft:#2B1517; --danger-line:#5E2B2E;
--hash:#3FCFC0;
--cat-person:#7EA8F1; --cat-org:#3FCFC0; --cat-project:#B39BFF;
--cat-thing:#E0A458; --cat-note:#FF8A66;
--sel:rgba(126,168,241,.32);
--shadow:0 10px 30px rgba(0,0,0,.45);
--card-shadow:0 1px 2px rgba(0,0,0,.30);
} }
:root[data-theme="light"] { color-scheme: light;
--bg:#F6F7FB; --surface:#FFFFFF; --raise:#F1F3F8; --well:#F7F8FC;
--line:#E3E6ED; --line2:#D5DAE6; --hair:#EDEFF4;
--ink:#0B0D12; --text:#3E4657; --muted:#5A6072; --dim:#6E7686; --faint:#8B92A3; --ghost:#A8AEBC;
--accent:#2F72E8; --accent-hover:#2861C5; --accent-soft:#EAF1FD; --accent-line:#C5DAF9;
--ok:#0F8A5F; --ok-soft:#E9F6F0; --ok-line:#CBE8DA;
--warn:#C2410C; --warn-soft:#FFF3EC; --warn-line:#FBDCC8;
--danger:#C81E1E; --danger-soft:#FDECEC; --danger-line:#F6CDCD;
--hash:#0E8F82;
--cat-person:#2F72E8; --cat-org:#0E8F82; --cat-project:#7A3BE0;
--cat-thing:#B45309; --cat-note:#F2542D;
--sel:rgba(47,114,232,.20);
--shadow:0 10px 30px rgba(11,13,18,.10);
--card-shadow:0 1px 2px rgba(11,13,18,.04), 0 2px 6px rgba(11,13,18,.05);
}
:root[data-theme="dark"] { color-scheme: dark;
--bg:#0B0E14; --surface:#111621; --raise:#171D2A; --well:#0D121B;
--line:#222A38; --line2:#333C4D; --hair:#1C2431;
--ink:#F2F5FA; --text:#C9D1DE; --muted:#9AA4B7; --dim:#8B95A8; --faint:#79839A; --ghost:#5F6980;
--accent:#7EA8F1; --accent-hover:#A3C1F5; --accent-soft:#122744; --accent-line:#2D4E80;
--ok:#3DD68C; --ok-soft:#12251C; --ok-line:#255140;
--warn:#F59E5B; --warn-soft:#2A1A11; --warn-line:#5A3A22;
--danger:#F87171; --danger-soft:#2B1517; --danger-line:#5E2B2E;
--hash:#3FCFC0;
--cat-person:#7EA8F1; --cat-org:#3FCFC0; --cat-project:#B39BFF;
--cat-thing:#E0A458; --cat-note:#FF8A66;
--sel:rgba(126,168,241,.32);
--shadow:0 10px 30px rgba(0,0,0,.45);
--card-shadow:0 1px 2px rgba(0,0,0,.30);
}
* { box-sizing:border-box; margin:0; }
html, body { height:100%; }
/* The reading surface is the brightest plane; nav and developer chrome sit
one step back on the tint. (The reverse reads as an unfinished page.) */
body { background:var(--surface); color:var(--text); font:15px/1.55 var(--sans); -webkit-font-smoothing:antialiased; }
a { color:var(--accent); text-decoration:none; }
::-webkit-scrollbar { width:10px; height:10px; }
::-webkit-scrollbar-thumb { background:var(--line2); border-radius:8px; border:3px solid transparent; background-clip:content-box; }
:focus-visible { outline:2px solid var(--accent); outline-offset:2px; border-radius:4px; }
@media (prefers-reduced-motion: reduce) { * { transition:none !important; animation:none !important; } }
/* Developer mode: hidden by default, revealed by html.dev. Explicit
display values (not `revert`, which would drop id-level flex rules). */
/* Belt and braces against stored values that have no wrap opportunities
(JSON, hashes, URLs): flex children must be allowed to shrink, and text
must be allowed to break mid-token. Nothing may scroll the page sideways. */
.mrow .say, .mrow .prov, .srow .t, .evi-row .t, .ev .say, .ans-text,
.kv .v, #ginspect .meta { min-width:0; overflow-wrap:anywhere; }
.mrow, .srow, .evi-row, .ev, .acts { min-width:0; }
.dev-only { display:none !important; }
html.dev .dev-only { display:block !important; }
html.dev .dev-flex { display:flex !important; }
/* ── shell ── */
#shell { display:flex; min-height:100vh; align-items:stretch; }
#rail { width:260px; flex-shrink:0; background:var(--bg); border-right:1px solid var(--line);
padding:26px 18px 20px 22px; display:flex; flex-direction:column; gap:26px; position:sticky; top:0; height:100vh; }
#main { flex:1; min-width:0; display:flex; flex-direction:column; }
.page { padding:44px 56px 56px 48px; display:flex; flex-direction:column; gap:24px; }
/* One reading column, centred in whatever space the rail leaves. A cap
keeps line length sane; auto margins stop it hugging the rail on a wide
monitor, where a left-pinned column just looks like a broken page. */
.col { width:100%; max-width:var(--col); margin-left:auto; margin-right:auto; }
.wide { width:100%; max-width:var(--wide); margin-left:auto; margin-right:auto; }
/* ── query workbench ── */
/* The composer is one surface holding the editor and everything you can do
to it, so Run reads as the act and the rest as afterthoughts. */
/* No overflow:hidden here — the Format menu is absolutely positioned inside
the action bar, and clipping the composer clips the menu. Round the
children instead. */
.composer { background:var(--surface); border:1px solid var(--line2); border-radius:12px;
box-shadow:var(--card-shadow); }
/* The editor is a transparent textarea over a highlighted mirror: the caret,
selection and IME stay native, the colour comes from the layer beneath. */
.qedit { position:relative; }
#qhl, #qtext { font-family:var(--mono); font-size:13px; line-height:21px;
padding:16px 18px; white-space:pre-wrap; overflow-wrap:break-word;
border:0; margin:0; }
#qhl { position:absolute; inset:0; pointer-events:none; overflow:hidden;
color:var(--text); border-radius:12px 12px 0 0; }
#qtext { position:relative; width:100%; display:block; resize:none; overflow-y:auto;
background:none; color:transparent; caret-color:var(--ink);
border-radius:12px 12px 0 0; min-height:88px; max-height:340px; }
#qtext::selection { background:var(--sel); }
#qtext:focus { outline:none; }
#qtext::placeholder { color:var(--faint); }
#qhl .k { color:var(--ink); font-weight:600; } /* RECALL, WHERE, LIMIT … */
#qhl .s { color:var(--hash); } /* "quoted strings" */
#qhl .n { color:var(--warn); } /* numbers */
#qhl .c { color:var(--faint); } /* -- comments */
.composer .cbar { display:flex; align-items:center; gap:9px; flex-wrap:wrap;
padding:11px 14px; border-top:1px solid var(--line);
background:var(--well); border-radius:0 0 12px 12px; }
.composer .kbd { font-size:11.5px; font-weight:500; opacity:.75; }
/* ── the on-ramp: what the page offers before you have run anything ── */
.onramp { display:flex; flex-direction:column; gap:12px; }
.qsec { display:flex; align-items:center; gap:11px; padding-top:10px; }
.qsec i { flex:1; height:1px; background:var(--line); }
/* Two across so the four questions read as a block, not a ragged row — and
sized to hold two even when the developer rail takes 330px off the width. */
.starters { display:grid; grid-template-columns:repeat(auto-fit, minmax(340px, 1fr)); gap:12px; }
.starter { text-align:left; background:var(--surface); border:1px solid var(--line);
border-radius:11px; padding:15px 16px; display:flex; flex-direction:column; gap:10px;
cursor:pointer; transition:border-color .12s, box-shadow .12s; }
.starter:hover { border-color:var(--accent-line); box-shadow:var(--card-shadow); }
.starter b { font-size:15px; font-weight:600; color:var(--ink); line-height:21px; }
/* the CAL each question writes, shown so the answer teaches the language */
.starter code { font-family:var(--mono); font-size:11.5px; color:var(--muted); background:var(--bg);
border:0; border-radius:6px; padding:8px 10px; display:block;
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
/* ── analytics: the grain-type census, namespace breakdown, growth trend
and recall-leg status that used to live as a small "WHAT'S IN THIS
MEMORY" teaser on this very page — moved to its own tab so it could
cover all 12 grain types instead of 4, without crowding the on-ramp.
`.crow` is the shared row shape for both the grain-type census
and the namespace breakdown — a mono key, an optional gloss, a bar
proportional to that list's own max (not a global constant), and a
right-aligned count. */
.stiles { display:grid; grid-template-columns:repeat(4, minmax(200px, 1fr)); gap:14px; }
.stile { padding:18px 20px; display:flex; flex-direction:column; gap:6px; }
.stile .lbl { font-size:11.5px; font-weight:600; color:var(--dim); letter-spacing:.09em; }
.stile .n { font-size:28px; font-weight:700; color:var(--ink); letter-spacing:-.02em; font-variant-numeric:tabular-nums; }
.stile .sub { font-size:12.5px; color:var(--faint); }
.census { display:flex; flex-direction:column; margin-top:6px; }
.crow { display:flex; align-items:center; gap:14px; padding:9px 0; border:0; background:none;
width:100%; text-align:left; font-family:inherit; cursor:pointer; }
.crow .k { width:150px; flex-shrink:0; font-family:var(--mono); font-size:12.5px; color:var(--ink); }
.crow .k.wide { width:200px; }
.crow .g { width:230px; flex-shrink:0; font-size:12.5px; color:var(--faint);
overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.crow .track { flex:1; height:8px; background:var(--raise); border-radius:4px; }
.crow .bar { height:100%; background:var(--accent); border-radius:4px; }
.crow .bar.zero { background:var(--line); }
.crow .n { width:40px; flex-shrink:0; text-align:right; font-size:14px; font-weight:600;
color:var(--ink); font-variant-numeric:tabular-nums; }
.crow .n.zero { color:var(--faint); font-weight:500; }
.gchart { display:flex; align-items:flex-end; gap:6px; height:100px; margin-top:22px; }
.gbar { flex:1; background:var(--accent-line); border-radius:4px 4px 0 0; }
.gbar.today { background:var(--accent); }
.legs { display:flex; gap:14px; }
.leg { flex:1; padding:16px 18px; display:flex; flex-direction:column; gap:8px; }
.leg .hd { display:flex; align-items:center; gap:8px; }
.leg .dot { width:7px; height:7px; border-radius:4px; flex-shrink:0; }
.leg b { font-size:14px; font-weight:600; color:var(--ink); }
.leg .d { font-size:12.5px; color:var(--faint); line-height:18px; }
/* minmax(0,·) or a long description sets the column's min-content width and
the two halves stop being halves. */
.recents { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:12px 26px; }
.rrow { display:flex; flex-direction:column; gap:3px; padding:9px 0; text-align:left;
background:none; border:0; border-bottom:1px solid var(--hair); cursor:pointer; width:100%; }
.rrow:hover .rq, .rrow:hover .rn { color:var(--accent); }
/* A recent run is code and reads as code; a saved query has a human name. */
.rrow .rq { font-family:var(--mono); font-size:11.5px; color:var(--text);
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.rrow .rn { font-size:14px; color:var(--ink); font-weight:500;
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.rrow .rm { font-size:12.5px; color:var(--faint);
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.rempty { padding:9px 0; font-size:13px; color:var(--faint); }
/* Restate the query in plain words, so a non-technical reader can tell at a
glance whether the CAL asked what they meant. */
.qsum { display:flex; flex-direction:column; gap:3px; padding-bottom:13px; }
.qsum .h { font-size:19px; font-weight:600; color:var(--ink); letter-spacing:-.01em; }
.qsum .h em { font-style:normal; font-weight:400; font-size:15px; color:var(--muted); }
#qbar { display:flex; align-items:center; gap:12px; flex-wrap:wrap;
padding:12px 0; border-bottom:1px solid var(--line); }
#qmore { padding:16px 0; }
#qerr { background:var(--danger-soft); border:1px solid var(--danger-line); border-radius:10px;
padding:12px 14px; font-size:13px; }
#qerr .code { font-family:var(--mono); font-size:11px; color:var(--danger);
border:1px solid var(--danger-line); border-radius:5px; padding:1px 6px; margin-right:8px; }
#qerr pre { margin-top:8px; font-family:var(--mono); font-size:12.5px; color:var(--muted); white-space:pre-wrap; }
#qerr .hint { margin-top:7px; color:var(--warn); }
code { font-family:var(--mono); font-size:.92em; background:var(--raise); border:1px solid var(--line);
border-radius:5px; padding:1px 5px; }
.menuwrap { position:relative; display:inline-block; }
/* A drawn chevron rather than the ▾ glyph, which renders thin and pale at
this size and disappears against a ghost button. */
.btn.hasmenu::after { content:''; width:6px; height:6px; flex-shrink:0; margin-left:2px;
border-right:1.7px solid currentColor; border-bottom:1.7px solid currentColor;
transform:translateY(-2px) rotate(45deg); }
/* JSON is the developer's view of the answer — colour it the way the rest of
this console colours values, so the meanings carry across. */
.jsonv { line-height:19px; }
.jsonv .jk { color:var(--ink); font-weight:600; }
.jsonv .js { color:var(--hash); }
.jsonv .jn { color:var(--warn); }
.jsonv .jb { color:var(--ok); font-weight:500; }
.jsonv .jz { color:var(--faint); }
.menu { position:absolute; z-index:30; top:calc(100% + 6px); right:0; background:var(--surface);
border:1px solid var(--line2); border-radius:11px; min-width:300px; max-width:460px;
max-height:340px; overflow-y:auto; box-shadow:var(--shadow); padding:5px; }
.menu .mi { padding:8px 11px; border-radius:8px; cursor:pointer; font-size:13px; color:var(--text); }
.menu .mi:hover { background:var(--raise); }
.menu .mi small { display:block; font-family:var(--mono); font-size:11px; color:var(--dim);
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-top:2px; }
.menu .sep { padding:8px 11px 4px; font-size:11px; font-weight:600; letter-spacing:.09em; color:var(--dim); }
/* order-preserving masonry: cards keep result order, heights vary with content */
#qcards { display:grid; grid-template-columns:repeat(auto-fill, minmax(300px, 1fr));
grid-auto-rows:8px; gap:0 16px; }
/* `layoutMasonry()` reserves a gutter's worth of extra rows past each
card's own content height — but a grid item stretches to fill its full
row-span by default, so without `align-self:start` the card's own box
grows to swallow that reserved space and the "gap" never becomes a gap. */
.qcard { align-self:start; background:var(--surface); border:1px solid var(--line); border-radius:12px;
padding:14px 16px; display:flex; flex-direction:column; gap:8px;
box-shadow:var(--card-shadow); overflow:hidden; }
.qcard .hd { display:flex; align-items:center; gap:8px; }
.qcard .kind { font-size:11px; font-weight:600; letter-spacing:.06em; text-transform:uppercase; }
.qcard .say { font-size:15px; line-height:22px; color:var(--ink); overflow-wrap:anywhere; }
.qcard .kv { display:flex; gap:8px; font-size:12.5px; padding:3px 0; border-top:1px solid var(--hair); }
.qcard .kv b { flex-shrink:0; min-width:84px; color:var(--dim); font-weight:500; }
.qcard .kv span { color:var(--text); overflow-wrap:anywhere; min-width:0; }
#qtable { width:100%; border-collapse:collapse; font-size:13.5px; }
#qtable th { text-align:left; font-size:11px; font-weight:600; letter-spacing:.06em; color:var(--dim);
text-transform:uppercase; padding:8px 12px 8px 0; border-bottom:1px solid var(--line2); white-space:nowrap; }
#qtable td { padding:9px 12px 9px 0; border-bottom:1px solid var(--hair); vertical-align:top;
max-width:340px; overflow-wrap:anywhere; }
.seg.sm button { height:26px; padding:0 11px; font-size:12.5px; }
/* The graph is a canvas, not prose — let it use the width, within reason. */
#graphView { width:100%; max-width:var(--wide); margin-left:auto; margin-right:auto; }
/* ── rail ── */
/* Nav items carry their own 11px left padding (room for the hover/active
pill around the icon), and the rail footer already insets by that same
11px to match — the brand row was the one place that didn't, so its
icon sat 11px left of every nav icon below it. */
.brand { display:flex; align-items:center; gap:9px; padding-left:11px; border:0; background:none;
font-family:inherit; text-align:left; cursor:pointer; width:100%; border-radius:9px;
padding-top:4px; padding-bottom:4px; margin:-4px 0; transition:background .12s; }
.brand:hover { background:var(--raise); }
/* The full v2 lockup (A + reev + improvement loop), not the A alone —
two bitmaps because the dark variant sets `reev` in white, which
BRAND.md requires as its own artwork rather than a CSS recolor. */
.brand .logo { height:31px; width:auto; display:block; }
.brand .logo.dark { display:none; }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) .brand .logo.light { display:none; }
:root:not([data-theme="light"]) .brand .logo.dark { display:block; }
}
:root[data-theme="dark"] .brand .logo.light { display:none; }
:root[data-theme="dark"] .brand .logo.dark { display:block; }
.nav { display:flex; flex-direction:column; gap:2px; }
.nav-item { display:flex; align-items:center; gap:11px; padding:9px 11px; border-radius:9px;
cursor:pointer; color:var(--text); font-size:15px; font-weight:500; border:0; background:none;
width:100%; text-align:left; font-family:inherit; transition:background .12s; }
.nav-item:hover { background:var(--raise); }
.nav-item.on { background:var(--accent-soft); color:var(--accent); font-weight:600; }
.nav-item svg { flex-shrink:0; stroke:currentColor; }
.nav-item .grow { flex:1; }
.pill { display:inline-flex; align-items:center; justify-content:center; min-width:20px; height:20px;
padding:0 6px; border-radius:10px; background:var(--warn); color:#fff; font-size:11px; font-weight:600; }
.pill.soft { background:var(--raise); color:var(--dim); }
.nav-item.on .pill.soft { background:var(--surface); color:var(--accent); }
.sec-label { font-size:11.5px; font-weight:600; color:var(--dim); letter-spacing:.09em; }
#entities { display:flex; flex-direction:column; gap:1px; overflow-y:auto; min-height:0; }
.ent { display:flex; align-items:center; gap:10px; padding:7px 11px; border-radius:8px; cursor:pointer;
border:0; background:none; width:100%; text-align:left; font-family:inherit; transition:background .12s; }
.ent:hover { background:var(--raise); }
.ent.on { background:var(--accent-soft); }
.ent .av { display:flex; align-items:center; justify-content:center; width:22px; height:22px; flex-shrink:0;
border-radius:11px; background:var(--raise); color:var(--muted); font-size:10.5px; font-weight:600; }
.ent.on .av { background:var(--accent); color:#fff; }
.ent .nm { flex:1; font-size:14.5px; font-weight:500; color:var(--ink); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.ent .ct { width:22px; flex-shrink:0; text-align:right; font-size:13px; color:var(--faint); font-variant-numeric:tabular-nums; }
.rail-foot { margin-top:auto; display:flex; flex-direction:column; gap:14px; padding:0 11px 2px; }
.dot { width:7px; height:7px; border-radius:4px; background:var(--ghost); flex-shrink:0; }
.toggle-row { display:flex; align-items:center; gap:10px; padding-top:14px; border-top:1px solid var(--line); }
.toggle-row span { flex:1; font-size:13.5px; color:var(--dim); }
.sw { width:34px; height:20px; flex-shrink:0; border-radius:10px; background:var(--line2); padding:2px;
display:flex; align-items:center; cursor:pointer; border:0; transition:background .15s; }
.sw i { width:16px; height:16px; border-radius:8px; background:#fff; display:block; transition:transform .15s; }
.sw.on { background:var(--accent); }
.sw.on i { transform:translateX(14px); }
/* ── type ── */
h1 { font:700 31px/38px var(--sans); color:var(--ink); letter-spacing:-.025em; }
h2 { font:700 15px var(--sans); color:var(--ink); letter-spacing:-.01em; }
.sub { font-size:14.5px; line-height:22px; color:var(--muted); }
.meta { font-size:13px; color:var(--dim); }
.tiny { font-size:12.5px; color:var(--faint); }
.mono { font-family:var(--mono); font-size:11.5px; color:var(--hash); }
/* ── page header: one breadcrumb line — home icon, prior pages, then the
current page as the trail's own last segment (not a separate display
headline below it) — followed by a description line. Every page's
title block, one component. All trail text shares one font size; color
and weight carry the hierarchy instead: prior pages read legibly rather
than near-invisible, the current-page segment is the cleanest, darkest,
boldest text in the row, and the description recedes a step further
neutral than either. ── */
.pagehead { display:flex; flex-direction:column; gap:3px; }
.pagehead .trail { display:flex; flex-wrap:wrap; align-items:center; gap:6px; row-gap:2px; }
.pagehead .trail .home { display:flex; align-items:center; padding:2px; margin-left:-2px; border:0; background:none; color:var(--dim); border-radius:5px; transition:color .12s; }
.pagehead .trail .home:hover { color:var(--accent); }
/* The "›" sits 1px low against the icon/text either side of it — nudge
it down that 1px rather than the icon (which is already centred). */
.pagehead .trail .sep { font-size:16px; color:var(--faint); padding-bottom:1px; }
.pagehead .trail .link { border:0; background:none; padding:0; font:500 13.5px var(--sans); color:var(--dim); cursor:pointer; }
.pagehead .trail .link:hover { color:var(--accent); }
.pagehead .ctitle { font:600 13.5px/19px var(--sans); color:var(--ink); letter-spacing:-.01em; }
.pagehead .cdesc { font-size:13.5px; line-height:20px; color:var(--muted); margin-top:2px; }
/* Editable title/description (Workflows only): the same element throughout
hover and focus — never swapped for a different tag — so turning it into
an active field never shifts anything around it. The padding/negative-
margin pair keeps the text sitting in exactly the same spot whether or
not the hover/focus background is showing. The input never carries its
own width: it sits in a grid cell sized by an invisible twin (::after,
same text via data-value) so the field hugs its content and the edit/
lock icons sit right after the text instead of stranded at the row's
far edge. */
.pagehead .edit-row { display:inline-flex; align-items:center; gap:5px; max-width:100%; vertical-align:middle; }
/* The sizer span carries the same ctitle/cdesc class as the input inside
it, so it (and its ::after, which inherits font from it for free) picks
up the exact same font as the real title/description text below —
no font:inherit here, that would out-specificity .pagehead .ctitle/
.cdesc and silently fall back to an ambient size. ::after and the input
also share identical padding/border so the ghost's measured width
already includes the room the input's own padding will eat into. */
.pagehead .input-sizer { display:inline-grid; align-items:center; min-width:1em; max-width:100%; }
.pagehead .input-sizer::after, .pagehead .input-sizer input {
grid-area:1/1; box-sizing:border-box; padding:1px 5px; border:1px solid transparent; }
.pagehead .input-sizer::after { content:attr(data-value) ' '; visibility:hidden; white-space:pre; }
.pagehead input.ctitle, .pagehead input.cdesc {
display:block; width:100%; min-width:1em; height:auto; background:none;
border-radius:6px; margin:-1px -5px; cursor:pointer; }
.pagehead input.ctitle:hover:not(:focus):not(:disabled), .pagehead input.cdesc:hover:not(:focus):not(:disabled) {
background:var(--raise); border-color:var(--line); cursor:text; }
.pagehead input.ctitle:focus, .pagehead input.cdesc:focus {
background:var(--surface); border-color:var(--accent-line); box-shadow:0 0 0 3px var(--accent-soft); cursor:text; outline:none; }
.pagehead input.ctitle:disabled, .pagehead input.cdesc:disabled { color:var(--dim); cursor:default; }
.pagehead input.ctitle::placeholder, .pagehead input.cdesc::placeholder { color:var(--faint); }
.pagehead .edit-icon { display:flex; align-items:center; flex-shrink:0; color:var(--faint); opacity:0; transition:opacity .12s; cursor:pointer; }
.pagehead .edit-row:hover .edit-icon { opacity:1; }
.pagehead .lock-hint { display:flex; align-items:center; flex-shrink:0; color:var(--warn); cursor:help; margin-left:2px; }
/* ── controls ── */
button { font-family:inherit; cursor:pointer; }
.btn { display:inline-flex; align-items:center; justify-content:center; gap:7px; height:40px; padding:0 20px;
border-radius:10px; background:var(--accent); color:#fff; border:0; font-size:14.5px; font-weight:600;
transition:background .12s; white-space:nowrap; flex-shrink:0; }
.btn:hover { background:var(--accent-hover); }
.btn.sm { height:34px; padding:0 15px; font-size:13px; border-radius:9px; }
.btn.ghost { background:var(--surface); border:1px solid var(--line2); color:var(--text); font-weight:500; }
.btn.ghost:hover { background:var(--raise); }
.btn.danger { background:none; border:0; color:var(--danger); font-weight:600; padding:0; height:auto; }
.btn:disabled { opacity:.5; cursor:default; }
.chip { padding:6px 13px; border-radius:16px; border:1px solid var(--line); background:var(--surface);
font-size:13.5px; color:var(--text); cursor:pointer; transition:border-color .12s, color .12s; }
.chip:hover { border-color:var(--line2); }
.chip.on { background:var(--accent); border-color:var(--accent); color:#fff; font-weight:600; }
.seg { display:inline-flex; padding:3px; border-radius:10px; background:var(--raise); }
.seg button { height:30px; padding:0 15px; border-radius:8px; border:0; background:none; color:var(--muted);
font-size:13.5px; font-weight:500; }
.seg button.on { background:var(--surface); color:var(--accent); font-weight:600; box-shadow:0 1px 2px rgba(11,13,18,.06); }
.tabs { display:flex; align-items:flex-end; gap:26px; border-bottom:1px solid var(--line); }
.tabs button { padding:0 0 11px; border:0; background:none; font-size:14.5px; font-weight:500; color:var(--muted); }
.tabs button.on { color:var(--accent); font-weight:600; box-shadow:inset 0 -2px 0 var(--accent); }
input[type=text], textarea { font-family:inherit; background:var(--surface); border:1px solid var(--line2);
border-radius:10px; color:var(--ink); padding:9px 12px; font-size:14px; width:100%; }
input[type=text]:focus, textarea:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-soft); }
/* A native <select>, restyled to match every other control here instead of
the browser's own chrome — `appearance:none` plus a drawn chevron.
Chrome renders no pseudo-elements on <select>, so the chevron is a real
sibling span (`.sel-wrap`/`.sel-arrow`), the same shape `.ns-combo`'s
own arrow already uses, not a ::after. */
select { appearance:none; -webkit-appearance:none; font-family:inherit; background:var(--surface);
border:1px solid var(--line2); border-radius:10px; color:var(--ink); padding:9px 30px 9px 12px;
font-size:14px; width:100%; cursor:pointer; }
select:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-soft); }
select:disabled { cursor:default; opacity:.6; }
.sel-wrap { position:relative; display:block; }
.sel-arrow { position:absolute; right:11px; top:0; height:100%; display:flex; align-items:center;
pointer-events:none; color:var(--faint); }
/* ── ask ── */
.askbar { display:flex; align-items:center; gap:13px; height:56px; padding:0 14px 0 18px; background:var(--surface);
border:1px solid var(--line2); border-radius:13px; transition:border-color .12s, box-shadow .12s; }
.askbar:focus-within { border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-soft); }
.askbar input { border:0; background:none; padding:0; font-size:16px; flex:1; height:100%; }
.askbar input:focus { outline:none; box-shadow:none; }
.askbar input::placeholder { color:var(--faint); }
.examples { display:flex; align-items:center; gap:8px; flex-wrap:wrap; padding:0 2px; }
.examples .tiny { flex-shrink:0; }
/* ── cards & banners ── */
/* On a white page a card needs its own lift, not fill contrast. */
.card { background:var(--surface); border:1px solid var(--line); border-radius:14px; box-shadow:var(--card-shadow); }
.banner { display:flex; align-items:center; gap:12px; padding:13px 16px; border-radius:11px;
background:var(--warn-soft); border:1px solid var(--warn-line); }
.banner .grow { flex:1; font-size:14.5px; color:var(--text); }
.banner b { color:var(--ink); font-weight:600; }
.banner .go { flex-shrink:0; font-size:14px; font-weight:600; color:var(--accent); cursor:pointer; }
.empty { padding:34px 0; text-align:center; color:var(--dim); font-size:14px; }
.planv { display:flex; flex-direction:column; padding-top:6px; }
.prow { display:flex; gap:14px; padding:10px 0; border-bottom:1px solid var(--hair); font-size:13.5px; }
.prow b { width:104px; flex-shrink:0; color:var(--dim); font-weight:500; }
.prow span { color:var(--text); font-family:var(--mono); font-size:12.5px; }
.pnote { margin-top:14px; padding:12px 14px; background:var(--warn-soft);
border:1px solid var(--warn-line); border-radius:9px; font-size:13px;
line-height:20px; color:var(--text); }
/* A query that matched nothing is a normal outcome, not an error — say what
was asked and offer the next thing to try, rather than a dead end. */
.nores { display:flex; flex-direction:column; align-items:flex-start; gap:9px;
padding:30px 26px; background:var(--surface); border:1px solid var(--line);
border-radius:12px; }
.nores .t { font-size:17px; font-weight:600; color:var(--ink); }
.nores .d { font-size:14px; line-height:21px; color:var(--muted); max-width:62ch; }
.nores .acts { display:flex; gap:9px; flex-wrap:wrap; padding-top:4px; }
/* Colour carries meaning here, never decoration: teal is a content address
everywhere in this console, burnt orange is "needs attention". */
.v-hash { color:var(--hash); font-family:var(--mono); font-size:11.5px; }
.v-time { color:var(--dim); }
.v-yes { color:var(--ok); font-weight:500; }
.v-no { color:var(--warn); font-weight:500; }
.v-num { color:var(--ink); font-weight:500; font-variant-numeric:tabular-nums; }
/* ── memory list ── */
.grp-head { display:flex; align-items:baseline; gap:10px; padding:22px 0 10px; }
.grp-head:first-child { padding-top:6px; }
.mrow { display:flex; align-items:flex-start; gap:18px; padding:14px 8px 14px 0; border-top:1px solid var(--hair);
cursor:pointer; border-radius:8px; transition:background .1s; }
.mrow:hover { background:var(--raise); }
.mrow.sel { background:var(--accent-soft); }
.mrow .body { flex:1; display:flex; flex-direction:column; gap:4px; min-width:0; }
.mrow .say { font-size:16.5px; line-height:25px; color:var(--ink); }
.mrow .prov { font-size:13px; line-height:20px; color:var(--dim); }
.mrow .when { width:96px; flex-shrink:0; text-align:right; font-size:13px; color:var(--dim); padding-top:4px; }
.mrow.gone .say { color:var(--ghost); text-decoration:line-through; }
.mrow.sup .say { color:var(--muted); }
/* ── answer ── */
#answer { display:flex; flex-direction:column; padding:28px 30px 0; }
.ans-label { font-size:11.5px; font-weight:600; color:var(--accent); letter-spacing:.09em; }
.ans-text { font-size:20px; line-height:31px; color:var(--ink); letter-spacing:-.01em; }
.srow { display:flex; align-items:center; gap:14px; padding:11px 0; border-bottom:1px solid var(--hair); cursor:pointer; }
.srow:last-child { border-bottom:0; }
.srow .t { flex:1; font-size:15px; color:var(--ink); }
.srow .w { width:96px; flex-shrink:0; text-align:right; font-size:13px; color:var(--dim); }
.disclose { display:flex; align-items:center; gap:10px; padding:15px 0 18px; border-top:1px solid var(--hair);
cursor:pointer; font-size:14px; color:var(--text); }
.disclose .grow { flex:1; }
.disclose .caret { transition:transform .15s; }
.disclose.open .caret { transform:rotate(90deg); }
pre.code { font-family:var(--mono); font-size:13px; line-height:21px; color:var(--ink); background:var(--well);
border:1px solid var(--hair); border-radius:10px; padding:14px 16px; overflow-x:auto; white-space:pre-wrap;
word-break:break-word; }
/* ── graph ── */
#gwrap { background:var(--well); border:1px solid var(--line); border-radius:16px; overflow:hidden; }
/* The query workbench draws its own result graph (#qstage/#qcanvas/#qzoom);
it shares this chrome so the two graphs read — and handle — the same. */
#gstage, #qstage { position:relative; }
#gcanvas { display:block; width:100%; height:560px; cursor:grab; }
#qcanvas { display:block; width:100%; height:460px; cursor:grab;
background:var(--well); border:1px solid var(--line); border-radius:14px; }
#gcanvas.grabbing, #qcanvas.grabbing { cursor:grabbing; }
.float { position:absolute; background:var(--surface); border:1px solid var(--line); border-radius:12px; box-shadow:var(--shadow); }
#gtools { top:16px; left:16px; display:flex; align-items:center; gap:10px; background:none; border:0; box-shadow:none; }
#glegend { bottom:16px; left:16px; display:flex; align-items:center; gap:14px; height:34px; padding:0 14px; border-radius:17px; }
#glegend span { display:flex; align-items:center; gap:6px; font-size:12.5px; color:var(--text); white-space:nowrap; }
#gzoom { bottom:16px; right:16px; display:flex; align-items:center; height:34px; padding:0 4px; border-radius:17px; }
#qzoom { bottom:14px; right:14px; display:flex; align-items:center; height:34px; padding:0 4px; border-radius:17px; }
#gzoom button, #qzoom button { width:30px; height:28px; border:0; background:none; color:var(--text); font-size:16px; border-radius:14px; }
#gzoom button.lbl, #qzoom button.lbl { width:auto; padding:0 10px; font-size:12px; font-weight:600; color:var(--accent); }
#ginspect { top:16px; right:16px; width:288px; padding:18px; display:flex; flex-direction:column; gap:14px; }
#gscrub { display:flex; flex-direction:column; gap:11px; padding:16px 20px 18px; background:var(--surface); border-top:1px solid var(--line); }
#gscrub input[type=range] { width:100%; accent-color:var(--accent); }
.scrub-ticks { display:flex; justify-content:space-between; font-size:11.5px; color:var(--faint); }
/* ── workflows ── */
/* The plan list reuses .starter (query page's card) — a workflow card is
the same shape: a bold label plus a code-styled gloss line. */
#wfList { display:grid; grid-template-columns:repeat(auto-fit, minmax(300px, 1fr)); gap:12px; align-items:start; }
#wfwrap { background:var(--well); border:1px solid var(--line); border-radius:16px; overflow:hidden; }
#wfstage { position:relative; }
/* The canvas is the reason this page exists — give it the room, not a
token box. Scales with the viewport rather than a fixed guess, with a
floor for short windows. */
/* A plan is a wide, short strip, so the floor here only needs to leave
room to drag a node clear of its row. */
#wfcanvas { display:block; width:100%; height:calc(100vh - 260px); min-height:380px; cursor:default; }
#wfcanvas.connecting { cursor:crosshair; }
#wftools { top:16px; left:16px; display:flex; align-items:center; gap:9px; background:none; border:0; box-shadow:none; }
#wflegend { bottom:16px; left:16px; display:flex; align-items:center; flex-wrap:wrap; gap:8px 14px;
min-height:34px; max-width:min(560px, 62%); padding:7px 14px; border-radius:15px; }
#wflegend span { display:flex; align-items:center; gap:6px; font-size:12.5px; color:var(--text); white-space:nowrap; }
#wflegend .legsep { color:var(--ghost); }
#wfzoom { bottom:16px; right:16px; display:flex; align-items:center; height:34px; padding:0 4px; border-radius:17px; }
#wfzoom button { width:30px; height:28px; border:0; background:none; color:var(--text); font-size:16px; border-radius:14px; }
#wfzoom button.lbl { width:auto; padding:0 10px; font-size:12px; font-weight:600; color:var(--accent); }
#wfinspect { top:16px; right:16px; width:302px; padding:18px; display:flex; flex-direction:column; gap:13px; max-height:488px; overflow-y:auto; }
.wf-badge { display:inline-flex; align-items:center; gap:6px; padding:3px 10px; border-radius:10px; font-size:11.5px; font-weight:600; width:fit-content; }
.wf-field { display:flex; flex-direction:column; gap:5px; }
.wf-field .tiny { color:var(--dim); }
/* A read-only inspector row: the trigger panel is all of these, because a
trigger cannot be authored through CAL and so must not offer inputs that
look editable. */
.wf-ro { display:flex; flex-direction:column; gap:3px; }
.wf-ro .k { font-size:12.5px; color:var(--dim); }
.wf-ro .v { font-size:13.5px; color:var(--ink); overflow-wrap:anywhere; }
.wf-ro .v.mono { font-family:var(--mono); font-size:12px; color:var(--text); }
/* ── the run bar: which run the canvas is tinted by ──
It sits in the page header rather than floating over the canvas, where it
would collide with the tools (top-left) and the inspector (top-right) at
narrow widths. */
.runbar { display:flex; align-items:center; gap:10px; height:34px; padding:0 6px 0 12px;
border:1px solid var(--line2); border-radius:9px; background:var(--surface); flex-shrink:0; }
.runbar .dot { width:8px; height:8px; border-radius:5px; flex-shrink:0; }
.runbar .lbl { font-size:12.5px; color:var(--text); white-space:nowrap; }
.runbar .lbl b { color:var(--ink); font-weight:600; }
.runbar .tally { font-size:12px; color:var(--dim); white-space:nowrap; }
.runbar select { height:26px; width:auto; max-width:230px; border:0; background:none; color:var(--ink);
font-size:12.5px; font-weight:600; font-family:inherit; padding:0 24px 0 8px;
line-height:26px; text-overflow:ellipsis; border-radius:7px; }
.runbar select:hover { background:var(--raise); }
.runbar .sel-wrap { display:flex; align-items:center; width:auto; height:26px; }
.runbar .sel-arrow { right:7px; }
.runbar .go { border:0; background:none; color:var(--accent); font-size:12.5px; font-weight:600;
padding:0 8px; height:26px; border-radius:7px; white-space:nowrap; }
.runbar .go:hover { background:var(--accent-soft); }
/* ── runs ── */
/* Grouped, not one flat grid: "waiting on you" is a different kind of thing
from "finished last Tuesday", and a single list buries the first in the
second. */
.rungroup { display:flex; flex-direction:column; gap:12px; }
.rungroup + .rungroup { margin-top:30px; }
.rungroup > .hd { display:flex; align-items:baseline; gap:10px; }
.rungroup > .hd h3 { font-size:13px; font-weight:600; color:var(--dim); letter-spacing:.07em;
text-transform:uppercase; }
.rungroup > .hd .tiny { color:var(--faint); }
.rungrid { display:grid; grid-template-columns:repeat(auto-fit, minmax(400px, 1fr)); gap:12px; align-items:start; }
.runcard { padding:0; overflow:hidden; display:flex; flex-direction:column; }
.runcard .top { display:flex; align-items:center; gap:11px; padding:15px 18px 13px; }
.runcard .top .plan { flex:1; min-width:0; font-size:15px; font-weight:600; color:var(--ink);
overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.runcard .top .plan .rid { display:block; font-size:12px; font-weight:400; color:var(--faint);
font-family:var(--mono); }
.runcard .meta { display:flex; flex-wrap:wrap; gap:5px 14px; padding:0 18px 14px; font-size:12.5px; color:var(--dim); }
.runcard .steps { display:flex; gap:3px; padding:0 18px 15px; }
.runcard .steps i { height:4px; flex:1; border-radius:2px; background:var(--line); }
.runcard .foot { display:flex; align-items:center; gap:14px; padding:12px 18px;
border-top:1px solid var(--hair); background:var(--well); }
.runcard .foot .grow { flex:1; }
.ask { margin:0 18px 16px; padding:13px 15px; border-radius:10px;
background:var(--warn-soft); border:1px solid var(--warn-line); }
.ask b { color:var(--ink); font-weight:600; font-size:13.5px; }
.ask .who { font-size:12.5px; color:var(--muted); margin-top:3px; }
.ask .acts { display:flex; gap:14px; align-items:center; margin-top:11px; }
.status-tag { display:inline-flex; align-items:center; gap:6px; padding:3px 10px; border-radius:10px;
font-size:11.5px; font-weight:600; flex-shrink:0; }
/* ── tools ── */
#toolBody { display:flex; flex-direction:column; gap:14px; }
.toolgrid { display:grid; grid-template-columns:repeat(auto-fit, minmax(340px, 1fr)); gap:12px; align-items:start; }
.toolcard { text-align:left; background:var(--surface); border:1px solid var(--line); border-radius:14px;
box-shadow:var(--card-shadow); padding:16px 18px; display:flex; flex-direction:column; gap:8px;
cursor:pointer; font-family:inherit; }
.toolcard:hover { border-color:var(--accent-line); }
.toolcard .hd { display:flex; align-items:center; gap:10px; }
.toolcard .hd b { flex:1; min-width:0; font-size:15px; font-weight:600; color:var(--ink);
overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.toolcard .desc { font-size:13.5px; color:var(--text); line-height:19px; }
.toolcard .use { font-size:12.5px; color:var(--faint); }
/* One execution = one line. A run of 40 calls has to stay scannable, so the
detail opens in place rather than each row carrying its payload. */
.exec { display:flex; align-items:center; gap:12px; width:100%; padding:11px 16px; border:0; background:none;
border-top:1px solid var(--hair); text-align:left; font-family:inherit; cursor:pointer; }
.exec:first-child { border-top:0; }
.exec:hover { background:var(--raise); }
.exec .bar { width:3px; align-self:stretch; border-radius:2px; flex-shrink:0; }
.exec .nm { flex:1; min-width:0; font-size:13.5px; color:var(--ink); font-weight:500;
overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.exec .nm span { color:var(--faint); font-weight:400; }
.exec .when { font-size:12px; color:var(--faint); white-space:nowrap; flex-shrink:0; }
.execwrap { display:flex; flex-direction:column; }
.execdet { padding:2px 16px 16px 31px; display:flex; flex-direction:column; gap:12px; background:var(--well);
border-top:1px solid var(--hair); }
/* Reuses the query workbench's own JSON block (pre.code.jsonv) — same
highlighting, just tighter, because these sit inside a list row. */
.execdet pre.code { font-size:11.5px; line-height:17.5px; background:var(--surface);
border:1px solid var(--line); border-radius:9px; padding:11px 13px;
max-height:300px; overflow:auto; white-space:pre-wrap; overflow-wrap:anywhere; }
.execdet .lab { font-size:11.5px; font-weight:600; color:var(--dim); letter-spacing:.07em; }
.schema { display:flex; flex-direction:column; }
.schema .r { display:flex; align-items:baseline; gap:12px; padding:7px 0; border-top:1px solid var(--hair); }
.schema .r:first-child { border-top:0; }
.schema .r .n { width:170px; flex-shrink:0; font-family:var(--mono); font-size:12.5px; color:var(--ink); }
.schema .r .t { font-size:12.5px; color:var(--hash); font-family:var(--mono); }
.schema .r .req { font-size:11px; font-weight:600; color:var(--warn); }
.schema .r .d { flex:1; min-width:0; font-size:12.5px; color:var(--dim); }
/* ── namespace combobox: a real dropdown (known namespaces, click to
pick) that is also just a text field — type a prefix pattern like
"org.*" and it's accepted the same as any exact name. Shared by every
page with a namespace picker, rendered as one pill ("Namespace: value
⌄") rather than each page inventing its own label placement — that
drift was exactly what made the header row's height/position jump
between pages that have this control and pages that don't. */
.ns-combo { position:relative; display:inline-flex; align-items:stretch; height:34px;
border-radius:9px; background:var(--surface); border:1px solid var(--line2);
cursor:text; flex-shrink:0; }
/* A shaded, static tag for "Namespace" — its own background, rounded to
match the pill's own left corners (no `overflow:hidden` on `.ns-combo`
for that — the dropdown menu is an absolutely-positioned child of it and
would get clipped too), and a hairline border to its right — so it
reads as the fixed label, leaving the plain-background value beside it
looking like the part you can edit. */
.ns-combo .lbl { display:flex; align-items:center; padding:0 11px; background:var(--raise);
color:var(--dim); font-size:13px; flex-shrink:0; border-right:1px solid var(--line2);
border-radius:8px 0 0 8px; }
.ns-combo .value { display:flex; align-items:center; gap:8px; padding:0 12px; }
/* Auto-width value: an invisible ::after twin (same text, via data-value)
sizes the grid cell the input shares with it, so the pill hugs "caller"
as tightly as it hugs "org.billing" — the same trick the editable page
title uses (see .pagehead .input-sizer above). `input[type=text]`'s own
rule outranks a single `.ns-combo-input` class on specificity, so every
override below is scoped through `.ns-combo` to actually win. */
.ns-combo .sizer { display:inline-grid; align-items:center; min-width:1em; }
.ns-combo .sizer::after, .ns-combo .ns-combo-input { grid-area:1/1; box-sizing:border-box; }
.ns-combo .sizer::after { content:attr(data-value) ' '; visibility:hidden; white-space:pre; font:inherit; }
.ns-combo .ns-combo-input { border:0; background:none; padding:0; height:auto; width:100%; min-width:1em;
font:600 13px var(--sans); color:var(--ink); cursor:text; }
.ns-combo .ns-combo-input:focus { outline:none; box-shadow:none; }
/* Was pointer-events:none (clicks fell through to the text-cursor pill
behind it) — the caret is a dropdown trigger, not part of the typed
field, so it gets its own hand cursor instead of inheriting the input's
I-beam. Still handled by `wrap`'s mousedown listener: with events no
longer passing through, this becomes the event's target, which is not
`input`, so that listener's fallback path (focus the input) still
fires — same click behavior, just the right cursor over the icon. */
.ns-combo-arrow { display:flex; align-items:center; color:var(--faint); flex-shrink:0; cursor:pointer; }
.ns-combo-menu { position:absolute; z-index:20; top:calc(100% + 4px); right:0; left:auto; min-width:240px;
background:var(--surface); border:1px solid var(--line2); border-radius:10px;
box-shadow:var(--shadow); max-height:230px; overflow-y:auto; padding:4px; }
.ns-combo-opt { padding:7px 9px; border-radius:7px; font-size:13px; color:var(--text); cursor:pointer; }
.ns-combo-opt:hover, .ns-combo-opt.on { background:var(--raise); }
.ns-combo-opt.hint { color:var(--accent); font-family:var(--mono); font-size:12px; }
.ns-combo-empty { padding:7px 9px; font-size:13px; color:var(--faint); }
/* "All namespaces" always sits last, set apart from whatever real
namespaces/hint happen to be above it — a thin rule, not a repeat of
the option padding, so it doesn't read as just another row. */
.ns-combo-opt.all-ns { margin-top:4px; padding-top:11px; border-top:1px solid var(--hair); }
/* ── suggestions ── */
/* Page-level stacks own the rhythm between blocks; `.stack` is an inner
group whose own rows carry their separators, so it takes no gap. */
#sugList, #conBody { display:flex; flex-direction:column; gap:16px; }
.stack { display:flex; flex-direction:column; }
.sug { display:flex; flex-direction:column; gap:16px; padding:24px 28px 22px; }
.tag { display:inline-flex; align-items:center; gap:7px; padding:4px 10px 4px 8px; border-radius:14px; font-size:12px; font-weight:600; }
.evi { display:flex; flex-direction:column; background:var(--well); border:1px solid var(--hair); border-radius:11px; padding:2px 16px; }
.evi-row { display:flex; align-items:center; gap:12px; padding:12px 0; border-bottom:1px solid var(--hair); }
.evi-row:last-child { border-bottom:0; }
.evi-row .t { flex:1; font-size:15px; color:var(--ink); }
.evi-row .w { width:140px; flex-shrink:0; text-align:right; font-size:13px; color:var(--dim); }
.acts { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
.acts .note { flex:1; text-align:right; font-size:13.5px; color:var(--dim); }
/* The confirm step replaces the action row rather than sitting under it —
three live buttons at once is a guessing game. */
.reason { display:flex; flex-direction:column; gap:9px; padding:14px 16px;
background:var(--well); border:1px solid var(--line); border-radius:11px; }
.reason .line { display:flex; align-items:center; gap:10px; }
/* ── activity ── */
.ev { display:flex; align-items:flex-start; gap:16px; padding:14px 0; border-top:1px solid var(--hair); }
.ev .at { width:52px; flex-shrink:0; font-size:13px; color:var(--dim); padding-top:3px; }
.ev .ic { width:18px; flex-shrink:0; display:flex; justify-content:center; padding-top:5px; }
.ev .body { flex:1; display:flex; flex-direction:column; gap:3px; min-width:0; }
.ev .say { font-size:15.5px; color:var(--ink); }
.ev-tags { display:flex; align-items:center; gap:8px; flex-shrink:0; padding-top:4px; }
.ev-tags .tag { padding:3px 9px; border-radius:8px; font-size:11px; }
/* ── connect ── */
.apps { display:flex; gap:16px; }
.app { flex:1; display:flex; flex-direction:column; gap:8px; background:var(--well); border:1px solid var(--line);
border-radius:12px; padding:14px 16px; }
.app .hd { display:flex; align-items:center; gap:9px; }
.app .hd b { flex:1; font-size:14.5px; font-weight:600; color:var(--ink); }
.conns { display:flex; }
.conns div { flex:1; display:flex; justify-content:center; }
.conns i { width:2px; height:22px; background:var(--line2); display:block; border-radius:1px; }
.kv { display:flex; align-items:baseline; gap:12px; padding:9px 0; border-top:1px solid var(--hair); }
.kv .k { width:190px; flex-shrink:0; font-size:13.5px; color:var(--dim); }
.kv .v { flex:1; font-size:14px; color:var(--ink); word-break:break-word; }
/* ── detail panel: an inline card in the page flow (used to be a
floating slide-over that dimmed the whole app behind it). `#panelWrap`
carries the same horizontal inset as `.page` so the card lines up with
whatever page opened it; `#panel` is the card itself, centred at the
usual reading width. "View full screen" expands `#panelWrap` to cover
the viewport instead — for content too long to read comfortably in the
column, not for every open — and the card sheds its own chrome since
the wrap is now playing that role. ── */
#panelWrap { padding:24px 56px 56px 48px; }
#panel { width:100%; max-width:var(--wide); margin:0 auto; background:var(--surface);
border:1px solid var(--line2); border-radius:16px; box-shadow:var(--card-shadow);
padding:28px 30px 32px; overflow-y:auto; display:flex; flex-direction:column; gap:24px; }
#panelWrap.full { position:fixed; inset:0; z-index:45; background:var(--surface);
padding:44px 56px 56px; overflow-y:auto; }
#panelWrap.full #panel { border:0; box-shadow:none; border-radius:0; padding:0; }
.pgroup { display:flex; flex-direction:column; gap:14px; padding-top:20px; border-top:1px solid var(--hair); }
.step { display:flex; gap:14px; }
.step .rail { display:flex; flex-direction:column; align-items:center; width:10px; flex-shrink:0; gap:4px; }
.step .bul { width:10px; height:10px; border-radius:5px; background:var(--ok); flex-shrink:0; }
.step .bul.past { background:var(--surface); border:1.5px solid var(--line2); }
.step .ln { width:1px; flex:1; background:var(--line); }
/* ── developer tab (Settings → Developer) — used to be a sidebar fixed to
the right of every page; now it's a normal card in Settings, present
only once `dev-only` reveals its tab. ── */
.oprow { display:flex; align-items:center; gap:10px; padding:7px 0; border-bottom:1px solid var(--hair);
cursor:pointer; font-family:var(--mono); font-size:11.5px; }
.oprow .t { width:30px; flex-shrink:0; color:var(--ghost); }
.oprow .o { width:70px; flex-shrink:0; }
/* What the operation wrote, in words — the address is on hover. Sans, because
this is prose now; teal mono only when we fall back to a bare hash. */
.oprow .h { flex:1; min-width:0; font-family:var(--sans); font-size:12.5px; color:var(--text);
overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.oprow .h.addr { font-family:var(--mono); font-size:11.5px; color:var(--hash); }
.oprow .h.sys { color:var(--faint); } /* the engine talking to itself */
/* ── toast ── */
#toast { position:fixed; bottom:24px; left:50%; transform:translateX(-50%); background:var(--ink); color:var(--bg);
border-radius:10px; padding:10px 20px; font-size:14px; z-index:99; box-shadow:var(--shadow); display:none; }
@media (max-width:900px) { #rail { display:none; } .page { padding:28px 22px 44px; } }
/* Last word: `hidden` must beat every id-level display rule above. */
[hidden] { display:none !important; }
</style>
<script>
(function () {
var q = new URLSearchParams(location.search);
var t = q.get('theme') || localStorage.getItem('areev.theme');
if (t === 'light' || t === 'dark') document.documentElement.dataset.theme = t;
var d = q.get('dev');
if (d === '1' || (d !== '0' && localStorage.getItem('areev.dev') === '1'))
document.documentElement.classList.add('dev');
})();
</script>
<div id="shell">
<nav id="rail">
<button class="brand" id="brandBtn" type="button" title="Memory">
<img class="logo light" src="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class="nav-item on" data-page="memory">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M5 4.5A1.5 1.5 0 016.5 3H17a1.5 1.5 0 011.5 1.5V21l-6.5-3.4L5.5 21V4.5z" stroke-width="1.7" stroke-linejoin="round"/></svg>
<span class="grow">Memory</span>
</button>
<button class="nav-item" data-page="query">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M4.5 6.5h15M4.5 12h9M4.5 17.5h12" stroke-width="1.7" stroke-linecap="round"/><path d="M16.5 15.5l2.2 2.2" stroke-width="1.7" stroke-linecap="round"/><circle cx="15" cy="14" r="2.6" stroke-width="1.7"/></svg>
<span class="grow">Query</span>
</button>
<button class="nav-item" data-page="activity">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M3 12.5h4.2l2.6-7 4.2 13 2.4-6h4.6" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
<span class="grow">Activity</span>
</button>
<!-- Plan before run before catalog: the order you meet them in. A
trigger has no nav item of its own — it is only meaningful next to
the plan it starts, so it lives on the workflow canvas. -->
<button class="nav-item" data-page="workflows">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><circle cx="5.5" cy="6" r="2.3" stroke-width="1.7"/><circle cx="18.5" cy="6" r="2.3" stroke-width="1.7"/><circle cx="12" cy="18" r="2.3" stroke-width="1.7"/><path d="M7.6 7.2L11 16M16.4 7.2L13 16M7.8 6h8.4" stroke-width="1.7" stroke-linecap="round"/></svg>
<span class="grow">Workflows</span>
<span class="pill soft" id="wfTrgPill" hidden>0</span>
</button>
<button class="nav-item" data-page="runs">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M5 4.5v15l13-7.5-13-7.5z" stroke-width="1.7" stroke-linejoin="round"/></svg>
<span class="grow">Runs</span>
<span class="pill" id="runPill" hidden>0</span>
</button>
<button class="nav-item" data-page="tools">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M9 2.8v5.4M15 2.8v5.4" stroke-width="1.7" stroke-linecap="round"/><path d="M5.8 8.2h12.4v3.2a6.2 6.2 0 01-12.4 0V8.2z" stroke-width="1.7" stroke-linejoin="round"/><path d="M12 17.6v3.6" stroke-width="1.7" stroke-linecap="round"/></svg>
<span class="grow">Tools</span>
</button>
<button class="nav-item" data-page="suggestions">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M12 3.5l1.9 4.9 4.9 1.9-4.9 1.9L12 17.1l-1.9-4.9L5.2 10.3l4.9-1.9L12 3.5z" stroke-width="1.7" stroke-linejoin="round"/></svg>
<span class="grow">Suggestions</span>
<span class="pill" id="sugPill" hidden>0</span>
</button>
<button class="nav-item" data-page="analytics">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M5 19V13.5M11.5 19V8.5M18 19V5" stroke-width="1.7" stroke-linecap="round"/></svg>
<span class="grow">Analytics</span>
</button>
<button class="nav-item" data-page="settings">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke-width="1.7"/><path d="M19.4 13.5a1.7 1.7 0 000-3l-1-.2a6.7 6.7 0 00-.7-1.7l.6-.9a1.7 1.7 0 00-2.4-2.4l-.9.6a6.7 6.7 0 00-1.7-.7l-.2-1a1.7 1.7 0 00-3 0l-.2 1a6.7 6.7 0 00-1.7.7l-.9-.6a1.7 1.7 0 00-2.4 2.4l.6.9a6.7 6.7 0 00-.7 1.7l-1 .2a1.7 1.7 0 000 3l1 .2c.15.6.4 1.17.7 1.7l-.6.9a1.7 1.7 0 002.4 2.4l.9-.6c.53.3 1.1.55 1.7.7l.2 1a1.7 1.7 0 003 0l.2-1c.6-.15 1.17-.4 1.7-.7l.9.6a1.7 1.7 0 002.4-2.4l-.6-.9c.3-.53.55-1.1.7-1.7l1-.2z" stroke-width="1.7" stroke-linejoin="round"/></svg>
<span class="grow">Settings</span>
</button>
</div>
<div class="rail-foot">
<div class="toggle-row" id="whorow" style="display:none;border:0;padding-top:0">
<span id="whoami" title="the principal this session is bound to">…</span>
<button id="signbtn" style="background:none;border:0;color:var(--accent);cursor:pointer;font:inherit;padding:0">Sign in</button>
</div>
<span class="tiny" id="dblabel" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{DB}}</span>
</div>
</nav>
<main id="main">
<!-- ── MEMORY ──
Namespace picker scopes the List view, the Graph view, and the Ask
bar all at once (MEM_NS) — it sits above both view modes rather
than inside either. ── -->
<section class="page" id="page-memory">
<div style="display:flex;align-items:flex-end;gap:16px" class="wide">
<div id="memCrumb" style="flex:1;min-width:0"></div>
<span id="memNsHost"></span>
<div class="seg" id="mview">
<button class="on" data-v="list">List</button>
<button data-v="graph">Graph</button>
</div>
</div>
<div id="listView" style="display:flex;flex-direction:column;gap:24px">
<div class="wide" style="display:flex;flex-direction:column;gap:11px">
<div class="askbar">
<svg width="19" height="19" viewBox="0 0 24 24" fill="none" style="flex-shrink:0"><circle cx="11" cy="11" r="6.6" stroke="var(--accent)" stroke-width="1.8"/><path d="M16 16l4.2 4.2" stroke="var(--accent)" stroke-width="1.8" stroke-linecap="round"/></svg>
<input type="text" id="ask" placeholder="Search your memories — or ask a question and press Enter" autocomplete="off">
<button class="btn sm" id="askBtn">Ask</button>
</div>
<div class="examples" id="examples"></div>
</div>
<div class="banner wide" id="sugBanner" hidden>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" style="flex-shrink:0"><path d="M12 3.5l1.9 4.9 4.9 1.9-4.9 1.9L12 17.1l-1.9-4.9L5.2 10.3l4.9-1.9L12 3.5z" stroke="var(--warn)" stroke-width="1.7" stroke-linejoin="round"/></svg>
<span class="grow" id="sugBannerText"></span>
<span class="go" id="sugBannerGo">Review →</span>
</div>
<div class="wide" id="filterBar" hidden></div>
<div class="card wide" id="answer" hidden></div>
<div class="wide" id="memList"><div class="empty">loading…</div></div>
</div>
<div id="graphView" hidden>
<div id="gwrap">
<div id="gstage">
<canvas id="gcanvas"></canvas>
<div class="float" id="gtools">
<div style="display:flex;align-items:center;gap:9px;height:36px;width:250px;padding:0 12px;background:var(--surface);border:1px solid var(--line);border-radius:10px">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" style="flex-shrink:0"><circle cx="11" cy="11" r="6.6" stroke="var(--dim)" stroke-width="1.9"/><path d="M16 16l4.2 4.2" stroke="var(--dim)" stroke-width="1.9" stroke-linecap="round"/></svg>
<input type="text" id="gjump" placeholder="Jump to anyone…" style="border:0;background:none;padding:0;font-size:13.5px">
</div>
<div class="seg" id="gdepth" style="background:var(--surface);border:1px solid var(--line)">
<button class="on" data-d="1">Direct</button><button data-d="2">2 steps</button>
</div>
</div>
<div class="float" id="glegend"></div>
<div class="float" id="gzoom">
<button id="gout" title="zoom out">−</button><button id="gin" title="zoom in">+</button><button class="lbl" id="gfit">Fit</button>
</div>
<div class="float" id="ginspect" hidden></div>
</div>
<div id="gscrub">
<div style="display:flex;align-items:center;gap:9px">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" style="flex-shrink:0"><circle cx="12" cy="12" r="8.5" stroke="var(--muted)" stroke-width="1.8"/><path d="M12 7.5V12l3 2" stroke="var(--muted)" stroke-width="1.8" stroke-linecap="round"/></svg>
<b style="font-size:13.5px;color:var(--ink)">Rewind</b>
<span class="meta" style="flex:1">drag to see what your agent knew at any point — nothing is ever deleted from the history</span>
<span class="chip on" id="gnow" style="height:26px;padding:0 12px;display:inline-flex;align-items:center">now</span>
</div>
<input type="range" id="grange" min="0" max="100" value="100">
<div class="scrub-ticks" id="gticks"></div>
</div>
</div>
</div>
</section>
<!-- ── ANALYTICS ── -->
<section class="page" id="page-analytics" hidden>
<div class="wide" style="display:flex;align-items:flex-start;gap:16px">
<div id="anCrumb" style="flex:1;min-width:0"></div>
<span id="anNsHost"></span>
</div>
<div class="wide stiles" id="anTiles"></div>
<div class="wide qsec"><span class="sec-label">WHAT'S IN THIS MEMORY</span><i></i>
<span class="tiny">All 12 grain types this memory can hold — click one to run it in Query</span></div>
<div class="wide census" id="anCensus"></div>
<div class="wide qsec"><span class="sec-label">NAMESPACES</span><i></i>
<span class="tiny">Every namespace this session can read — click one to scope the page to it</span></div>
<div class="wide census" id="anNsBreakdown"></div>
<div class="wide qsec"><span class="sec-label">GROWTH</span><i></i>
<span class="tiny" id="anGrowthCaption"></span></div>
<div class="wide" id="anGrowth"></div>
<div class="wide qsec"><span class="sec-label">HOW IT CAN BE QUERIED</span><i></i>
<span class="tiny">The recall legs active on this file</span></div>
<div class="wide legs" id="anLegs"></div>
</section>
<!-- ── ACTIVITY ── -->
<section class="page" id="page-activity" hidden>
<div class="wide" style="display:flex;align-items:flex-start;gap:16px">
<div id="actCrumb" style="flex:1;min-width:0"></div>
<span id="actNsHost"></span>
</div>
<div class="examples wide" id="actFilters"></div>
<div class="wide" id="actList"><div class="empty">loading…</div></div>
</section>
<!-- ── SUGGESTIONS ── -->
<section class="page" id="page-suggestions" hidden>
<div id="sugCrumb" class="wide"></div>
<div class="wide" style="display:flex;align-items:center;gap:16px">
<div class="tabs" id="sugTabs" style="flex:1">
<button class="on" data-s="pending">Needs review</button>
<button data-s="applied">Applied</button>
<button data-s="rejected">Dismissed</button>
</div>
<button class="btn sm" id="runLoop">Run analysis</button>
</div>
<div class="wide" id="sugList"><div class="empty">loading…</div></div>
</section>
<!-- ── RUNS: the governed runtime viewer + HITL approval queue.
Namespace picker shares WF_NS with Workflows/Tools (same rationale:
a run executes a plan, and the plan's namespace IS the run's) —
but unlike those pages, an unpicked namespace here means "every
run" (today's existing behavior, unchanged), not "the bound
default" — a run's own bookkeeping lives in a fixed system
namespace, so "the bound default" is not a run's natural home the
way it is a fact's. ── -->
<section class="page" id="page-runs" hidden>
<div class="wide" style="display:flex;align-items:flex-start;gap:16px">
<div id="runCrumb" style="flex:1;min-width:0"></div>
<span id="runNsHost"></span>
</div>
<div class="wide" id="runList"><div class="empty">loading…</div></div>
</section>
<!-- ── WORKFLOWS: plans as an editable graph ──
One action slot, top right, for whatever this view's primary act is:
"New workflow" on the list, "Save as new plan" in the editor. -->
<!-- Tools: what a step can call, and every call that was made. Both are
Tool grains split by `kind` — one catalog answering two questions
("what can run" / "what did run"), so two tabs rather than two pages.
The namespace picker is deliberately the SAME state the Workflows
page uses (WF_NS): a plan and the tools it binds are one operations
surface, and two independent pickers on the same rows drift. -->
<section class="page" id="page-tools" hidden>
<div id="toolCrumb" class="wide"></div>
<div class="wide" style="display:flex;align-items:center;gap:16px" id="toolTabsRow">
<div class="tabs" id="toolTabs" style="flex:1">
<button class="on" data-t="catalog">Catalog</button>
<button data-t="executions">Executions</button>
</div>
<span id="toolNsHost"></span>
</div>
<div class="wide" id="toolBody"></div>
</section>
<section class="page" id="page-workflows" hidden>
<div class="wide" style="display:flex;align-items:flex-start;gap:16px">
<div id="wfCrumb" style="flex:1;min-width:0"></div>
<span id="wfRunHost"></span>
<span id="wfNsHost"></span>
<button class="btn sm" id="wfNewBtn">New workflow</button>
<button class="btn sm" id="wfSave" hidden>Save as new plan</button>
</div>
<div class="wide" id="wfList"><div class="empty">loading…</div></div>
<div class="wide" id="wfOrphans" hidden></div>
<div id="wfEditorWrap" hidden style="display:flex;flex-direction:column;gap:12px;flex:1;min-height:0;">
<div class="wide" id="wfwrap" style="flex:1;min-height:0;">
<div id="wfstage">
<canvas id="wfcanvas"></canvas>
<div class="float" id="wftools">
<button class="btn sm" id="wfAddNode">+ Node</button>
<button class="btn ghost sm" id="wfResetLayout">Reset layout</button>
<span class="tiny" id="wfHint">Drag a step's dot to connect it</span>
</div>
<div class="float" id="wflegend"></div>
<div class="float" id="wfzoom">
<button id="wfout" title="zoom out">−</button><button id="wfin" title="zoom in">+</button><button class="lbl" id="wffit">Fit</button>
</div>
<div class="float" id="wfinspect" hidden></div>
</div>
</div>
<div class="col" id="wfReasonBox"></div>
</div>
</section>
<!-- ── SETTINGS (formerly "Connect" — the Agent tab plus General,
which now also carries what used to sit in the rail-foot:
developer mode and dark mode. Developer is a third tab, itself
`dev-only` — it used to be a fixed card pinned to the right of
every page; now it's one more tab, present only once Developer
mode is actually on.) ── -->
<section class="page" id="page-settings" hidden>
<div id="setCrumb" class="wide"></div>
<div class="tabs wide" id="conTabs">
<button class="on" data-c="agent">Your agent</button>
<button data-c="general">General</button>
<button class="dev-only" data-c="developer">Developer</button>
</div>
<div class="wide" id="conBody"></div>
</section>
<!-- ── QUERY ── -->
<section class="page" id="page-query" hidden>
<div class="wide" style="display:flex;align-items:center;gap:16px">
<div id="queryCrumb" style="flex:1;min-width:0"></div>
<button class="btn ghost sm" id="qreset" hidden>New query</button>
</div>
<span class="wide sub" id="qintro">Ask the memory a precise question. Every view in this console
runs the same language underneath — start from an example below and edit it.</span>
<div class="wide composer">
<div class="qedit">
<div id="qhl" aria-hidden="true"></div>
<textarea id="qtext" spellcheck="false" rows="3"
placeholder='RECALL facts WHERE subject = "john" LIMIT 20'></textarea>
</div>
<div class="cbar">
<button class="btn sm" id="qrun">Run <span class="kbd">⌘⏎</span></button>
<button class="btn ghost sm" id="qexplain">Explain</button>
<button class="btn ghost sm" id="qsave">Save</button>
<div class="menuwrap"><button class="btn ghost sm hasmenu" id="fmtBtn">Format</button>
<div class="menu" id="fmtMenu" hidden></div></div>
<div style="flex:1"></div>
<span class="tiny" id="qnotice"></span>
</div>
</div>
<div class="wide" id="qerr" hidden></div>
<div class="wide onramp" id="qonramp">
<div class="qsec"><span class="sec-label">START FROM A QUESTION</span><i></i>
<span class="tiny">Each one writes real CAL into the editor — edit it from there</span></div>
<div class="starters" id="qstarters"></div>
<div class="qsec"><span class="sec-label">SAVED & RECENT</span><i></i>
<div class="menuwrap"><button class="btn ghost sm hasmenu" id="savedBtn">All saved</button>
<div class="menu" id="savedMenu" hidden></div></div>
<div class="menuwrap"><button class="btn ghost sm hasmenu" id="histBtn">Full history</button>
<div class="menu" id="histMenu" hidden></div></div></div>
<div class="recents" id="qrecents"></div>
</div>
<div class="wide" id="qresult" hidden>
<div id="qsummary"></div>
<div id="qbar"></div>
<div id="qbody"></div>
<div id="qmore" hidden></div>
</div>
</section>
<!-- ── grain detail: a dedicated inline card, appended right after
whichever page opened it, with its own "view full screen" mode
(see #panelWrap.full above) rather than a floating slide-over. ── -->
<div id="panelWrap" hidden><div id="panel"></div></div>
</main>
</div>
<div id="toast"></div>
<script>
'use strict';
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/&/g,'&').replace(/</g,'<')
.replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''');
const el = (tag, cls, txt) => { const n = document.createElement(tag); if (cls) n.className = cls;
if (txt != null) n.textContent = txt; return n; };
/* Wrap a native <select> with a drawn chevron (see the `select`/`.sel-wrap`
CSS) so it reads as one of this console's own controls rather than the
browser's default box — real native behavior underneath, just restyled. */
function styledSelect(select) {
const wrap = el('div', 'sel-wrap');
wrap.appendChild(select);
const arrow = el('span', 'sel-arrow');
arrow.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none"><path d="M5 9l7 7 7-7" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
wrap.appendChild(arrow);
return wrap;
}
/* ══ page header ══════════════════════════════════════════════════════
One component for every page: a breadcrumb trail (home icon › section ›
optional current item) plus a description line beneath it. Every page
calls this instead of hand-rolling its own <h1>/.sub — home always jumps
to Memory; crumbs is an array of {label, onClick?} with the trailing,
onClick-less entry rendered as the bold "you are here" segment. */
const HOME_ICON = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M4 11.5L12 4l8 7.5M6.5 10v9h11v-9" '
+ 'stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
const EDIT_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M16.5 3.5l4 4L8 20l-5 1 1-5L16.5 3.5z" '
+ 'stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>';
const LOCK_ICON = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none"><rect x="5" y="11" width="14" height="9" rx="2" stroke="currentColor" stroke-width="1.8"/>'
+ '<path d="M8 11V7a4 4 0 018 0v4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>';
/* The detail panel's "view full screen" toggle — four corners pulling
outward to expand, the same four pulling back in to collapse. */
const EXPAND_ICON = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M9 4H4v5M15 4h5v5M9 20H4v-5M15 20h5v-5" '
+ 'stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
const COLLAPSE_ICON = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M4 9V4h5M4 15v5h5M20 9V4h-5M20 15v5h-5" '
+ 'stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
/* An inline-editable title/description field: always the same <input>, in
display state or focused/active state — never swapped for another
element — so becoming editable never shifts the layout around it. A
pencil icon fades in on row hover as the "this is editable" cue; clicking
the text itself works just as well. cfg: {value, placeholder, disabled,
onCommit(newValue)}. lockHint, if given, adds a small icon carrying it as
a native tooltip (used for "why can't I edit this"). */
function editableField(cls, cfg, lockHint) {
const row = el('div', 'edit-row');
// The sizer's data-value drives an invisible ::after twin (same text, same
// font) that the input shares a grid cell with — the cell (and so the
// input) is exactly as wide as the text/placeholder, never wider, so the
// edit/lock icons that follow sit right against the text instead of
// stranded at the far edge of a full-width field.
const sizer = el('span', 'input-sizer ' + cls);
sizer.dataset.value = cfg.value || cfg.placeholder || '';
const input = document.createElement('input');
input.type = 'text'; input.className = cls; input.autocomplete = 'off';
input.value = cfg.value || '';
input.placeholder = cfg.placeholder || '';
input.disabled = !!cfg.disabled;
input.addEventListener('input', () => { sizer.dataset.value = input.value || cfg.placeholder || ''; });
input.addEventListener('blur', () => {
const v = input.value.trim();
if (v !== (cfg.value || '')) cfg.onCommit(v);
});
input.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
else if (e.key === 'Escape') { input.value = cfg.value || ''; sizer.dataset.value = cfg.value || cfg.placeholder || ''; input.blur(); }
});
sizer.appendChild(input);
row.appendChild(sizer);
if (!cfg.disabled) {
const icon = el('span', 'edit-icon'); icon.innerHTML = EDIT_ICON;
icon.onclick = () => input.focus();
row.appendChild(icon);
}
if (lockHint) {
const lock = el('span', 'lock-hint'); lock.innerHTML = LOCK_ICON; lock.title = lockHint;
row.appendChild(lock);
}
return row;
}
/* opts (optional): { editTitle, editDesc: <editableField cfg>, lockHint }.
The current-page segment (either the last crumb's plain label, or the
editable title field when editTitle is set) renders IN the trail row,
right after its own leading "›" — one line, home icon through to "you
are here" — never a separate headline below it. descHtml (or editDesc)
is the one line beneath. */
function renderCrumbHeader(hostId, crumbs, descHtml, opts) {
const host = $(hostId); if (!host) return;
opts = opts || {};
host.textContent = '';
const wrap = el('div', 'pagehead');
const trail = el('div', 'trail');
const home = el('button', 'home'); home.innerHTML = HOME_ICON; home.title = 'Memory'; home.onclick = () => go('memory');
trail.appendChild(home);
const priorCrumbs = opts.editTitle ? crumbs : crumbs.slice(0, -1);
for (const c of priorCrumbs) {
trail.appendChild(el('span', 'sep', '›'));
if (c.onClick) { const b = el('button', 'link', c.label); b.onclick = c.onClick; trail.appendChild(b); }
else trail.appendChild(el('span', 'link', c.label));
}
trail.appendChild(el('span', 'sep', '›'));
if (opts.editTitle) trail.appendChild(editableField('ctitle', opts.editTitle, opts.lockHint));
else trail.appendChild(el('span', 'ctitle', crumbs[crumbs.length - 1].label));
wrap.appendChild(trail);
if (opts.editDesc) wrap.appendChild(editableField('cdesc', opts.editDesc, null));
else if (descHtml) { const d = el('div', 'cdesc'); d.innerHTML = descHtml; wrap.appendChild(d); }
host.appendChild(wrap);
}
/* ══ api ══════════════════════════════════════════════════════════════ */
let TOKEN = sessionStorage.getItem('areev.token') || '';
async function api(url, opts) {
opts = Object.assign({}, opts);
if (TOKEN) opts.headers = Object.assign({}, opts.headers, { Authorization: 'Bearer ' + TOKEN });
let r;
try { r = await fetch(url, opts); } catch (e) { return { ok: false, error: 'network error' }; }
if (r.status === 401) {
const t = window.prompt('This console is protected. Paste its token:');
if (t) { TOKEN = t; sessionStorage.setItem('areev.token', t); return api(url, opts); }
return { ok: false, error: 'not authorised' };
}
try { return await r.json(); } catch (e) { return { ok: false, error: 'bad response' }; }
}
const cal = q => api('/api/cal', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: q }) });
/* Identity: in multi-principal mode (areev ui --auth) the rail shows who
this session is bound to; Sign in stores a bearer token, Sign out
drops back to the read-only anonymous session. */
async function refreshWhoami() {
const w = await api('/api/whoami');
if (!w || !w.ok || w.mode !== 'credentials') return;
const row = $('whorow'); row.style.display = '';
$('whoami').textContent = w.owner ? 'Owner session' : w.principal;
$('signbtn').textContent = TOKEN ? 'Sign out' : 'Sign in';
}
document.addEventListener('DOMContentLoaded', () => {
const btn = $('signbtn');
if (btn) btn.addEventListener('click', () => {
if (TOKEN) { TOKEN = ''; sessionStorage.removeItem('areev.token'); }
else {
const t = window.prompt('Paste your access token:');
if (!t) return;
TOKEN = t; sessionStorage.setItem('areev.token', t);
}
location.reload();
});
refreshWhoami();
});
/* ══ helpers ══════════════════════════════════════════════════════════ */
function toast(msg) {
const t = $('toast'); t.textContent = msg; t.style.display = 'block';
clearTimeout(toast._h); toast._h = setTimeout(() => { t.style.display = 'none'; }, 2000);
}
function copyText(s, label) {
if (!navigator.clipboard) { toast('copy unavailable'); return; }
navigator.clipboard.writeText(s).then(() => toast((label || 'Copied') + ' ✓'), () => toast('Copy failed'));
}
function download(name, text, mime) {
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([text], { type: mime || 'application/json' }));
a.download = name; a.click(); URL.revokeObjectURL(a.href);
}
const hlcMs = h => Math.floor((h || 0) / 65536);
const shortHash = h => h ? h.slice(0, 12) + '…' : '';
const cap = s => s ? s.charAt(0).toUpperCase() + s.slice(1) : '';
/* Capitalise names that read as words ("john" → "John"), but leave
identifiers alone — "Payment_gateway" and "Contract-9107" look wrong. */
const titleize = s => /^[a-z]+( [a-z]+)*$/.test(String(s || '')) ? cap(s) : String(s || '');
const lowerFirst = s => s ? s.charAt(0).toLowerCase() + s.slice(1) : '';
function relTime(ms) {
if (!ms) return '';
const d = Date.now() - ms;
if (d < 45000) return 'just now';
const m = Math.floor(d / 60000); if (m < 60) return m + (m === 1 ? ' minute ago' : ' minutes ago');
const h = Math.floor(m / 60); if (h < 24) return h + (h === 1 ? ' hour ago' : ' hours ago');
const dd = Math.floor(h / 24); if (dd < 30) return dd + (dd === 1 ? ' day ago' : ' days ago');
const mo = Math.floor(dd / 30); return mo + (mo === 1 ? ' month ago' : ' months ago');
}
const shortWhen = ms => {
if (!ms) return '';
const d = Date.now() - ms;
if (d < 45000) return 'now';
const m = Math.floor(d / 60000); if (m < 60) return m + 'm';
const h = Math.floor(m / 60); if (h < 24) return h + 'h';
const dd = Math.floor(h / 24); if (dd < 30) return dd + 'd';
return Math.floor(dd / 30) + 'mo';
};
const dayKey = ms => new Date(ms).toDateString();
function dayLabel(ms) {
const k = dayKey(ms), today = new Date().toDateString();
const y = new Date(Date.now() - 86400000).toDateString();
if (k === today) return 'TODAY';
if (k === y) return 'YESTERDAY';
return new Date(ms).toLocaleDateString(undefined, { day: 'numeric', month: 'long' }).toUpperCase();
}
const clock = ms => new Date(ms).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
const isoTitle = ms => ms ? new Date(ms).toISOString() : '';
/* created_at rides as epoch millis (a number) on stored grains, but an ISO
string on anything hand-written — accept both, never NaN. */
function createdMs(f) {
const c = f && f.created_at;
if (typeof c === 'number') return c;
if (typeof c === 'string') { const p = Date.parse(c); return isNaN(p) ? 0 : p; }
return 0;
}
/* Some writers (areev remember, memory-tool imports) tuck the human text
inside `context` rather than a top-level field. Dig for it — a memory
that renders as an empty row is worse than no row at all. */
function ctxText(f) {
const c = f && f.context;
if (!c || typeof c !== 'object') return '';
for (const k of ['content', 'text', 'message', 'summary', 'description']) {
if (typeof c[k] === 'string' && c[k].trim()) return c[k];
}
return '';
}
/* `full`: skip the 140-char clamp — the one place this matters is the
detail panel, which exists precisely to show what a list row cannot. */
function preview(f, full) {
if (!f) return '';
const v = f.object != null ? f.object : f.content != null ? f.content
: f.description != null ? f.description : f.tool_content != null ? f.tool_content
: f.summary != null ? f.summary : f.title != null ? f.title
: ctxText(f) ? ctxText(f)
: f.data != null ? JSON.stringify(f.data) : '';
const s = typeof v === 'string' ? v : JSON.stringify(v);
if (full) return s;
return s.length > 140 ? s.slice(0, 140) + '…' : s;
}
const cssVar = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
/* ══ language: a triple, said out loud ════════════════════════════════ */
const REL_PHRASE = {
prefers: 'Prefers {o}', likes: 'Likes {o}', dislikes: 'Dislikes {o}',
works_at: 'Works at {o}', employed_by: 'Works at {o}', member_of: 'Is a member of {o}',
lives_in: 'Lives in {o}', based_in: 'Is based in {o}', headquartered_in: 'Headquartered in {o}',
owns_project: 'Owns the {o} project', maintains: 'Maintains {o}', works_on: 'Works on {o}',
collaborates_with: 'Collaborates with {o}', knows: 'Knows {o}', reports_to: 'Reports to {o}',
asked_about: 'Asked about {o}', email: 'Email is {o}', phone: 'Phone number is {o}',
role: 'Role is {o}', title: 'Title is {o}', speaks: 'Speaks {o}', located_in: 'Is located in {o}',
};
/* No sentence is allowed to be a wall of text. A fact's object can be a
serialized record (the loop stores recommendations as Facts), and an
unbroken 1.5 KB of JSON has no wrap opportunities — it just blows the
column out sideways. */
const MAX_SAY = 180;
/* `full`: skip the clamp — see preview() above. */
const clampText = (s, full) => (!full && s.length > MAX_SAY) ? s.slice(0, MAX_SAY).trimEnd() + '…' : s;
function predicate(g, full) {
const f = g.fields || {};
if (g.type === 'fact') {
const r = f.relation || '', o = f.object;
const os = clampText(typeof o === 'string' ? o : JSON.stringify(o == null ? '' : o), full);
const tpl = REL_PHRASE[r];
if (tpl) return tpl.replace('{o}', os);
if (!r) return os;
return cap(r.replace(/_/g, ' ')) + ' ' + os;
}
const fallback = 'A ' + (g.type || 'memory') + ' with no readable text';
if (g.type === 'tool') {
const name = f.tool_name || 'A tool';
const body = f.tool_content || ctxText(f) || '';
return name + (f.is_error ? ' failed' : ' ran') + (body ? ' — ' + clampText(body, full) : '');
}
/* A run checkpoint is the runtime's own bookkeeping — its body is the
scheduler's serialized state, which has no sentence in it. Say which run
and which step it belongs to instead of calling it unreadable. */
if (g.type === 'state' && f.checkpoint && f.run_id != null)
return 'Checkpoint of run ' + f.run_id + (f.superstep != null ? ' \u00b7 step ' + f.superstep : '');
if (g.type === 'observation') return f.content || f.object || ctxText(f) || fallback;
if (g.type === 'event') return f.content || f.description || preview(f, full) || fallback;
if (g.type === 'goal') return f.description || f.content || preview(f, full) || fallback;
return preview(f, full) || fallback;
}
/* `full`: pass through to predicate()/preview() — the detail panel wants
the untruncated text; every list/card/row view wants the clamp. */
function sentence(g, full) {
const f = g.fields || {}, p = predicate(g, full);
if (!f.subject) return p;
const s = String(f.subject);
/* Observations and events are free text that usually names the subject
already — prefixing it again gives "john john asked about…". */
if (p.toLowerCase().startsWith(s.toLowerCase())) return cap(p);
return titleize(s) + ' ' + lowerFirst(p);
}
/* Where did this come from, in words a human can check. Returned in parts so
callers that already show a timestamp can drop the "Learned …" one. */
function provenanceParts(g) {
const f = g.fields || {}, bits = [];
const prevGrain = f.derived_from && BYHASH[f.derived_from];
const was = g._prevValue
|| (prevGrain ? (typeof (prevGrain.fields || {}).object === 'string'
? prevGrain.fields.object : preview(prevGrain.fields)) : null);
if (was) bits.push('Changed from ' + was);
const when = createdMs(f) || hlcMs(g.hlc);
if (!bits.length) bits.push('Learned ' + relTime(when));
if (g.type === 'observation') bits.push('noticed by your agent, not confirmed');
if (f.namespace && f.namespace !== 'shared') bits.push('in ' + f.namespace);
if (typeof f.confidence === 'number' && f.confidence < 0.75) bits.push('low confidence');
return bits;
}
const provenance = g => provenanceParts(g).join(' · ');
/* ══ state ════════════════════════════════════════════════════════════ */
let BROWSE = [], BYHASH = {}, STATS = {}, CONFIG = null, LOG = [], RECS = {}, TELEMETRY = null;
let PAGE = 'memory', MVIEW = 'list', SUGTAB = 'pending', CONTAB = 'agent', ACTFILTER = 'all';
let TOOLTAB = 'catalog', TOOL_SEL = null;
let ENTITY = null, ANSWER = null, SEL = null, ACTIVE_ENTS = [];
const isGone = g => !!(g.forgotten || g.missing || g.op === 'forget');
const isCurrent = g => !isGone(g) && !g.superseded_by && !g._stale;
/* Areev Loop keeps its own bookkeeping in the file (namespace "areev-loop",
subject "__loop_state__"). It is a real grain, but it is not something
the agent remembers *about anyone* — keep it out of the human views.
It stays reachable from the op-log and the CAL console. */
const INTERNAL_NS = new Set(['areev-loop']);
function isInternal(g) {
const f = g.fields || {};
if (INTERNAL_NS.has(f.namespace)) return true;
const s = f.subject;
return typeof s === 'string' && /^__.*__$/.test(s);
}
const currentGrains = () => BROWSE.filter(g => isCurrent(g) && !isInternal(g));
/* The Memory page's own namespace scope — same pattern as WF_ROWS/wfRows()
(Workflows/Tools): null means "the bound default", which is BROWSE,
already loaded, no extra fetch; anything else fetched and cached
separately, leaving BROWSE alone for the pages that still depend on it
meaning "the bound default" (the rail, Settings, and everything else
that doesn't have a picker of its own). Threaded through the List view,
the Graph view, and the Ask bar. */
let MEM_NS = null, MEM_ROWS = null, MEM_BYHASH = null;
const memRows = () => MEM_ROWS || BROWSE;
const memByHash = () => MEM_BYHASH || BYHASH;
const memGrains = () => memRows().filter(g => isCurrent(g) && !isInternal(g));
async function memSetNamespace(ns) {
MEM_NS = (!ns || ns === boundNamespace()) ? null : ns;
if (MEM_NS) {
MEM_ROWS = await browseForNamespace(MEM_NS);
MEM_BYHASH = {};
for (const g of MEM_ROWS) MEM_BYHASH[g.hash] = g;
} else {
MEM_ROWS = null; MEM_BYHASH = null;
}
// A namespace switch invalidates whatever entity the list/graph was
// focused on — it may not even exist in the new scope.
ENTITY = null; ANSWER = null;
render();
}
/* The store keeps one head per (namespace, subject, relation) — a plain
re-ADD of the same pair replaces the old value without logging a
SUPERSEDE, so /api/browse cannot tell us which row is live. Resolve it
the same way the store does: within a key, the newest op wins. Without
this the list shows a replaced value as if it were current. */
function headHashes(grains) {
const best = new Map();
for (const g of grains) {
if (isGone(g) || (g.type && g.type !== 'fact')) continue;
const f = g.fields || {};
if (!f.subject || !f.relation) continue;
const k = (f.namespace || '') + '\0' + f.subject + '\0' + f.relation;
const cur = best.get(k);
if (!cur || (g.op_seq || 0) > (cur.op_seq || 0)) best.set(k, g);
}
const out = new Set();
for (const g of best.values()) out.add(g.hash);
return out;
}
function markHeads() {
const heads = headHashes(BROWSE);
const byKey = new Map();
for (const g of BROWSE) {
g._stale = false; g._prevValue = null;
if (isGone(g) || (g.type && g.type !== 'fact')) continue;
const f = g.fields || {};
if (!f.subject || !f.relation) continue;
const k = (f.namespace || '') + '\0' + f.subject + '\0' + f.relation;
if (!byKey.has(k)) byKey.set(k, []);
byKey.get(k).push(g);
}
for (const list of byKey.values()) {
list.sort((a, b) => (a.op_seq || 0) - (b.op_seq || 0));
list.forEach((g, i) => {
g._stale = !heads.has(g.hash);
if (!g._stale && i > 0) {
const p = list[i - 1].fields || {};
g._prevValue = typeof p.object === 'string' ? p.object : null;
}
});
}
}
/* ══ entities ═════════════════════════════════════════════════════════ */
const PERSONISH = new Set(['prefers','likes','dislikes','works_at','lives_in','employed_by','knows',
'collaborates_with','owns_project','reports_to','asked_about','email','phone','speaks','role','title']);
const ORGISH = new Set(['works_at','employed_by','member_of','customer_of']);
const PROJECTISH = new Set(['owns_project','maintains','works_on','assigned_to']);
const PLACEISH = new Set(['lives_in','based_in','headquartered_in','located_in']);
/* Relations whose object is another entity; everything else names a VALUE
that belongs to its subject. `vendor: cobalt_cloud` is an edge between two
things the memory knows; `amount: 4400.00` is a property of one invoice,
and drawing it as a peer node is what turns a graph of twenty entities
into a hairball of two hundred. Used by the graph only — the list view
wants every value it can show. */
const ENTITY_REL = new Set(['works_at','employed_by','member_of','customer_of','reports_to',
'assigned_to','owner','vendor','escalates_to','corrected_by','owns_project','maintains',
'works_on','knows','collaborates_with','lives_in','based_in','headquartered_in','located_in',
'manages','supervises','part_of','belongs_to','depends_on','supplier','contact','approver']);
/* Plainly a literal — a number, an amount, a date, a boolean, a term like
`net_45`. Vetoed even under an entity relation, so an unfamiliar schema
cannot smuggle a scalar back in as a node. */
const VALUEISH = /^(true|false|yes|no|none|null)$|^[\d.,]+$|^\d{4}-\d{2}-\d{2}|^\d[\d.,_]*\s*_?(usd|eur|gbp|percent|days?|business_days?|hours?|months?)$|^net_?\d+$/i;
/* A tool call carries no subject, but it is plainly *about* the tool —
without this every tool call falls into one anonymous "Everything else"
heap. The graph opts out (a tool with no relations would be a lone dot). */
const subjectOf = (g, withTools) => {
const f = g.fields || {};
return f.subject || (withTools !== false && g.type === 'tool' ? f.tool_name : null) || null;
};
function buildEntities(grains, opts) {
const withTools = !(opts && opts.tools === false);
/* `entityObjects` keeps an object only when it is something the memory
knows ABOUT — it is a subject somewhere too, or it arrived through a
relation that points at an entity. The graph asks for this; every other
caller wants the values as well. */
const entityObjects = !!(opts && opts.entityObjects);
const subjects = new Set();
if (entityObjects) for (const g of grains) { const s = subjectOf(g, withTools); if (s) subjects.add(s); }
const keepObject = (rel, obj) => !entityObjects
|| ((subjects.has(obj) || ENTITY_REL.has(rel)) && !VALUEISH.test(obj));
const map = new Map();
const ensure = n => { if (!map.has(n)) map.set(n, { name: n, kind: 'thing', count: 0, deg: 0 }); return map.get(n); };
for (const g of grains) {
const f = g.fields || {};
const s = subjectOf(g, withTools);
if (s) ensure(s).count++;
if (g.type === 'fact' && typeof f.object === 'string' && f.object && f.object.length <= 64
&& keepObject(f.relation || '', f.object)) ensure(f.object).deg++;
}
for (const g of grains) {
const f = g.fields || {}, r = f.relation || '';
if (f.subject && PERSONISH.has(r)) ensure(f.subject).kind = 'person';
if (g.type === 'fact' && typeof f.object === 'string' && map.has(f.object)) {
const e = map.get(f.object);
if (ORGISH.has(r)) e.kind = 'org';
else if (PROJECTISH.has(r)) e.kind = 'project';
else if (PLACEISH.has(r)) e.kind = 'org';
}
}
return [...map.values()].sort((a, b) => (b.count - a.count) || (b.deg - a.deg) || a.name.localeCompare(b.name));
}
const KIND_VAR = { person: '--cat-person', org: '--cat-org', project: '--cat-project',
thing: '--cat-thing', note: '--cat-note' };
/* ══ boot ═════════════════════════════════════════════════════════════ */
async function boot() {
/* The server hands us the full path; show the file name and keep the
path in the tooltip so the rail stays readable. */
const full = ($('dblabel').textContent || '').trim();
DB_PATH = full;
$('dblabel').textContent = full.split('/').pop() || full;
$('dblabel').title = full;
wireChrome();
applyHash();
await Promise.all([loadStats(), loadBrowse(), loadLog(), loadConfig(), loadCaps(), loadNamespaces()]);
await loadRecs('pending');
if (WF_DEEPLINK) { wfOpen(WF_DEEPLINK); WF_DEEPLINK = null; }
if (PAGE === 'suggestions' && !RECS[SUGTAB]) await loadRecs(SUGTAB);
render();
if (PAGE === 'memory' && MVIEW === 'graph') Graph.mount();
addEventListener('hashchange', () => {
if (applyHash()) {
if (WF_DEEPLINK) { wfOpen(WF_DEEPLINK); WF_DEEPLINK = null; }
render();
if (MVIEW === 'graph') Graph.mount();
}
});
}
let DB_PATH = '';
async function loadStats() { STATS = await api('/api/stats') || {}; }
async function loadConfig() { CONFIG = await api('/api/config'); }
/* Every namespace this session can read, for the namespace pickers on
Activity/Workflows/etc. `null` = couldn't load (e.g. a very old build with
no /api/namespaces route) — pickers fall back to just the bound default. */
let NAMESPACES = null;
async function loadNamespaces() {
const r = await api('/api/namespaces');
NAMESPACES = (r && r.ok && Array.isArray(r.namespaces)) ? r.namespaces : null;
}
/* A namespace <select>, shared by every page that filters by it. `current`
is the bound value (falls back to the session default); onChange gets the
picked namespace or '*' for "all namespaces this session can read". */
/* A namespace picker that is a dropdown AND a text field at once: click it
for the known-namespace list (with live counts), or just type — a prefix
pattern like "org.*" is accepted exactly like an exact name, since the
server (not this control) is what actually validates and gates it. */
function nsCombo(id, current, onChange) {
const bound = boundNamespace();
const list = NAMESPACES && NAMESPACES.length ? NAMESPACES : [{ namespace: bound, count: null }];
const options = list.map(n => ({ value: n.namespace, label: n.namespace + (typeof n.count === 'number' ? ' (' + n.count + ')' : '') }));
// "All namespaces" (server value '*') is kept out of `options` rather than
// unshifted/pushed onto it: it isn't a real namespace to fuzzy-match
// against, it's a distinct "stop narrowing and search everything" action
// — renderMenu() always appends it itself, last, regardless of what's
// typed (a separator sets it apart from whatever IS filtered above it).
const ALL_NS = { value: '*', label: 'All namespaces' };
const known = new Set(options.map(o => o.value).concat(ALL_NS.value));
const wrap = el('div', 'ns-combo'); wrap.id = id;
wrap.title = 'Scope this page to one namespace, or type a prefix like "org.*" to include its descendants too.';
wrap.appendChild(el('span', 'lbl', 'Namespace'));
const sizer = el('span', 'sizer');
const input = document.createElement('input');
input.type = 'text'; input.className = 'ns-combo-input'; input.autocomplete = 'off'; input.spellcheck = false;
input.placeholder = 'namespace, or prefix.*';
input.value = current || bound;
sizer.dataset.value = input.value;
sizer.appendChild(input);
const arrow = el('span', 'ns-combo-arrow');
arrow.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none"><path d="M5 9l7 7 7-7" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
const menu = el('div', 'ns-combo-menu'); menu.hidden = true;
function renderMenu() {
const typed = input.value.trim();
const f = typed.toLowerCase();
menu.textContent = '';
for (const o of options) {
if (f && !o.label.toLowerCase().includes(f) && !o.value.toLowerCase().includes(f)) continue;
const row = el('div', 'ns-combo-opt' + (o.value === input.value ? ' on' : ''), o.label);
row.onmousedown = e => { e.preventDefault(); commit(o.value); };
menu.appendChild(row);
}
if (typed && !known.has(typed)) {
const row = el('div', 'ns-combo-opt hint', (typed.endsWith('*') ? 'Use prefix ' : 'Use ') + '"' + typed + '"');
row.onmousedown = e => { e.preventDefault(); commit(typed); };
menu.appendChild(row);
}
// Checked before "All namespaces" is appended below, so a typed filter
// that matches nothing still gets its own "nothing matches" message —
// "All namespaces" is a way out of that, not a match for it.
if (!menu.childElementCount) menu.appendChild(el('div', 'ns-combo-empty', 'No matching namespace'));
const allRow = el('div', 'ns-combo-opt all-ns' + (ALL_NS.value === input.value ? ' on' : ''), ALL_NS.label);
allRow.onmousedown = e => { e.preventDefault(); commit(ALL_NS.value); };
menu.appendChild(allRow);
}
function commit(v) {
v = (v || '').trim() || (current || bound);
input.value = v; sizer.dataset.value = v; menu.hidden = true;
if (v !== current) onChange(v);
}
input.addEventListener('focus', () => { renderMenu(); menu.hidden = false; });
input.addEventListener('input', () => { sizer.dataset.value = input.value; renderMenu(); });
input.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); commit(input.value); input.blur(); }
else if (e.key === 'Escape') { input.value = current || bound; sizer.dataset.value = input.value; menu.hidden = true; input.blur(); }
});
input.addEventListener('blur', () => commit(input.value));
// The arrow (and the label, and the pill's own padding) aren't the
// input — a plain click there hits the pill, not the field inside it, and
// does nothing. Forward it to the input's own focus, which is what
// actually opens the menu.
wrap.addEventListener('mousedown', e => { if (e.target === input) return; e.preventDefault(); input.focus(); });
const value = el('div', 'value'); value.appendChild(sizer); value.appendChild(arrow);
wrap.appendChild(value); wrap.appendChild(menu);
return wrap;
}
const boundNamespace = () => (CONFIG && CONFIG.session && CONFIG.session.namespace) || 'shared';
/* Per-namespace browse cache for pages with a namespace picker. The bound
session default always reads the already-loaded global BROWSE — no extra
fetch, and it stays what the rail/entities/graph use. A different
namespace fetches once and caches (switching back and forth is instant). */
const NS_BROWSE_CACHE = new Map();
async function browseForNamespace(ns) {
if (!ns || ns === boundNamespace()) return BROWSE;
if (NS_BROWSE_CACHE.has(ns)) return NS_BROWSE_CACHE.get(ns);
const r = await api('/api/browse?limit=2000&ns=' + encodeURIComponent(ns));
const rows = (r && r.ok && r.grains) ? r.grains : [];
NS_BROWSE_CACHE.set(ns, rows);
return rows;
}
async function loadBrowse() {
const r = await api('/api/browse?limit=2000');
BROWSE = (r && r.ok && r.grains) ? r.grains : [];
BYHASH = {};
for (const g of BROWSE) BYHASH[g.hash] = g;
markHeads();
}
async function loadLog() { const r = await api('/api/log?limit=400'); LOG = Array.isArray(r) ? r : []; }
/* "Needs review" also covers `approved` — a recommendation you approved but
whose apply did not land would otherwise belong to no tab at all. */
const TAB_STATUS = { pending: ['pending', 'approved'], applied: ['applied'], rejected: ['rejected'] };
async function loadRecs(tab) {
const out = [];
for (const s of (TAB_STATUS[tab] || [tab])) {
const r = await api('/api/loop/recommendations?status=' + encodeURIComponent(s));
if (r && r.ok && Array.isArray(r.recommendations)) out.push(...r.recommendations);
}
RECS[tab] = out;
if (tab === 'pending') {
const n = out.length;
$('sugPill').hidden = !n; $('sugPill').textContent = n;
}
}
async function refresh() {
await Promise.all([loadStats(), loadBrowse(), loadLog()]);
await loadRecs('pending');
render();
}
/* ══ chrome ═══════════════════════════════════════════════════════════ */
function wireChrome() {
$('brandBtn').onclick = () => go('memory');
$('nav').querySelectorAll('.nav-item').forEach(b => { b.onclick = () => go(b.dataset.page); });
$('mview').querySelectorAll('button').forEach(b => {
b.onclick = () => { MVIEW = b.dataset.v; render(); if (MVIEW === 'graph') Graph.mount(); };
});
/* Developer mode / Dark mode toggles now live in Settings → General
(renderConnectGeneral), rebuilt fresh each visit — see settingsToggle(). */
$('askBtn').onclick = () => runAsk($('ask').value);
// The bar is 56px tall, the input's own line-box is much shorter — click
// the bar's own padding above/below the text and it should still focus
// the field, not just the exact pixels the glyphs occupy.
$('ask').closest('.askbar').addEventListener('mousedown', e => {
if (e.target === $('ask')) return; e.preventDefault(); $('ask').focus();
});
$('ask').addEventListener('keydown', e => { if (e.key === 'Enter') runAsk($('ask').value); });
$('ask').addEventListener('input', () => { if (!$('ask').value) { ANSWER = null; }
renderExamples(); renderMemList(); });
$('sugBannerGo').onclick = () => go('suggestions');
$('sugTabs').querySelectorAll('button').forEach(b => {
b.onclick = async () => { SUGTAB = b.dataset.s; if (!RECS[SUGTAB]) await loadRecs(SUGTAB); render(); };
});
$('conTabs').querySelectorAll('button').forEach(b => { b.onclick = () => { CONTAB = b.dataset.c; render(); }; });
$('toolTabs').querySelectorAll('button').forEach(b => { b.onclick = () => { TOOLTAB = b.dataset.t; TOOL_SEL = null; render(); }; });
$('runLoop').onclick = runAnalysis;
/* the run button is a write too — gate it once config lands */
$('qrun').onclick = () => runQuery();
$('qtext').addEventListener('input', () => { syncEditor(); queryNotice(); });
$('qtext').addEventListener('scroll', () => { $('qhl').scrollTop = $('qtext').scrollTop; });
$('qtext').addEventListener('keydown', e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) runQuery(); });
$('qexplain').onclick = () => { const t = $('qtext').value.trim();
if (t) runQuery(/^EXPLAIN\b/i.test(t) ? t : 'EXPLAIN ' + t); };
$('qsave').onclick = saveCurrentQuery;
$('qreset').onclick = resetQuery;
$('fmtBtn').onclick = () => openMenu('fmtMenu', buildFormatMenu);
$('histBtn').onclick = () => openMenu('histMenu', buildHistoryMenu);
$('savedBtn').onclick = () => openMenu('savedMenu', buildSavedMenu);
addEventListener('resize', () => { if (PAGE === 'query' && Q.view === 'cards') layoutMasonry(); });
document.addEventListener('keydown', e => {
if (e.key === 'Escape') closePanel();
if (e.key === '/' && document.activeElement === document.body) { e.preventDefault(); $('ask').focus(); }
});
Graph.wire();
WFGraph.wire();
$('wfNewBtn').onclick = wfNew;
$('wfAddNode').onclick = wfAddNode;
$('wfResetLayout').onclick = () => { WFGraph.resetOverrides(); WFGraph.mount(); };
$('wfSave').onclick = wfArmSave;
}
/* Deep links: #memory · #graph · #activity · #suggestions · #settings/agent */
/* Set by applyHash when the URL names a specific plan (#workflows/<hash>);
consumed once BROWSE has loaded (boot() and the hashchange listener both
need to open it, since a deep link can arrive either way). */
let WF_DEEPLINK = null;
function applyHash() {
const raw = (location.hash || '').replace(/^#/, '');
if (!raw) return false;
const [head, tail] = raw.split('/');
if (head === 'graph') { if (PAGE !== 'memory') closePanelIfOpen(); PAGE = 'memory'; MVIEW = 'graph'; return true; }
/* #triggers was its own page until triggers moved onto the canvas. Keep
the old link alive rather than dead-ending a bookmark: it now means "show
me what starts things", which is the plan list. */
if (head === 'triggers') {
if (PAGE !== 'workflows') closePanelIfOpen();
PAGE = 'workflows'; WF_SEL = null; WF_DRAFT = null; WF_PICK = null; return true;
}
if (['memory', 'analytics', 'activity', 'runs', 'tools', 'workflows', 'suggestions', 'settings', 'query'].includes(head)) {
if (head !== PAGE) closePanelIfOpen();
PAGE = head;
if (head === 'memory') MVIEW = 'list';
if (head === 'settings' && ['agent', 'general', 'developer'].includes(tail)) CONTAB = tail;
if (head === 'suggestions' && ['pending', 'applied', 'rejected'].includes(tail)) SUGTAB = tail;
if (head === 'tools') {
if (['catalog', 'executions'].includes(tail)) TOOLTAB = tail;
TOOL_SEL = null;
}
if (head === 'workflows') {
if (tail && /^[0-9a-f]{8,64}$/i.test(tail)) WF_DEEPLINK = tail;
else { WF_SEL = null; WF_DRAFT = null; WF_PICK = null; }
}
return true;
}
return false;
}
function syncHash() {
const h = PAGE === 'memory' ? (MVIEW === 'graph' ? 'graph' : 'memory')
: PAGE === 'settings' ? 'settings/' + CONTAB
: PAGE === 'suggestions' ? 'suggestions/' + SUGTAB
: PAGE === 'tools' ? 'tools/' + TOOLTAB
: PAGE === 'workflows' ? 'workflows' + (WF_SEL ? '/' + WF_SEL : '') : PAGE;
if (location.hash.replace(/^#/, '') !== h) history.replaceState(null, '', '#' + h);
}
function go(page) {
if (page !== PAGE) closePanelIfOpen();
PAGE = page;
if (page === 'suggestions' && !RECS[SUGTAB]) loadRecs(SUGTAB).then(render);
// Same reset applyHash() already does for a bare "#workflows" — without
// it, the sidebar's generic nav click left an open draft/selection in
// place, so "Workflows" looked like it wasn't navigating at all when you
// were mid-edit (it re-rendered the same editor you were already on).
if (page === 'workflows') { WF_SEL = null; WF_DRAFT = null; WF_PICK = null; }
render();
}
/* ══ runs: the governed runtime ═══════════════════════════════════════
ONE index, loaded once, shared by this page and the workflow canvas's run
overlay. Two surfaces asking the server the same question separately is
exactly how they drift: the tint on a canvas node and the strip on a card
here are the same three facts, so they read them from the same place.
`/api/run/list` returns id + outcome only, so which plan a run executed
comes from `inspect` — one request per run, but also the only place
plan_hash, the principal and the pending asks exist. Where inspect can't
say (an older journal), the plan is recovered from the run's own step
grains, which name it in `related_to`. */
let RUNIDX = null, RUNIDX_INFLIGHT = null;
/* The Runs page's namespace-scoped view (#165). The SERVER filters, so a
quiet tenant's runs are not lost behind a busier tenant's newest page —
the old client-side filter over a fixed 50 read as "this namespace has no
runs" while it had open approvals. Cached per (namespace, page size). */
let RUNIDX_NS = null, RUNIDX_NS_KEY = null, RUNIDX_NS_INFLIGHT = null;
let RUN_LIMIT = 100;
const RUN_LIMIT_MAX = 500; /* the server clamps here too */
/* Run-journal Tool grains: the store's record of what each step actually did.
`isCurrent` alone leaves exactly one row per (run, node) — the journal
writes the intent as Pending and then SUPERSEDES it with the result, so the
superseded intent drops out and what survives IS the step's current state.
No head-resolution needed; that is the invariant doing the work. */
function runStepGrains() {
return wfRows().filter(g => {
const f = g.fields || {};
return g.type === 'tool' && f.kind !== 'definition' && f.run_id && f.node && isCurrent(g);
});
}
/** The plan a step grain was recorded against, via `mg:step_action:<node>`. */
function stepPlanHash(f) {
for (const r of (Array.isArray(f.related_to) ? f.related_to : [])) {
if (r && typeof r.relation_type === 'string' && r.relation_type.startsWith('mg:step_action:')) {
return String(r.hash || '').replace(/^sha256:/, '');
}
}
return null;
}
/* Four states, because "pending" means two different things. A step still
Pending in a run that is *open* is waiting on someone; the same row in a
run that was canceled or failed is simply where it stopped, and colouring
that orange would invite an approval that can never arrive. */
const STEP_TONE = { done: 'ok', waiting: 'warn', failed: 'danger', stopped: 'ghost' };
const STEP_WORD = { done: 'done', waiting: 'waiting on a person', failed: 'failed', stopped: 'not finished' };
function stepState(f, outcome) {
if (f.is_error === true) return 'failed';
const st = String(f.status || 'completed');
if (st === 'failed' || st === 'error') return 'failed';
if (st !== 'pending') return 'done';
return outcome && outcome !== 'open' ? 'stopped' : 'waiting';
}
/** node → { state, grain } for one run. Latest attempt wins. */
function runStepStates(runId, outcome) {
const out = new Map();
for (const g of runStepGrains()) {
const f = g.fields;
if (f.run_id !== runId) continue;
const prev = out.get(f.node);
const rank = (f.superstep || 0) * 1e13 + (f.attempt || 0) * 1e11 + (createdMs(f) || 0);
if (prev && prev.rank >= rank) continue;
out.set(f.node, { state: stepState(f, outcome), grain: g, rank });
}
return out;
}
/** Forget every cached run index. Separate from fetching on purpose: the
caller that invalidates (a respond, a "Show more") is not always the view
that will read next, and a fetch bundled into the reset built the
UNSCOPED index — inspect fan-out included — for a scoped page that then
threw it away and built its own. */
function resetRunIndexes() {
RUNIDX = null; RUNIDX_INFLIGHT = null;
RUNIDX_NS = null; RUNIDX_NS_KEY = null; RUNIDX_NS_INFLIGHT = null;
}
async function loadRuns(force) {
if (force) resetRunIndexes();
if (RUNIDX) return RUNIDX;
if (RUNIDX_INFLIGHT) return RUNIDX_INFLIGHT;
RUNIDX_INFLIGHT = buildRunIndex('/api/run/list?limit=' + RUN_LIMIT).then(idx => {
/* A failed load is returned to this caller but NOT cached: the next
render must retry, or one dropped connection pins the page to
"failed to load runs" until something else happens to change the
cache key. */
if (!idx.error) RUNIDX = idx;
RUNIDX_INFLIGHT = null; return idx;
});
return RUNIDX_INFLIGHT;
}
/** The run index for ONE namespace (or an `org.*` prefix), filtered by the
server. Only the Runs page reads this; the canvas overlay and the Tools
page keep the unscoped index, because a plan's runs may have been started
under a different session namespace than the plan lives in. */
async function loadRunsScoped(ns) {
const key = ns + '|' + RUN_LIMIT;
if (RUNIDX_NS_KEY !== key) { RUNIDX_NS = null; RUNIDX_NS_INFLIGHT = null; RUNIDX_NS_KEY = key; }
if (RUNIDX_NS) return RUNIDX_NS;
if (RUNIDX_NS_INFLIGHT) return RUNIDX_NS_INFLIGHT;
RUNIDX_NS_INFLIGHT = buildRunIndex('/api/run/list?ns=' + encodeURIComponent(ns) + '&limit=' + RUN_LIMIT).then(idx => {
if (RUNIDX_NS_KEY === key) {
if (!idx.error) RUNIDX_NS = idx; // same rule as loadRuns: never cache a failure
RUNIDX_NS_INFLIGHT = null;
}
return idx;
});
return RUNIDX_NS_INFLIGHT;
}
/** Open runs across the WHOLE memory, for the nav badge. One list read, no
per-run inspect: the badge needs `outcome`, which the list already
carries. Capped at the server's own ceiling, so a memory with more open
runs than that undercounts rather than stalling the page. */
async function runOpenCount() {
const list = await api('/api/run/list?limit=' + RUN_LIMIT_MAX);
if (!list || !list.ok || !Array.isArray(list.runs)) return 0;
return list.runs.filter(r => r.outcome === 'open').length;
}
async function buildRunIndex(url) {
{
const idx = { runs: [], byId: new Map(), byPlan: new Map(), error: null, total: 0, truncated: false, unattributed: 0 };
const list = await api(url);
if (!list || !list.ok) {
idx.error = (list && list.error) || 'failed to load runs';
return idx;
}
idx.total = typeof list.total === 'number' ? list.total : (Array.isArray(list.runs) ? list.runs.length : 0);
idx.truncated = !!list.truncated;
idx.unattributed = typeof list.unattributed === 'number' ? list.unattributed : 0;
const rows = Array.isArray(list.runs) ? list.runs : [];
const details = await Promise.all(rows.map(r =>
api('/api/run/inspect?run_id=' + encodeURIComponent(r.run_id)).catch(() => null)));
/* One pass over the step grains rather than a scan per run — a memory
with a few thousand executions makes the nested version quadratic. */
const firstSeen = new Map(), planFromGrains = new Map();
for (const g of runStepGrains()) {
const f = g.fields, t = createdMs(f);
const cur = firstSeen.get(f.run_id);
if (cur == null || (t && t < cur)) firstSeen.set(f.run_id, t);
if (!planFromGrains.has(f.run_id)) {
const h = stepPlanHash(f);
if (h) planFromGrains.set(f.run_id, h);
}
}
rows.forEach((r, i) => {
const d = (details[i] && details[i].ok) ? details[i] : {};
const run = {
run_id: r.run_id,
ns: r.ns || null,
outcome: r.outcome || 'unknown',
plan_hash: d.plan_hash ? String(d.plan_hash).replace(/^sha256:/, '') : (planFromGrains.get(r.run_id) || null),
principal: d.principal || null,
checkpoints: d.checkpoints, journal_entries: d.journal_entries,
started_ms: firstSeen.get(r.run_id) || null,
asks: (d.pending_asks && typeof d.pending_asks === 'object')
? Object.values(d.pending_asks).map(a => (a && a.ask) ? a.ask : a) : [],
};
idx.runs.push(run);
idx.byId.set(run.run_id, run);
if (run.plan_hash) {
if (!idx.byPlan.has(run.plan_hash)) idx.byPlan.set(run.plan_hash, []);
idx.byPlan.get(run.plan_hash).push(run);
}
});
for (const list2 of idx.byPlan.values()) list2.sort((a, b) => (b.started_ms || 0) - (a.started_ms || 0));
return idx;
}
}
const OUTCOME_TONE = { completed: 'ok', open: 'warn', canceled: 'ghost', failed: 'danger' };
function outcomeTone(o) { return OUTCOME_TONE[o] || 'danger'; }
function statusTag(word, tone) {
const t = el('span', 'status-tag', word);
t.style.cssText = 'background:var(--' + (tone === 'ghost' ? 'raise' : tone + '-soft') + ');color:var(--'
+ (tone === 'ghost' ? 'dim' : tone) + ')';
return t;
}
/** The plan a run executed, by whatever name it has. */
function planLabel(hash) {
const g = hash && wfByHash()[hash];
return g ? wfLabel(g) : (hash ? shortHash(hash) : 'unknown plan');
}
async function renderRuns() {
renderCrumbHeader('runCrumb', [{ label: 'Runs' }],
'Every execution of a plan: journaled, checkpointed, pausable. A run waiting on a person shows its '
+ 'approval below — approving requires your own sign-in, because the approver’s identity <em>is</em> '
+ 'the audit record and a shared console token is not an identity.');
const nsHost = $('runNsHost'); nsHost.textContent = '';
// Unpicked shows as "*" (every run — this page's behavior before the
// picker existed), not the bound default like its sibling pages: a run's
// own bookkeeping lives in a fixed system namespace, not the one its
// plan happens to live in, so there is no single "home" namespace to
// default a run list to.
nsHost.appendChild(nsCombo('runNs', WF_NS || '*', ns => wfSetNamespace(ns)));
const box = $('runList');
const scopedNs = (WF_NS && WF_NS !== '*') ? WF_NS : null;
if (!RUNIDX && !scopedNs) box.innerHTML = '<div class="empty">loading…</div>';
/* Scoped, the SERVER filters (#165) — never a client-side cut of an
unscoped page, which is what hid a quiet tenant's open approvals behind
a busy tenant's newest fifty. */
const view = scopedNs ? await loadRunsScoped(scopedNs) : await loadRuns();
if (PAGE !== 'runs') return; // navigated away while loading
/* The nav badge counts every open run in the memory, whatever this page is
narrowed to — narrowing what you're LOOKING at must never narrow what
you're WARNED about. ONE path for both cases, so the badge cannot read a
different window depending on the picker: a plain list read at the
server's ceiling, no inspect fan-out (`outcome` rides the list itself).
Deriving it from the visible page instead would count over RUN_LIMIT
rows when unscoped and RUN_LIMIT_MAX when scoped — the wider view with
the narrower warning. */
const openCount = await runOpenCount();
const pill = $('runPill');
pill.hidden = openCount === 0; pill.textContent = openCount;
/* Exactly what the server matched — no client-side second filter, so the
count beside "Showing N of M" is the server's own and cannot disagree
with it. A run whose index entry predates the namespace stamp is not
known to be in any scope: the server counts it in `unattributed` and the
notes below say so, rather than this page inferring a namespace from the
run's PLAN, which is a different thing. */
const scoped = view.runs;
box.textContent = '';
if (view.error) { box.innerHTML = '<div class="empty">' + esc(view.error) + '</div>'; return; }
if (!scoped.length) {
box.innerHTML = scopedNs
? '<div class="empty">No runs in "' + esc(scopedNs) + '" — nothing has run in that namespace.'
+ (view.unattributed ? ' ' + view.unattributed + ' run' + (view.unattributed === 1 ? '' : 's')
+ ' predate the namespace record and appear under "All namespaces".' : '') + '</div>'
: '<div class="empty">No runs recorded in this memory yet. A run is one execution of a plan '
+ '— start one with <code>areev run start</code>, or let a trigger start it.</div>';
return;
}
// Say when the page is a window, not the whole set: "showing 100 of 214"
// is a limitation; a silent 100 is a wrong answer.
if (view.truncated || scopedNs) {
const note = el('div', 'tiny');
note.style.cssText = 'margin:0 0 10px;color:var(--dim)';
note.appendChild(document.createTextNode('Showing ' + scoped.length + ' of ' + view.total + ' run'
+ (view.total === 1 ? '' : 's') + (scopedNs ? ' in "' + scopedNs + '"' : '') + ', newest first.'
+ (view.unattributed ? ' ' + view.unattributed + ' older run' + (view.unattributed === 1 ? '' : 's')
+ ' predate the namespace record — see "All namespaces".' : '')));
if (view.truncated && RUN_LIMIT < RUN_LIMIT_MAX) {
const more = el('a', null, ' Show more');
more.href = '#'; more.style.marginLeft = '6px';
/* Reset, then let render() rebuild only the index this view reads —
never both. */
more.onclick = e => { e.preventDefault(); RUN_LIMIT = Math.min(RUN_LIMIT * 2, RUN_LIMIT_MAX); resetRunIndexes(); render(); };
note.appendChild(more);
} else if (view.truncated) {
note.appendChild(document.createTextNode(' Older runs: narrow by namespace, or use areev run list --offset.'));
}
box.appendChild(note);
}
const waiting = scoped.filter(r => r.asks.length);
const active = scoped.filter(r => !r.asks.length && r.outcome === 'open');
const done = scoped.filter(r => !r.asks.length && r.outcome !== 'open');
const groups = [
['Waiting on you', waiting, 'A step bound to a human-approval tool has paused the run.'],
['In flight', active, 'Started, not finished, nothing asked of you yet.'],
['Finished', done, null],
];
for (const [title, rows, gloss] of groups) {
if (!rows.length) continue;
const grp = el('div', 'rungroup');
const hd = el('div', 'hd');
hd.appendChild(el('h3', null, title + ' · ' + rows.length));
if (gloss) hd.appendChild(el('span', 'tiny', gloss));
grp.appendChild(hd);
const grid = el('div', 'rungrid');
for (const run of rows) grid.appendChild(runCard(run));
grp.appendChild(grid);
box.appendChild(grp);
}
}
function runCard(run) {
const card = el('div', 'card runcard');
const top = el('div', 'top');
const plan = el('div', 'plan');
plan.appendChild(document.createTextNode(planLabel(run.plan_hash)));
const rid = el('span', 'rid', run.run_id);
plan.appendChild(rid);
top.appendChild(plan);
top.appendChild(statusTag(run.outcome, outcomeTone(run.outcome)));
card.appendChild(top);
const meta = el('div', 'meta');
const bits = [];
/* Written before the run index recorded a session namespace (#165). Said
plainly, because the alternative is a filter silently deciding which
namespace it belongs to. */
if (!run.ns) bits.push('namespace not recorded');
if (run.principal) bits.push('started by ' + run.principal);
if (run.started_ms) bits.push(relTime(run.started_ms));
if (run.checkpoints != null) bits.push(run.checkpoints + ' checkpoints');
if (run.journal_entries != null) bits.push(run.journal_entries + ' journal entries');
for (const b of bits) meta.appendChild(el('span', null, b));
card.appendChild(meta);
/* The same overlay the canvas draws, one bar per step in plan order — so a
glance at the card and a glance at the graph agree about where the run
got to. */
const planG = run.plan_hash && wfByHash()[run.plan_hash];
const order = planG && Array.isArray((planG.fields || {}).nodes) ? planG.fields.nodes : [];
if (order.length) {
const states = runStepStates(run.run_id, run.outcome);
const strip = el('div', 'steps');
for (const id of order) {
const st = states.get(id);
const i = el('i');
i.title = id + (st ? ' — ' + STEP_WORD[st.state] : ' — not reached');
if (st) i.style.background = 'var(--' + STEP_TONE[st.state] + ')';
strip.appendChild(i);
}
card.appendChild(strip);
}
for (const ask of run.asks) card.appendChild(askBlock(run.run_id, ask));
const foot = el('div', 'foot');
foot.appendChild(el('span', 'grow'));
if (run.plan_hash) {
const b = el('button', 'btn ghost sm', 'Open plan ▸');
b.onclick = () => { WF_RUN = run.run_id; location.hash = '#workflows/' + run.plan_hash; };
foot.appendChild(b);
}
card.appendChild(foot);
return card;
}
/* Separation of duties is the whole point of this control, so when it is
unavailable it has to say WHICH credential is missing. `lock()`'s generic
read-only reason is not it: `run.respond` refuses a shared console token
even when that token can write everything else. */
const RESPOND_WHY = 'Approving needs your own sign-in (areev ui --auth). A shared console token '
+ 'and an anonymous caller are both refused here, because the approver’s identity is the audit record.';
function askBlock(runId, ask) {
const box = el('div', 'ask');
box.appendChild(el('b', null, 'Waiting on a person'));
const node = ask.node || '';
const tool = ask.tool_name || '';
box.appendChild(el('div', 'who', node && tool && node !== tool ? node + ' · ' + tool : (node || tool || 'an approval step')));
const acts = el('div', 'acts');
const btn = (cls, label, refuse) => {
const b = lock(el('button', cls, label));
b.title = RESPOND_WHY;
b.onclick = () => respondRun(runId, ask.tool_call_id, refuse);
return b;
};
acts.appendChild(btn('btn sm', 'Approve', false));
acts.appendChild(btn('btn danger', 'Refuse', true));
box.appendChild(acts);
return box;
}
async function respondRun(id, ask, refuse) {
const r = await api('/api/run/respond', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
run_id: id, tool_call_id: ask,
result: refuse ? { refused: true } : { approved: true },
is_error: refuse,
}),
});
if (!r.ok) { toast(r.error || 'response refused'); return; }
toast('Recorded as ' + (r.responder || 'you') + ' — resume the run to continue.');
resetRunIndexes(); render(); // render() rebuilds only the index this view reads
}
/* ══ analytics ════════════════════════════════════════════════════════
The Query page's "WHAT'S IN THIS MEMORY" on-ramp, grown into its own
page: every grain type it offers as a starter (not just the 4), every
namespace, a growth trend, and the recall legs this file has active.
Stat tiles and the namespace breakdown are always whole-file — STATS and
the effective config have no per-namespace form. Composition and growth
follow the namespace picker, the same convention Activity/Workflows use. */
const ANALYTICS_TYPES = [
['facts', 'fact', "Things it holds as true"],
['tools', 'tool', "Every tool call it made"],
['observations', 'observation', "Things it noticed, unconfirmed"],
['events', 'event', "Things that happened, in order"],
['goals', 'goal', "Objectives it's working toward"],
['states', 'state', "A snapshot of context, taken whole"],
['workflows', 'workflow', "Procedures it can follow, as a graph"],
['skills', 'skill', "Capabilities it has learned"],
['reasonings', 'reasoning', "Chains of thought behind a decision"],
['consensuses', 'consensus', "Agreements reached among agents"],
['consents', 'consent', "Permissions granted or withdrawn"],
['recommendations', 'recommendation', "Changes the loop proposed to itself"],
];
let AN_NS = null;
async function anSetNamespace(ns) {
AN_NS = (!ns || ns === boundNamespace()) ? null : ns;
await renderAnalytics();
}
/* A census row: mono key, optional gloss, a bar proportional to `max` (that
list's own largest count — so the grain census and the namespace
breakdown each fill their own width instead of one dwarfing the other),
and a right-aligned count. `count == null` means "couldn't count it on
this build" (mirrors the vocab cards' own honesty about COUNT failing) —
shown as "—" and treated as 0 for the bar, never a lie. */
function censusRow(host, key, gloss, count, max, onClick) {
const r = el('button', 'crow');
r.appendChild(el('span', 'k' + (gloss == null ? ' wide' : ''), key));
if (gloss != null) r.appendChild(el('span', 'g', gloss));
const track = el('div', 'track');
const bar = el('div', 'bar' + (count ? '' : ' zero'));
bar.style.width = Math.max(max ? ((count || 0) / max) * 100 : 0, 3) + '%';
track.appendChild(bar); r.appendChild(track);
r.appendChild(el('span', 'n' + (count ? '' : ' zero'), count == null ? '—' : String(count)));
if (onClick) r.onclick = onClick;
host.appendChild(r);
}
/* nsCombo fires its onChange once per commit path (option click, Enter,
blur-on-change) — on a fast synchronous page two of those firing for one
pick is invisible, but this page's render does several sequential
network round trips, wide enough for a second, newer call to land while
an older one is still mid-flight. AN_GEN guards against that: every call
takes a ticket, does ALL its awaiting up front, and only writes to the
DOM if its ticket is still the latest — an overtaken call discards its
(now-stale) results instead of appending duplicate rows on top of the
newer render's. */
let AN_GEN = 0;
async function renderAnalytics() {
const gen = ++AN_GEN;
const nsList = NAMESPACES || [];
const scope = AN_NS || boundNamespace();
const rows = await browseForNamespace(scope);
// Composition: one COUNT per grain type, scoped to the picked namespace.
// CAL has no "every namespace at once" wildcard on a RECALL WHERE clause
// (recall is exact-namespace or a registered "org.*" prefix, never a bare
// "*" — that lift-the-filter form is `/api/browse?ns=*`'s own owner-gated
// server route, not CAL) — so "All namespaces" sums one COUNT per real
// namespace instead of asking CAL for a wildcard it will refuse.
const esc = s => String(s).replace(/"/g, '\\"');
const scopeNs = AN_NS === '*' ? nsList.map(n => n.namespace) : [scope];
async function scopedCount(plural) {
const perNs = await Promise.all(scopeNs.map(ns =>
cal('RECALL ' + plural + ' WHERE namespace = "' + esc(ns) + '" COUNT')));
let total = 0, anyOk = false;
for (const r of perNs) {
if (r && r.ok && r.result && typeof r.result.count === 'number') { total += r.result.count; anyOk = true; }
}
return anyOk ? total : null;
}
const typeCounts = await Promise.all(ANALYTICS_TYPES.map(([plural]) => scopedCount(plural)));
if (gen !== AN_GEN) return; // superseded — a newer namespace pick (or re-render) already won
renderCrumbHeader('anCrumb', [{ label: 'Analytics' }],
"The shape of what's stored here — composition, growth, and what it can be queried by.");
const nsHost = $('anNsHost'); nsHost.textContent = '';
nsHost.appendChild(nsCombo('anNs', scope, anSetNamespace));
const tiles = $('anTiles'); tiles.textContent = '';
const tile = (label, value, sub, color) => {
const t = el('div', 'card stile');
t.appendChild(el('span', 'lbl', label));
const n = el('span', 'n', String(value)); if (color) n.style.color = color; t.appendChild(n);
t.appendChild(el('span', 'sub', sub));
tiles.appendChild(t);
};
const topNs = nsList.length ? nsList.slice().sort((a, b) => b.count - a.count)[0] : null;
tile('Total memories', STATS.grains != null ? STATS.grains : '?',
(STATS.current != null ? STATS.current : '?') + ' live now');
tile('Namespaces', nsList.length, topNs ? 'most of it is in ' + topNs.namespace : 'nothing scoped yet');
tile('Operations logged', STATS.ops != null ? STATS.ops : '?', 'adds, supersessions, forgets');
// Whole-file, like its three siblings above — `rows` (below) is the
// picker-scoped source the Growth *chart* uses; mixing scopes within one
// tile row would make the tiles look inconsistent with each other.
const weekAgo = Date.now() - 7 * 86400000;
const recent = BROWSE.filter(g => g.op === 'add' && !isInternal(g) && hlcMs(g.hlc) >= weekAgo).length;
tile('Last 7 days', '+' + recent, 'new memories written', 'var(--ok)');
const census = $('anCensus'); census.textContent = '';
const withCounts = ANALYTICS_TYPES.map(([plural, name, gloss], i) => [plural, name, gloss, typeCounts[i]])
.sort((a, b) => (b[3] || 0) - (a[3] || 0));
const maxCount = Math.max(1, ...withCounts.map(w => w[3] || 0));
for (const [plural, name, gloss, n] of withCounts) {
censusRow(census, name, gloss, n, maxCount, () => {
const s = 'RECALL ' + plural + (scopeNs.length === 1 ? ' WHERE namespace = "' + esc(scopeNs[0]) + '"' : '') + ' LIMIT 20';
go('query'); setQueryText(s); runQuery(s);
});
}
// Namespaces: always whole-file (this is the one section that shows every
// namespace at once) — clicking a row focuses the picker, and so every
// other section, on it.
const nsBox = $('anNsBreakdown'); nsBox.textContent = '';
if (!nsList.length) nsBox.appendChild(el('div', 'empty', 'No namespace list on this build.'));
const maxNs = Math.max(1, ...nsList.map(n => n.count || 0));
for (const n of nsList.slice().sort((a, b) => b.count - a.count)) {
censusRow(nsBox, n.namespace, null, n.count, maxNs, () => anSetNamespace(n.namespace));
}
// Growth: the last 14 days of "add" ops in the picked scope. `rows` is
// whatever window browseForNamespace loaded (2,000 ops, same cap the
// Graph/Activity views already accept) — captioned honestly rather than
// implying a full-history count.
const gHost = $('anGrowth'); gHost.textContent = '';
const days = [];
for (let i = 13; i >= 0; i--) days.push(dayKey(Date.now() - i * 86400000));
const perDay = Object.fromEntries(days.map(d => [d, 0]));
for (const g of rows) {
if (g.op !== 'add' || isInternal(g)) continue;
const k = dayKey(hlcMs(g.hlc));
if (k in perDay) perDay[k]++;
}
const maxDay = Math.max(1, ...days.map(d => perDay[d]));
const chart = el('div', 'gchart');
days.forEach((d, i) => {
const b = el('div', 'gbar' + (i === days.length - 1 ? ' today' : ''));
b.style.height = Math.max((perDay[d] / maxDay) * 100, perDay[d] ? 4 : 2) + 'px';
b.title = d + ': ' + perDay[d];
chart.appendChild(b);
});
gHost.appendChild(chart);
const axis = el('div'); axis.style.cssText = 'display:flex;justify-content:space-between;margin-top:8px';
axis.appendChild(el('span', 'tiny', '14 days ago'));
const todayLbl = el('span', 'tiny', 'today'); todayLbl.style.cssText = 'color:var(--accent);font-weight:600';
axis.appendChild(todayLbl);
gHost.appendChild(axis);
$('anGrowthCaption').textContent = 'Memories written per day, '
+ (scope === '*' ? 'across every namespace' : 'in ' + scope)
+ ' — from the ' + rows.length + ' most recent operations loaded';
// Recall legs: whole-file, from the effective config — not affected by
// the namespace picker (recall configuration is per-file, not per-ns).
const legs = $('anLegs'); legs.textContent = '';
const r = CONFIG && CONFIG.recall && CONFIG.recall.legs;
const leg = (dotColor, title, desc) => {
const c = el('div', 'card leg');
const hd = el('div', 'hd');
const dot = el('span', 'dot'); dot.style.background = dotColor; hd.appendChild(dot);
hd.appendChild(el('b', null, title));
c.appendChild(hd);
c.appendChild(el('span', 'd', desc));
legs.appendChild(c);
};
leg('var(--ok)', 'Structural', 'Exact-match recall by subject, relation, namespace. Always on.');
leg(r && r.bm25 ? 'var(--ok)' : 'var(--ghost)', 'Full-text (BM25)',
r && r.bm25 ? 'Plain-words search over indexed content. On for this file.' : 'Off — this file has no text index built.');
leg(r && r.vector ? 'var(--ok)' : 'var(--ghost)', 'Vector',
r && r.vector ? 'Semantic similarity search. On for this file.' : 'Dormant — no embedding backend installed.');
}
/* ══ render ═══════════════════════════════════════════════════════════ */
function render() {
syncHash();
for (const p of ['memory', 'analytics', 'activity', 'runs', 'tools', 'workflows', 'suggestions', 'settings', 'query']) $('page-' + p).hidden = PAGE !== p;
$('nav').querySelectorAll('.nav-item').forEach(b => b.classList.toggle('on', b.dataset.page === PAGE));
const trgN = triggerGrains().length;
$('wfTrgPill').hidden = trgN === 0; $('wfTrgPill').textContent = String(trgN);
$('listView').hidden = MVIEW !== 'list';
$('graphView').hidden = MVIEW !== 'graph';
$('mview').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.v === MVIEW));
$('sugTabs').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.s === SUGTAB));
$('toolTabs').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.t === TOOLTAB));
$('conTabs').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.c === CONTAB));
renderRail(); renderHeader(); renderExamples(); renderBanner(); renderFilterBar();
if (PAGE === 'memory') {
const nsHost = $('memNsHost'); nsHost.textContent = '';
nsHost.appendChild(nsCombo('memNs', MEM_NS || boundNamespace(), memSetNamespace));
renderAnswer(); renderMemList(); if (MVIEW === 'graph') Graph.rebuild();
}
if (PAGE === 'analytics') renderAnalytics();
if (PAGE === 'activity') renderActivity();
if (PAGE === 'runs') renderRuns();
if (PAGE === 'tools') renderTools();
if (PAGE === 'workflows') renderWorkflows();
if (PAGE === 'suggestions') { renderSuggestions(); lock($('runLoop')); }
if (PAGE === 'settings') renderSettingsPage();
if (PAGE === 'query') {
renderCrumbHeader('queryCrumb', [{ label: 'Query' }], null);
queryNotice(); syncEditor(); renderQueryResult(); renderOnramp();
const sv = $('qsave');
sv.disabled = !stmtSupported('DEFINE') || !canWrite();
sv.title = !stmtSupported('DEFINE')
? 'This build has no saved-query registry (DEFINE is not a supported statement)'
: (!canWrite() ? READONLY_WHY : 'Save this query into the memory file');
}
}
/* The rail no longer lists entities (moved out to declutter — the graph
page's inspector and the ask bar's examples reach the same filter), but
ACTIVE_ENTS itself stays: renderExamples() still uses it for suggested
questions. */
function renderRail() {
ACTIVE_ENTS = buildEntities(memGrains()).filter(e => e.count > 0).slice(0, 40);
}
function renderHeader() {
const n = memGrains().length;
const db = ($('dblabel').textContent || '').trim();
// Namespace-scoped, say so — an empty list with no explanation is exactly
// what looked like a bug before this picker existed.
const scoped = MEM_NS === '*' ? ' across every namespace' : (MEM_NS ? ' in "' + esc(MEM_NS) + '"' : '');
const desc = n
? esc(n + (n === 1 ? ' memory' : ' memories')) + scoped + ', kept in <b style="color:var(--text);font-weight:500">'
+ esc(db) + '</b> — nothing here is ever overwritten, only added to.'
: MEM_NS ? 'Nothing stored' + scoped + '.'
: 'Nothing stored yet. Connect an agent and what it learns will show up here.';
const crumbs = ENTITY
? [{ label: 'Memory', onClick: () => { ENTITY = null; render(); } }, { label: ENTITY }]
: [{ label: 'Memory' }];
renderCrumbHeader('memCrumb', crumbs, desc);
}
/* Only suggest questions the console can actually answer: a name it knows,
or the time-based one that reads the op-log. */
function renderExamples() {
const host = $('examples'); host.textContent = '';
if (!memGrains().length) return;
const typed = ($('ask').value || '').trim();
if (typed) {
host.appendChild(el('span', 'tiny', 'Filtering as you type — press Enter to ask “' +
(typed.length > 44 ? typed.slice(0, 44) + '…' : typed) + '”'));
return;
}
const qs = ACTIVE_ENTS.slice(0, 2).map(e => 'what do you know about ' + e.name + '?');
qs.push('what changed today?');
host.appendChild(el('span', 'tiny', 'Try'));
for (const q of qs.slice(0, 3)) {
const c = el('span', 'chip', q);
c.onclick = () => { $('ask').value = q; runAsk(q); };
host.appendChild(c);
}
}
/* When a filter is on, say so and give a way out — otherwise arriving from
the graph's "See all" looks like nothing happened. */
function renderFilterBar() {
const host = $('filterBar');
host.textContent = '';
host.hidden = !ENTITY;
if (!ENTITY) return;
const chip = el('div');
chip.style.cssText = 'display:inline-flex;align-items:center;gap:10px;padding:7px 8px 7px 14px;'
+ 'border-radius:18px;background:var(--accent-soft);border:1px solid var(--accent-line)';
const t = el('span', null, 'Showing only ' + ENTITY);
t.style.cssText = 'font-size:13.5px;font-weight:600;color:var(--accent)';
chip.appendChild(t);
const x = el('button', null, 'Show everything ✕');
x.style.cssText = 'border:0;background:var(--surface);color:var(--text);font-family:inherit;'
+ 'font-size:12.5px;font-weight:500;padding:4px 11px;border-radius:14px';
x.onclick = () => { ENTITY = null; render(); };
chip.appendChild(x);
host.appendChild(chip);
}
function renderBanner() {
const n = (RECS.pending || []).length;
$('sugBanner').hidden = !n || PAGE !== 'memory';
if (n) {
const kinds = [...new Set((RECS.pending || []).map(r => analyzerWord(r.analyzer)))].slice(0, 3);
$('sugBannerText').innerHTML = '<b>' + n + (n === 1 ? ' suggestion</b>' : ' suggestions</b>')
+ ' to make this memory more reliable' + (kinds.length ? ' — ' + esc(kinds.join(', ')) : '') + '.';
}
}
/* ── memory list ── */
function visibleGrains() {
const needle = ($('ask').value || '').toLowerCase().trim();
let rows = memGrains();
if (ENTITY) rows = rows.filter(g => {
const f = g.fields || {};
return subjectOf(g) === ENTITY || (typeof f.object === 'string' && f.object === ENTITY);
});
if (needle && !ANSWER) rows = rows.filter(g => sentence(g).toLowerCase().includes(needle));
return rows;
}
function renderMemList() {
const host = $('memList'); host.textContent = '';
const rows = visibleGrains();
const forgotten = memRows().filter(g => isGone(g) && !isInternal(g))
.filter(g => !ENTITY || ((g.fields || {}).subject === ENTITY));
if (!rows.length && !forgotten.length) {
const e = el('div', 'empty');
e.textContent = memGrains().length
? 'Nothing matches. Clear the box or pick a different name.'
: MEM_NS ? 'No memories in this namespace — try "All namespaces" or pick another.'
: 'No memories yet — open Connect to attach an agent.';
host.appendChild(e); return;
}
const groups = new Map();
for (const g of rows) {
const k = subjectOf(g) || '—';
if (!groups.has(k)) groups.set(k, []);
groups.get(k).push(g);
}
const order = [...groups.keys()].sort((a, b) => groups.get(b).length - groups.get(a).length || a.localeCompare(b));
for (const k of order) {
const list = groups.get(k).sort((a, b) => (b.op_seq || 0) - (a.op_seq || 0));
const head = el('div', 'grp-head');
head.appendChild(el('h2', null, k === '—' ? 'Everything else' : titleize(k)));
head.appendChild(el('span', 'meta', list.length + (list.length === 1 ? ' memory' : ' memories')));
host.appendChild(head);
for (const g of list) host.appendChild(memRow(g));
}
if (forgotten.length) {
const head = el('div', 'grp-head');
head.appendChild(el('h2', null, 'Deleted'));
head.appendChild(el('span', 'meta', forgotten.length + ' removed for good'));
host.appendChild(head);
for (const g of forgotten.slice(0, 20)) host.appendChild(memRow(g));
}
}
function memRow(g) {
const gone = isGone(g);
const row = el('div', 'mrow' + (gone ? ' gone' : '') + (SEL === g.hash ? ' sel' : ''));
const body = el('div', 'body');
const say = el('div', 'say', gone ? (g.fields ? predicate(g) : 'A memory') : predicate(g));
body.appendChild(say);
body.appendChild(el('div', 'prov', gone
? 'Deleted at your request — the content is gone for good'
: provenance(g)));
const dev = el('div', 'mono dev-only');
dev.textContent = (g.type || 'grain') + ' · ' + (g.hash || '').slice(0, 12)
+ (g.superseded_by ? ' · superseded ' + g.superseded_by.slice(0, 12) : '');
body.appendChild(dev);
row.appendChild(body);
row.appendChild(el('div', 'when', relTime(hlcMs(g.hlc))));
row.onclick = () => openPanel(g.hash);
return row;
}
/* ── ask → answer ── */
function relationFromQuestion(q) {
const low = ' ' + q.toLowerCase().replace(/[^a-z0-9_ ]/g, ' ') + ' ';
const rels = [...new Set(memGrains().map(g => (g.fields || {}).relation).filter(Boolean))];
let best = null;
for (const r of rels) {
for (const w of r.split('_')) {
if (w.length < 4) continue;
const stem = w.replace(/s$/, '');
if (low.includes(' ' + stem)) { best = r; break; }
}
if (best) break;
}
return best;
}
function entityFromQuestion(q) {
const low = q.toLowerCase();
let best = null;
for (const e of buildEntities(memGrains())) {
if (low.includes(e.name.toLowerCase()) && (!best || e.name.length > best.length)) best = e.name;
}
return best;
}
/* Free-text recall is a bag of words, so sending the whole question makes
"what", "does" and "today" compete with the words that matter. */
const STOPWORDS = new Set(['what','whats','who','whos','when','where','why','how','is','are','was',
'were','do','does','did','has','have','the','a','an','of','for','to','in','on','about','me','my',
'you','your','i','it','its','tell','show','know','knows','list','find','any','anything',
'everything','please','can','could','would','there','that','this','and','or']);
const contentWords = q => q.toLowerCase().replace(/[^a-z0-9\s_-]/g, ' ').split(/\s+/)
.filter(w => w.length > 1 && !STOPWORDS.has(w));
/* Questions about time cannot be answered by recall at all — they are a
question about the op-log. Answer them from it instead of pretending. */
const TEMPORAL = /\b(today|yesterday|this week|recently|lately|just now|changed|change[sd]?|new|newest|latest|happened|since)\b/i;
function answerFromActivity(q) {
const since = Date.now() - 24 * 3600 * 1000;
// LOG spans every namespace (it's the whole file's op-log) — scoped to a
// specific one, an op whose grain isn't in that namespace's loaded rows
// isn't this namespace's business, so it's dropped rather than mislabeled
// "deleted" for having no match. Left on the bound default or "All
// namespaces", nothing is filtered — today's behavior, unchanged.
const scope = MEM_NS && MEM_NS !== '*' ? MEM_NS : null;
const ops = LOG.filter(o => hlcMs(o.hlc) >= since)
.filter(o => {
const g = memByHash()[o.hash];
if (g && isInternal(g)) return false;
return scope ? !!g : true;
})
.sort((a, b) => (b.op_seq || 0) - (a.op_seq || 0));
const n = k => ops.filter(o => o.op === k).length;
const text = ops.length
? 'In the last 24 hours your agent learned ' + n('add') + ', changed ' + n('supersede')
+ ' and deleted ' + n('forget') + '.'
: 'Nothing has changed in the last 24 hours' + (scope ? ' in "' + esc(scope) + '"' : '') + '.';
/* A supersede logs two ops for the same grain — show it once. And a
tombstoned grain has no fields left to make a sentence from, so say
what happened to it rather than "no readable text". */
const seen = new Set(), grains = [];
for (const o of ops) {
if (grains.length >= 6 || seen.has(o.hash)) continue;
seen.add(o.hash);
const g = memByHash()[o.hash];
const say = o.op === 'forget' || !g || isGone(g) ? 'A memory was deleted'
: (o.op === 'supersede' ? 'Updated: ' : '') + sentence(g);
grains.push({ hash: o.hash, hlc: o.hlc, _say: say, fields: (g || {}).fields, type: (g || {}).type });
}
return { q, query: null, kind: 'activity', subject: null, relation: null, grains, text, error: null };
}
async function runAsk(q) {
q = (q || '').trim();
if (!q) { ANSWER = null; render(); return; }
const subject = entityFromQuestion(q);
const relation = relationFromQuestion(q);
if (!subject && TEMPORAL.test(q)) {
ANSWER = answerFromActivity(q);
ENTITY = null;
if (PAGE !== 'memory') go('memory'); else render();
return;
}
const words = contentWords(q);
// The Memory page's namespace scope, as a CAL fragment. "*" has no CAL
// equivalent (RECALL is exact-namespace or a registered prefix, never a
// bare wildcard — see the Analytics page's own note on this) — left
// there, the query runs unscoped, same as the bound-default case.
const nsw = (MEM_NS && MEM_NS !== '*') ? 'namespace = "' + MEM_NS.replace(/"/g, '') + '"' : '';
let query;
if (subject) {
query = 'RECALL facts WHERE subject = "' + subject.replace(/"/g, '') + '"'
+ (relation ? ' AND relation = "' + relation + '"' : '')
+ (nsw ? ' AND ' + nsw : '') + ' LIMIT 50';
} else {
// ABOUT precedes WHERE in the grammar — the clause is inserted after
// the free-text query, not appended onto it.
query = 'RECALL facts ABOUT "' + (words.join(' ') || q).replace(/"/g, '') + '"'
+ (nsw ? ' WHERE ' + nsw : '') + ' LIMIT 20';
}
let res = await cal(query);
if ((!res.ok || !((res.result || {}).grains || []).length) && !subject) {
const word = words[words.length - 1] || q;
// WHERE precedes LIKE in the grammar, same reason as above.
query = 'RECALL facts' + (nsw ? ' WHERE ' + nsw : '') + ' LIKE "' + word.replace(/"/g, '') + '" LIMIT 20';
res = await cal(query);
}
const grains = (res.ok && res.result && res.result.type === 'grains') ? (res.result.grains || []) : [];
ANSWER = { q, query, subject, relation, grains, error: res.ok ? null : (res.error || 'query failed'),
code: res.code, elapsed: res.elapsed_ms };
ENTITY = null;
if (PAGE !== 'memory') go('memory'); else render();
}
/* A CAL result grain and a browse row differ in shape — normalise. */
const rgType = g => g.grain_type || g.type;
const rgFields = g => g.fields || {};
function answerText(a) {
if (a.error) return null;
if (a.kind === 'activity') return a.text;
if (!a.grains.length) return 'Nothing matched that. Ask about one of the names on the left, '
+ 'or try “what changed today?”.';
const subj = a.subject ? cap(a.subject) : null;
if (a.relation) {
/* The same value can be a head in more than one namespace — say it once. */
const objs = [...new Set(a.grains.filter(g => rgFields(g).relation === a.relation)
.map(g => rgFields(g).object).filter(o => typeof o === 'string'))];
if (objs.length) {
const phrase = (REL_PHRASE[a.relation] || cap(a.relation.replace(/_/g, ' ')) + ' {o}');
const said = phrase.replace('{o}', objs.slice(0, 3).join(', '));
return (subj ? subj + ' ' + lowerFirst(said) : said) + '.';
}
}
if (subj) return 'Here is everything your agent knows about ' + subj + ' — '
+ a.grains.length + (a.grains.length === 1 ? ' memory' : ' memories') + '.';
return 'Found ' + a.grains.length + (a.grains.length === 1 ? ' memory' : ' memories') + ' that match.';
}
function renderAnswer() {
const host = $('answer');
host.hidden = !ANSWER; host.textContent = '';
if (!ANSWER) return;
const a = ANSWER;
const top = el('div'); top.style.cssText = 'display:flex;flex-direction:column;gap:10px;padding-bottom:24px';
top.appendChild(el('span', 'ans-label', a.error ? 'COULD NOT ANSWER' : 'ANSWER'));
const txt = el('span', 'ans-text', a.error ? a.error : answerText(a));
if (a.error) txt.style.color = 'var(--danger)';
top.appendChild(txt);
if (a.error && a.code) top.appendChild(el('span', 'meta', 'error code ' + a.code));
host.appendChild(top);
if (a.grains.length) {
const box = el('div'); box.style.cssText = 'display:flex;flex-direction:column;border-top:1px solid var(--hair)';
const lab = el('span', 'meta', 'Based on ' + a.grains.length + (a.grains.length === 1 ? ' memory' : ' memories'));
lab.style.cssText = 'padding:16px 0 4px'; box.appendChild(lab);
for (const g of a.grains.slice(0, 6)) {
const r = el('div', 'srow');
const dot = el('span'); dot.style.cssText = 'width:6px;height:6px;border-radius:3px;flex-shrink:0;background:var(--ok)';
r.appendChild(dot);
r.appendChild(el('span', 't', g._say || sentence({ type: rgType(g), fields: rgFields(g) })));
r.appendChild(el('span', 'w', relTime(hlcMs(g.hlc)) || ''));
if (g.hash) r.onclick = () => openPanel(g.hash);
box.appendChild(r);
}
host.appendChild(box);
}
if (a.kind === 'activity') {
const go2 = el('div', 'disclose');
go2.appendChild(el('span', 'grow', 'Every change, in order'));
const l = el('span', null, 'Open Activity →');
l.style.cssText = 'font-size:14px;font-weight:600;color:var(--accent)';
go2.appendChild(l);
go2.onclick = () => { ANSWER = null; go('activity'); };
host.appendChild(go2);
return;
}
const foot = el('div', 'disclose');
foot.innerHTML = '<svg class="caret" width="15" height="15" viewBox="0 0 24 24" fill="none">'
+ '<path d="M9 5.5l7 6.5-7 6.5" stroke="var(--dim)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'
+ '<span class="grow">How this answer was found</span>';
const openq = el('span'); openq.style.cssText = 'font-size:14px;font-weight:600;color:var(--accent)';
openq.textContent = 'Open in Query';
openq.onclick = e => { e.stopPropagation(); $('qtext').value = a.query; go('query'); runQuery(); };
if (a.query) foot.appendChild(openq);
const copy = el('span'); copy.style.cssText = 'font-size:14px;font-weight:600;color:var(--accent)';
copy.textContent = 'Copy'; copy.onclick = e => { e.stopPropagation(); copyText(answerText(a) || a.error, 'Answer'); };
foot.appendChild(copy);
const detail = el('div');
detail.style.cssText = 'display:none;flex-direction:column;gap:8px;padding:0 0 20px';
const pre = el('pre', 'code', a.query); detail.appendChild(pre);
detail.appendChild(el('span', 'tiny', a.elapsed != null ? 'ran in ' + a.elapsed + ' ms' : ''));
foot.onclick = () => {
const open = detail.style.display === 'flex';
detail.style.display = open ? 'none' : 'flex';
foot.classList.toggle('open', !open);
};
host.appendChild(foot); host.appendChild(detail);
}
/* ══ detail panel ═════════════════════════════════════════════════════ */
/* Closing always drops back out of full screen — each grain starts as the
inline card, and whether *this* one is worth expanding is a fresh call
the next open makes for itself. */
function closePanel() {
const wrap = $('panelWrap');
wrap.hidden = true; wrap.classList.remove('full');
SEL = null; renderMemList();
}
/* The panel is now an inline card, not a shade blocking the rest of the
app — nothing stops the sidebar's page navigation while one is open. It
isn't scoped to the page that opened it (it lives outside every `.page`
section, so a re-render doesn't wipe it), so without this a "Tools" click
would leave last week's fact card sitting under the Tools page — or worse,
stuck full screen over it. Every real page change closes it. */
function closePanelIfOpen() { if (!$('panelWrap').hidden) closePanel(); }
function togglePanelFull(btn) {
const full = $('panelWrap').classList.toggle('full');
btn.innerHTML = full ? COLLAPSE_ICON : EXPAND_ICON;
btn.title = full ? 'Exit full screen' : 'View full screen';
}
async function openPanel(hash) {
if (!hash) return;
hash = hash.replace(/^sha256:/, '');
SEL = hash; renderMemList();
const wrap = $('panelWrap'); wrap.hidden = false;
const p = $('panel'); p.textContent = '';
p.appendChild(el('span', 'tiny', 'loading…'));
wrap.scrollIntoView({ block: 'nearest' });
const known = BYHASH[hash];
const g = await api('/api/grain?hash=' + encodeURIComponent(hash));
p.textContent = '';
const head = el('div'); head.style.cssText = 'display:flex;align-items:flex-start;gap:12px';
const ht = el('div'); ht.style.cssText = 'display:flex;flex-direction:column;gap:9px;flex:1;min-width:0';
ht.appendChild(el('span', 'sec-label', 'MEMORY'));
const gone = g.ok === false;
const f = (!gone && g.fields) || {};
/* Full text, never clamped — a list row's job is to fit a line; this
card's job is to be the place you can read the whole thing. A tool's
body goes in its own CONTENT block below instead of into this title,
since cramming a JSON result into a sentence is not "reading it". */
const fullText = gone
? (known ? sentence(known, true) : 'This memory was deleted')
: g.type === 'tool' ? (f.tool_name || 'A tool') + (f.is_error ? ' failed' : ' ran')
: sentence({ type: g.type, fields: f }, true);
const title = el('span', null, fullText);
title.style.cssText = 'font:600 22px/31px var(--sans);color:var(--ink);letter-spacing:-.02em;'
+ 'white-space:pre-wrap;overflow-wrap:anywhere';
const titleWrap = el('div');
// Long content scrolls in its own box rather than stretching the card (and
// the page under it) to match — "full content" does not mean "no limits".
if (fullText.length > 400) titleWrap.style.cssText = 'max-height:320px;overflow-y:auto';
titleWrap.appendChild(title);
ht.appendChild(titleWrap);
head.appendChild(ht);
const fullBtn = el('button', 'btn ghost sm');
fullBtn.style.cssText = 'width:34px;padding:0;flex-shrink:0';
const isFull = wrap.classList.contains('full');
fullBtn.innerHTML = isFull ? COLLAPSE_ICON : EXPAND_ICON;
fullBtn.title = isFull ? 'Exit full screen' : 'View full screen';
fullBtn.onclick = () => togglePanelFull(fullBtn);
head.appendChild(fullBtn);
const x = el('button', 'btn ghost sm', '✕');
x.style.cssText = 'width:34px;padding:0;flex-shrink:0'; x.onclick = closePanel;
head.appendChild(x);
p.appendChild(head);
if (gone) {
const w = el('div', 'pgroup');
w.appendChild(el('span', 'sub', 'The content is gone for good — only the record that it was removed remains. '
+ 'That is what "forget" means here: a tombstone, not a hidden row.'));
const h = el('div', 'mono'); h.textContent = hash; h.style.wordBreak = 'break-all';
w.appendChild(h); p.appendChild(w); return;
}
const when = createdMs(f) || hlcMs(known && known.hlc);
const prov = el('div', 'pgroup');
const kv = (k, v, title2) => { const r = el('div'); r.style.cssText = 'display:flex;align-items:baseline;gap:12px';
const kk = el('span', null, k); kk.style.cssText = 'width:96px;flex-shrink:0;font-size:13.5px;color:var(--dim)';
const vv = el('span', null, v); vv.style.cssText = 'flex:1;font-size:14.5px;color:var(--ink)';
if (title2) vv.title = title2;
r.appendChild(kk); r.appendChild(vv); return r; };
prov.appendChild(kv('Learned', relTime(when) + (when ? ' · ' + new Date(when).toLocaleDateString() : ''), isoTitle(when)));
prov.appendChild(kv('Kind', cap(g.type || 'fact') + (g.type === 'observation' ? ' — something it saw, not something it was told' : '')));
if (f.namespace) prov.appendChild(kv('Namespace', f.namespace));
if (f.session_id) prov.appendChild(kv('Session', f.session_id));
const used = TELEMETRY && (TELEMETRY.access || []).find(a => a.hash === hash);
if (used) prov.appendChild(kv('Used', used.recall_count + ' times · last ' + relTime(used.last_ms)));
p.appendChild(prov);
/* A tool's body is usually code or JSON, not prose — codeBlock() picks
between highlighted JSON and plain monospace text rather than forcing
either, and each box scrolls on its own so a large result doesn't
dominate the card. Shown unconditionally: this is the memory's actual
content, not debugging detail, so it isn't dev-gated like the raw
grain JSON further down. */
if (g.type === 'tool') {
const raw = f.tool_content != null ? f.tool_content : f.content;
if (raw != null) {
const box = el('div', 'pgroup');
box.appendChild(el('span', 'sec-label', f.kind === 'definition' ? 'DESCRIPTION' : 'RESULT'));
const block = codeBlock(raw);
block.style.maxHeight = '420px'; block.style.overflowY = 'auto';
box.appendChild(block);
p.appendChild(box);
}
if (f.input != null) {
const box = el('div', 'pgroup');
box.appendChild(el('span', 'sec-label', 'ARGUMENTS'));
const block = codeBlock(f.input);
block.style.maxHeight = '300px'; block.style.overflowY = 'auto';
box.appendChild(block);
p.appendChild(box);
}
}
/* version history, in plain language */
if (g.type === 'fact' && f.subject && f.relation) {
const hist = await cal('HISTORY WHERE subject = "' + String(f.subject).replace(/"/g, '')
+ '" AND relation = "' + String(f.relation).replace(/"/g, '') + '"');
const versions = (hist.ok && hist.result && hist.result.versions) || [];
if (versions.length > 1) {
const box = el('div', 'pgroup');
box.appendChild(el('span', 'sec-label', 'HOW THIS CHANGED'));
versions.forEach((v, i) => {
const step = el('div', 'step');
const rail = el('div', 'rail');
const bul = el('div', 'bul' + (i === 0 ? '' : ' past')); rail.appendChild(bul);
if (i < versions.length - 1) rail.appendChild(el('div', 'ln'));
step.appendChild(rail);
const bd = el('div'); bd.style.cssText = 'display:flex;flex-direction:column;gap:3px;flex:1;padding-bottom:18px';
const val = el('span', null, typeof v.fields === 'object' && v.fields ? (v.fields.object != null ? String(v.fields.object) : preview(v.fields)) : '');
val.style.cssText = 'font-size:15.5px;font-weight:500;color:' + (i === 0 ? 'var(--ink)' : 'var(--muted)');
bd.appendChild(val);
bd.appendChild(el('span', 'meta', i === 0
? 'Added ' + relTime(hlcMs(v.hlc)) + ' · this is what your agent uses now'
: 'Added ' + relTime(hlcMs(v.hlc)) + ' · replaced, but kept so you can see the change'));
step.appendChild(bd);
box.appendChild(step);
});
p.appendChild(box);
}
}
/* actions */
const acts = el('div', 'pgroup');
const row = el('div'); row.style.cssText = 'display:flex;align-items:center;gap:10px';
const correct = el('button', 'btn', 'Correct this memory'); correct.style.flex = '1';
const askAbout = el('button', 'btn ghost', 'Ask about it');
row.appendChild(lock(correct)); row.appendChild(askAbout);
acts.appendChild(row);
const form = el('div'); form.style.cssText = 'display:none;flex-direction:column;gap:9px';
const inp = document.createElement('input'); inp.type = 'text';
inp.value = typeof f.object === 'string' ? f.object : '';
inp.placeholder = 'What should it say instead?';
const why = document.createElement('input'); why.type = 'text'; why.placeholder = 'Why are you changing it?';
const save = el('button', 'btn sm', 'Save the correction');
form.appendChild(el('span', 'meta', 'The old version is kept — corrections are added on top, never written over.'));
form.appendChild(inp); form.appendChild(why); form.appendChild(save);
acts.appendChild(form);
correct.onclick = () => { form.style.display = form.style.display === 'flex' ? 'none' : 'flex'; inp.focus(); };
askAbout.onclick = () => { closePanel(); $('ask').value = 'what do you know about ' + (f.subject || '') + '?'; runAsk($('ask').value); };
save.onclick = async () => {
if (!inp.value.trim()) { toast('Type the new value first'); return; }
save.disabled = true;
let q = 'SUPERSEDE sha256:' + hash + ' SET object = "' + inp.value.replace(/"/g, '\\"') + '"';
if (why.value.trim()) q += ' BECAUSE "' + why.value.replace(/"/g, '\\"') + '"';
const r = await cal(q);
save.disabled = false;
if (r.ok) { toast('Corrected ✓'); closePanel(); await refresh(); }
else toast('Could not save: ' + (r.error || 'unknown') + (r.code ? ' [' + r.code + ']' : ''));
};
const del = el('div'); del.style.cssText = 'display:flex;align-items:center;gap:9px;padding-top:4px';
del.innerHTML = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" style="flex-shrink:0">'
+ '<path d="M4.5 6.5h15M9.5 6.5V4.8h5v1.7M6.7 6.5l.9 12.2h8.8l.9-12.2" stroke="var(--danger)" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>';
const forget = el('button', 'btn danger', 'Forget this memory');
del.appendChild(lock(forget));
del.appendChild(el('span', 'meta', '— cannot be undone'));
forget.onclick = async () => {
if (!confirm('Forget this memory?\n\n"' + sentence({ type: g.type, fields: f })
+ '"\n\nThe content is erased for good. This cannot be undone.')) return;
const r = await cal('FORGET sha256:' + hash);
if (r.ok) { toast('Forgotten'); closePanel(); await refresh(); }
else toast('Could not forget: ' + (r.error || 'unknown'));
};
acts.appendChild(del);
p.appendChild(acts);
/* developer details */
const dev = el('div', 'pgroup dev-only dev-flex');
dev.appendChild(el('span', 'sec-label', 'DEVELOPER DETAILS'));
const hh = el('div', 'mono'); hh.textContent = g.hash || hash;
hh.style.cssText = 'word-break:break-all;cursor:pointer'; hh.title = 'click to copy';
hh.onclick = () => copyText(g.hash || hash, 'Content address');
dev.appendChild(hh);
dev.appendChild(el('pre', 'code', JSON.stringify(g.fields, null, 2)));
const cp = el('button', 'btn ghost sm', 'Copy grain JSON');
cp.onclick = () => copyText(JSON.stringify(g, null, 2), 'Grain JSON');
dev.appendChild(cp);
/* "As the model sees it" (docs/anonymization-proposal.md §8.3): the same
grain through the egress boundary — pseudonymized fields, whether or
not a policy is declared yet. The single most persuasive view this
feature has. */
const mv = el('button', 'btn ghost sm', 'Model view');
mv.style.marginLeft = '8px';
mv.onclick = async () => {
mv.disabled = true;
const pv = await api('/api/anon/preview?hash=' + encodeURIComponent(g.hash || hash));
mv.disabled = false;
if (!pv || pv.ok === false) { toast('Preview unavailable: ' + ((pv && pv.error) || '')); return; }
const pre = el('pre', 'code', JSON.stringify(pv.fields, null, 2));
pre.style.borderLeft = '2px solid var(--warn)';
dev.appendChild(el('span', 'sec-label', 'AS THE MODEL SEES IT'));
dev.appendChild(pre);
mv.remove();
};
dev.appendChild(mv);
p.appendChild(dev);
}
/* ══ activity ═════════════════════════════════════════════════════════ */
const ACT_KINDS = [['all', 'Everything'], ['add', 'Learned'], ['supersede', 'Changed'], ['forget', 'Deleted']];
/* null = the bound session default (the already-loaded global LOG/BYHASH —
no extra fetch). Anything else fetches that namespace's browse rows once
(cached) and reads op/hash/fields straight off them instead — a
namespace-scoped BROWSE row is already everything an op-log row plus a
BYHASH lookup would have given us. */
let ACT_NS = null;
async function actSetNamespace(ns) {
ACT_NS = (!ns || ns === boundNamespace()) ? null : ns;
await renderActivity();
}
async function renderActivity() {
renderCrumbHeader('actCrumb', [{ label: 'Activity' }], 'Everything your agent learned, changed, or forgot — newest first.');
const f = $('actFilters'); f.textContent = '';
for (const [k, label] of ACT_KINDS) {
const c = el('span', 'chip' + (ACTFILTER === k ? ' on' : ''), label);
c.onclick = () => { ACTFILTER = k; renderActivity(); };
f.appendChild(c);
}
const nsHost = $('actNsHost'); nsHost.textContent = '';
nsHost.appendChild(nsCombo('actNs', ACT_NS || boundNamespace(), actSetNamespace));
const host = $('actList'); host.textContent = '';
// A namespace-scoped browse row already carries op/hash/hlc *and* the
// resolved fields in one object — strictly more than /api/log's bare
// op-log entries, and (unlike /api/log, which spans every namespace with
// no filter of its own) it only ever contains this namespace's grains, so
// every row here resolves instead of falling through to a bare hash.
const rows = await browseForNamespace(ACT_NS || boundNamespace());
let ops = rows.slice().sort((a, b) => (b.op_seq || 0) - (a.op_seq || 0)).filter(o => !isInternal(o));
if (ACTFILTER !== 'all') ops = ops.filter(o => o.op === ACTFILTER);
if (!ops.length) { host.appendChild(el('div', 'empty', 'Nothing here yet.')); return; }
let day = null;
for (const o of ops.slice(0, 200)) {
const ms = hlcMs(o.hlc);
if (dayKey(ms) !== day) {
day = dayKey(ms);
const h = el('span', 'sec-label', dayLabel(ms));
h.style.cssText = 'display:block;padding:24px 0 12px;font-size:13px;letter-spacing:.06em';
host.appendChild(h);
}
const g = o;
const ev = el('div', 'ev');
ev.appendChild(el('span', 'at', clock(ms)));
const ic = el('span', 'ic');
ic.innerHTML = o.op === 'add'
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke="var(--ok)" stroke-width="2.4" stroke-linecap="round"/></svg>'
: o.op === 'forget'
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12h14" stroke="var(--danger)" stroke-width="2.4" stroke-linecap="round"/></svg>'
: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M4 8h11l-3-3M20 16H9l3 3" stroke="var(--warn)" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"/></svg>';
ev.appendChild(ic);
const body = el('div', 'body');
const verb = o.op === 'add' ? 'Learned that ' : o.op === 'supersede' ? 'Updated: ' : 'Deleted ';
body.appendChild(el('div', 'say', g && g.fields
? verb + lowerFirst(sentence(g))
: verb.trim() + ' a memory (' + shortHash(o.hash) + ')'));
/* The time is already in the left column — drop the "Learned …" part. */
const sub = o.op === 'forget'
? 'You asked for this — the content was erased, not just hidden'
: o.op === 'supersede' ? 'The previous version is kept so you can see the change'
: (g ? provenanceParts(g).filter(p => !/^Learned /.test(p)).join(' · ') : '');
if (sub) body.appendChild(el('div', 'prov', sub));
const dev = el('div', 'mono dev-only');
dev.textContent = 'op ' + o.op_seq + ' · ' + o.op + ' · ' + (o.hash || '').slice(0, 12);
body.appendChild(dev);
ev.appendChild(body);
/* A wide row has room to say what kind of grain this is and where it
lives — without that, the extra width past the text is just blank. */
const tags = el('div', 'ev-tags');
if (g && g.type) {
const kind = el('span', 'tag'); kind.style.cssText = 'background:var(--well);color:var(--dim);font-weight:500';
kind.textContent = g.type;
tags.appendChild(kind);
}
if (g && g.fields && g.fields.namespace) tags.appendChild(el('span', 'tiny mono', g.fields.namespace));
ev.appendChild(tags);
ev.style.cursor = 'pointer';
ev.onclick = () => openPanel(o.hash);
host.appendChild(ev);
}
}
/* ══ suggestions ══════════════════════════════════════════════════════ */
/* "loop.contradiction_sweep/1" → "contradiction sweep" */
const analyzerName = id => String(id || '').replace(/^loop\./, '').replace(/\/\d+$/, '').replace(/[._-]/g, ' ');
function analyzerWord(id) {
const s = analyzerName(id);
if (/contradict|conflict/.test(s)) return 'a conflict';
if (/dup/.test(s)) return 'a duplicate';
if (/stale|decay/.test(s)) return 'something stale';
if (/gap|missing/.test(s)) return 'a gap';
return s || 'a finding';
}
function sevStyle(sev) {
if (sev === 'high') return ['var(--danger)', 'var(--danger-soft)'];
if (sev === 'medium') return ['var(--warn)', 'var(--warn-soft)'];
if (sev === 'low') return ['var(--cat-project)', 'var(--accent-soft)'];
return ['var(--muted)', 'var(--raise)'];
}
function renderSuggestions() {
renderCrumbHeader('sugCrumb', [{ label: 'Suggestions' }],
'Ways to make this memory more reliable. Nothing is changed until you approve it, and every change can be undone.');
const host = $('sugList'); host.textContent = '';
if (!canWrite()) host.appendChild(readOnlyNote());
const list = RECS[SUGTAB] || [];
if (!list.length) {
host.appendChild(el('div', 'empty', SUGTAB === 'pending'
? 'Nothing needs your attention. Run an analysis to look again.'
: SUGTAB === 'applied' ? 'Nothing has been applied yet.' : 'Nothing dismissed.'));
}
for (const r of list) host.appendChild(sugCard(r));
if (SUGTAB === 'applied') renderOutcomes(host);
}
function sugCard(r) {
const [fg, bg] = sevStyle(r.severity);
const card = el('div', 'card sug');
const head = el('div'); head.style.cssText = 'display:flex;align-items:center;gap:10px';
const tag = el('span', 'tag', null); tag.style.cssText = 'background:' + bg + ';color:' + fg;
const d = el('span'); d.style.cssText = 'width:6px;height:6px;border-radius:3px;background:' + fg;
tag.appendChild(d); tag.appendChild(el('span', null, cap(analyzerWord(r.analyzer).replace(/^an? /, ''))));
head.appendChild(tag);
head.appendChild(el('span', 'meta', 'Found by the ' + analyzerName(r.analyzer) + ' check'));
const sp = el('div'); sp.style.flex = '1'; head.appendChild(sp);
head.appendChild(el('span', 'meta', r.status || ''));
card.appendChild(head);
const body = el('div'); body.style.cssText = 'display:flex;flex-direction:column;gap:8px';
const t = el('span', null, r.summary || 'A suggestion');
t.style.cssText = 'font:600 19px/27px var(--sans);color:var(--ink);letter-spacing:-.015em';
body.appendChild(t);
if (r.destructive) body.appendChild(el('span', 'sub',
'This one removes content for good. It cannot be undone once applied.'));
else body.appendChild(el('span', 'sub',
'Applying this changes what your agent reads next time. The old version stays in history.'));
card.appendChild(body);
const ev = evidenceRows(r.evidence);
if (ev) card.appendChild(ev);
const acts = el('div', 'acts');
const reason = el('div', 'reason'); reason.hidden = true;
const prompt = el('span', 'meta');
const line = el('div', 'line');
const why = document.createElement('input'); why.type = 'text';
const gate = document.createElement('input'); gate.type = 'text';
gate.placeholder = 'gate run id (eval-…)'; gate.hidden = true;
const conf = el('button', 'btn sm', 'Confirm');
const cancel = el('button', 'btn ghost sm', 'Cancel');
line.appendChild(why); line.appendChild(gate); line.appendChild(conf); line.appendChild(cancel);
reason.appendChild(prompt); reason.appendChild(line);
if (r.status === 'applied') {
if (r.rollbackable) {
const undo = el('button', 'btn ghost', 'Undo');
undo.onclick = () => arm('rollback', 'Why are you undoing this?', 'Undo it');
acts.appendChild(lock(undo));
}
acts.appendChild(el('span', 'note', r.rollbackable ? 'Undoable · the previous state is kept' : 'Not undoable'));
} else if (r.status === 'rejected') {
/* Rejected is terminal in the engine's lifecycle — offering a button
here would only ever produce an error. */
acts.appendChild(el('span', 'note', 'Dismissed — it will not be applied.'));
} else if (r.status === 'approved') {
/* Approved but not yet applied: usually because an apply failed midway.
Surface it rather than letting it fall between the tabs. */
const go = el('button', 'btn', 'Finish applying');
go.onclick = () => arm('apply', 'Why are you applying this?', 'Apply it');
acts.appendChild(lock(go));
acts.appendChild(el('span', 'note', 'You approved this, but it has not been applied yet.'));
} else {
const ok = el('button', 'btn', r.destructive ? 'Apply — removes content' : 'Apply this fix');
ok.onclick = () => arm('approve_and_apply', 'Why are you applying this?', 'Apply it');
const no = el('button', 'btn ghost', 'Dismiss');
no.onclick = () => arm('reject', 'Why are you dismissing this?', 'Dismiss it');
acts.appendChild(lock(ok)); acts.appendChild(lock(no));
acts.appendChild(el('span', 'note', r.destructive
? 'Cannot be undone' : r.rollbackable ? 'Undoable · the older memory stays in history' : ''));
}
card.appendChild(acts); card.appendChild(reason);
const dev = el('div', 'mono dev-only');
dev.textContent = (r.hash || '').slice(0, 16) + ' · ' + (r.analyzer || '') + ' · severity ' + (r.severity || '?')
+ (r.target_ref ? ' · target ' + String(r.target_ref).slice(0, 12) : '');
card.appendChild(dev);
let armed = null;
const gated = !!r.evalset_hash;
function arm(action, promptText, confirmLabel) {
armed = action;
const applying = action === 'apply' || action === 'approve_and_apply';
prompt.textContent = promptText + ' Your answer is recorded in the audit trail.'
+ (gated && applying
? ' This change is gated: paste the run id from `areev eval run --evalset '
+ String(r.evalset_hash).slice(0, 12) + '…`.'
: '');
gate.hidden = !(gated && applying);
conf.textContent = confirmLabel;
why.placeholder = 'e.g. confirmed with the customer on the call';
acts.hidden = true; reason.hidden = false;
why.focus();
}
cancel.onclick = () => { armed = null; why.value = ''; gate.value = ''; reason.hidden = true; acts.hidden = false; };
conf.onclick = async () => {
if (!why.value.trim()) { toast('A reason is required — it goes in the audit trail'); why.focus(); return; }
if (!gate.hidden && !gate.value.trim()) {
toast('This change applies only with a recorded gate run — run the evalset first and paste its run id');
gate.focus(); return;
}
conf.disabled = true; cancel.disabled = true;
await loopAct(r.hash, armed, why.value.trim(), gate.hidden ? '' : gate.value.trim());
conf.disabled = false; cancel.disabled = false;
};
return card;
}
/* Areev Loop cites evidence as bare content addresses (Vec<String>). A hash is
not evidence to a human — resolve it to the sentence it stands for, and
say so plainly when the grain is not in the loaded window. */
const HASH_RE = /^(sha256:)?[0-9a-f]{64}$/i;
/* Areev Loop's own records are Facts too — cite them as what they are rather
than dumping the serialized recommendation into the card. */
function internalLabel(g) {
const f = g.fields || {};
if (f.relation === 'loop_recommendation') {
let a = null;
try { a = JSON.parse(f.object).analyzer; } catch (e) { /* not JSON */ }
return a ? 'An earlier suggestion from the ' + analyzerName(a) + ' check'
: 'An earlier suggestion from this memory’s review queue';
}
if (f.relation === 'loop_audit') return 'An entry in the audit trail';
return 'An internal Areev record';
}
function describeRef(ref) {
const hash = String(ref).replace(/^sha256:/, '');
const g = BYHASH[hash];
if (!g) return { text: 'A memory outside the loaded window', when: '', hash };
const text = isInternal(g) ? internalLabel(g) : sentence(g);
return { text, when: relTime(hlcMs(g.hlc)), hash };
}
function evidenceRows(evidence) {
if (!evidence) return null;
let items = [];
if (Array.isArray(evidence)) items = evidence;
else if (typeof evidence === 'object') {
for (const k of ['items', 'grains', 'facts', 'rows']) if (Array.isArray(evidence[k])) { items = evidence[k]; break; }
if (!items.length) items = Object.entries(evidence).map(([k, v]) => ({ text: k + ': ' + (typeof v === 'object' ? JSON.stringify(v) : v) }));
}
if (!items.length) return null;
const box = el('div', 'evi');
for (const it of items.slice(0, 6)) {
const row = el('div', 'evi-row');
const mark = el('span'); mark.style.cssText = 'width:18px;flex-shrink:0;display:flex;justify-content:center';
mark.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M6 12h12" stroke="var(--ghost)" stroke-width="2.2" stroke-linecap="round"/></svg>';
row.appendChild(mark);
let text, when = '', hash = null;
if (typeof it === 'string') {
if (HASH_RE.test(it.trim())) ({ text, when, hash } = describeRef(it.trim()));
else text = it;
} else if (it && typeof it === 'object') {
const h = it.hash || it.grain || it.ref;
text = it.text || it.summary || it.label;
if (h) { const d = describeRef(h); hash = d.hash; when = d.when; if (!text) text = d.text; }
if (!text) text = JSON.stringify(it);
} else text = String(it);
row.appendChild(el('span', 't', text));
if (hash) {
const h = el('span', 'mono dev-only', hash.slice(0, 12));
h.style.cssText = 'flex-shrink:0;margin-right:10px';
row.appendChild(h);
row.onclick = () => openPanel(hash);
row.style.cursor = 'pointer';
}
row.appendChild(el('span', 'w', when));
box.appendChild(row);
}
/* Never truncate silently — a card citing 10 memories must not look like
it cites 6. */
if (items.length > 6) {
const more = el('div', 'evi-row');
const pad = el('span'); pad.style.cssText = 'width:18px;flex-shrink:0';
more.appendChild(pad);
more.appendChild(el('span', 't', '…and ' + (items.length - 6) + ' more'))
.style.color = 'var(--dim)';
box.appendChild(more);
}
return box;
}
async function renderOutcomes(parent) {
const r = await api('/api/loop/outcomes');
const list = (r && r.ok && r.outcomes) || [];
if (!list.length) return;
const host = el('div', 'stack');
parent.appendChild(host);
const head = el('div', 'grp-head'); head.appendChild(el('h2', null, 'Did it work?'));
head.appendChild(el('span', 'meta', 're-measured after each applied change'));
host.appendChild(head);
for (const o of list) {
const row = el('div', 'srow');
const good = o.verdict !== 'regressed';
const dot = el('span'); dot.style.cssText = 'width:6px;height:6px;border-radius:3px;flex-shrink:0;background:'
+ (good ? 'var(--ok)' : 'var(--danger)');
row.appendChild(dot);
const hz = o.horizon_ms % 86400000 === 0 ? (o.horizon_ms / 86400000) + ' days' : (o.horizon_ms / 3600000) + ' hours';
row.appendChild(el('span', 't', cap(String(o.metric || '').replace(/_/g, ' '))
+ ' went from ' + o.baseline + ' to ' + o.current + ' after ' + hz));
const v = el('span', 'w', o.verdict); v.style.color = good ? 'var(--ok)' : 'var(--danger)';
row.appendChild(v);
host.appendChild(row);
}
}
/* A console started without --token-env refuses every write. Say so up front
rather than letting someone type a reason and hit a wall. */
const canWrite = () => !!(CONFIG && CONFIG.server && CONFIG.server.auth_required);
const READONLY_WHY = 'This console is read-only — restart it with “areev ui --token-env VAR” to make changes.';
function lock(btn) { if (!canWrite()) { btn.disabled = true; btn.title = READONLY_WHY; } return btn; }
function readOnlyNote() {
const b = el('div', 'banner');
b.style.cssText = 'background:var(--accent-soft);border-color:var(--accent-line)';
b.appendChild(el('span', 'grow', 'Read-only. You can look at everything here, but approving, correcting '
+ 'and forgetting need a console started with a token: areev ui --token-env VAR'));
return b;
}
const errText = res => ((res && res.error) || 'unknown error') + (res && res.code ? ' [' + res.code + ']' : '');
/* The engine's lifecycle is Pending → Approved → Applied, so applying a
pending recommendation is two calls, not one — going straight to apply
fails with LOP-E020. One reason covers both: the user made one decision. */
async function loopAct(hash, action, because, gatingRun) {
const post = (url, body) => api(url, { method: 'POST',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
const done = async msg => { toast(msg); RECS = {}; await loadRecs(SUGTAB); await refresh(); };
/* A code or adapter revision applies only with a recorded gate run; the
server loads the stats from the journaled eval summary, never from us. */
const applyBody = gatingRun ? { hash, because, gating_run: gatingRun } : { hash, because };
let res;
if (action === 'approve_and_apply') {
res = await post('/api/loop/review', { hash, decision: 'approve', because });
if (!(res && res.ok)) return done('Could not approve: ' + errText(res));
res = await post('/api/loop/apply', applyBody);
return done(res && res.ok ? 'Applied ✓'
: 'Approved, but applying failed: ' + errText(res) + ' — finish it from Needs review');
}
if (action === 'apply') res = await post('/api/loop/apply', applyBody);
else if (action === 'rollback') res = await post('/api/loop/rollback', { hash, because });
else res = await post('/api/loop/review', { hash, decision: 'reject', because });
return done(res && res.ok
? (action === 'reject' ? 'Dismissed' : action === 'rollback' ? 'Undone ✓' : 'Applied ✓')
: 'Could not ' + (action === 'reject' ? 'dismiss' : action) + ': ' + errText(res));
}
async function runAnalysis() {
const b = $('runLoop'); b.disabled = true; b.textContent = 'Analysing…';
const res = await api('/api/loop/run', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
b.disabled = false; b.textContent = 'Run analysis';
if (res && res.ok) {
const n = (res.run && res.run.stored) || 0;
toast(n ? 'Found ' + n + (n === 1 ? ' suggestion' : ' suggestions') : 'Nothing new found');
} else toast('Could not run: ' + ((res && res.error) || 'the console may be read-only'));
RECS = {}; SUGTAB = 'pending'; await loadRecs('pending'); render();
}
/* ══ connect ══════════════════════════════════════════════════════════ */
/* Commands want the path the server actually opened, not the pretty label. */
const DB_NAME = () => DB_PATH || ($('dblabel').textContent || 'memory.db').trim();
function snippetFor(kind) {
const db = DB_NAME();
if (kind === 'claude') return 'claude mcp add areev -- areev serve --mcp --db ' + db;
if (kind === 'python') return 'import areev\ndb = areev.Areev("' + db + '", actor="user:me")\ndb.add_fact("john", "prefers", "green tea")\nprint(db.recall(subject="john"))';
if (kind === 'node') return 'import { Areev } from "areev";\nconst db = new Areev("' + db + '", "user:me");\ndb.addFact("john", "prefers", "green tea");\nconsole.log(db.recall("john"));';
return '{\n "mcpServers": {\n "areev": {\n "command": "areev",\n "args": ["serve", "--mcp", "--db", "' + db + '"]\n }\n }\n}';
}
function renderSettingsPage() {
// The Developer tab only exists once Developer mode is on (its button
// carries `dev-only`, same as the rest of the app's dev chrome) — if it
// was turned off while this tab was open, fall back rather than render a
// tab nothing points at any more.
if (CONTAB === 'developer' && !document.documentElement.classList.contains('dev')) CONTAB = 'general';
renderCrumbHeader('setCrumb', [{ label: 'Settings' }],
'Attach agents to this memory and configure how this console itself behaves.');
const host = $('conBody'); host.textContent = '';
if (CONTAB === 'agent') return renderConnectAgent(host);
if (CONTAB === 'developer') return renderConnectDeveloper(host);
return renderConnectGeneral(host);
}
let SNIPTAB = 'claude';
function renderConnectAgent(host) {
const empty = !currentGrains().length;
const hero = el('div'); hero.style.cssText = 'display:flex;flex-direction:column;gap:12px;max-width:650px;padding-bottom:8px';
const h = el('span', null, empty ? 'Your agent’s memory is ready — and empty.' : 'Attach another agent to this memory.');
h.style.cssText = 'font:700 32px/40px var(--sans);color:var(--ink);letter-spacing:-.03em';
hero.appendChild(h);
hero.appendChild(el('span', 'sub', empty
? 'Point an agent at this file. Everything it learns lands here as plain sentences you can read, correct, and delete.'
: 'Anything you connect reads and writes the same memory — they will all know what the others learned.'));
host.appendChild(hero);
const card = el('div', 'card');
const tabs = el('div', 'tabs'); tabs.style.cssText = 'padding:16px 24px 0;gap:24px';
for (const [k, label] of [['claude', 'Claude Code'], ['python', 'Python'], ['node', 'Node'], ['mcp', 'Any MCP client']]) {
const b = el('button', SNIPTAB === k ? 'on' : '', label);
b.onclick = () => { SNIPTAB = k; render(); };
tabs.appendChild(b);
}
card.appendChild(tabs);
const s1 = el('div'); s1.style.cssText = 'display:flex;flex-direction:column;gap:12px;padding:22px 24px 4px';
s1.appendChild(el('span', null, '1 · Attach the memory')).style.cssText = 'font-size:14px;font-weight:600;color:var(--ink)';
const codeRow = el('div');
codeRow.style.cssText = 'display:flex;align-items:flex-start;gap:16px;background:var(--well);border:1px solid var(--hair);border-radius:10px;padding:15px 14px 15px 18px';
const pre = el('pre', null, snippetFor(SNIPTAB));
pre.style.cssText = 'flex:1;font-family:var(--mono);font-size:13.5px;line-height:22px;color:var(--ink);white-space:pre-wrap;word-break:break-word;margin:0';
const cp = el('button', 'btn ghost sm', 'Copy');
cp.onclick = () => copyText(snippetFor(SNIPTAB), 'Command');
codeRow.appendChild(pre); codeRow.appendChild(cp);
s1.appendChild(codeRow);
card.appendChild(s1);
const s2 = el('div'); s2.style.cssText = 'display:flex;flex-direction:column;gap:12px;padding:20px 24px 22px';
s2.appendChild(el('span', null, '2 · Ask it to remember something')).style.cssText = 'font-size:14px;font-weight:600;color:var(--ink)';
const quote = el('div');
quote.style.cssText = 'border:1px dashed var(--line2);border-radius:10px;padding:15px 18px;font-size:15.5px;line-height:24px;color:var(--muted)';
quote.textContent = '“Remember that John Aldridge prefers green tea and works at Acme Corp.”';
s2.appendChild(quote);
card.appendChild(s2);
const strip = el('div');
strip.style.cssText = 'display:flex;align-items:center;gap:11px;padding:16px 24px;border-top:1px solid var(--line);'
+ 'background:' + (empty ? 'var(--accent-soft)' : 'var(--ok-soft)');
const ring = el('span');
ring.style.cssText = 'width:16px;height:16px;flex-shrink:0;border-radius:8px;display:flex;align-items:center;justify-content:center;background:'
+ (empty ? 'var(--accent-line)' : 'var(--ok-line)');
const core = el('span'); core.style.cssText = 'width:7px;height:7px;border-radius:4px;background:' + (empty ? 'var(--accent)' : 'var(--ok)');
ring.appendChild(core); strip.appendChild(ring);
const st = el('span', null, empty
? 'Watching for the first memory — this page fills in on its own.'
: STATS.grains + ' memories stored. Reload after your agent writes to see new ones.');
st.style.cssText = 'flex:1;font-size:14px;color:' + (empty ? 'var(--accent)' : 'var(--ok)');
strip.appendChild(st);
const rl = el('button', 'btn ghost sm', 'Reload'); rl.onclick = refresh;
strip.appendChild(rl);
card.appendChild(strip);
host.appendChild(card);
const three = el('div'); three.style.cssText = 'display:flex;gap:44px;padding-top:16px';
const bit = (t, s) => { const c = el('div'); c.style.cssText = 'display:flex;flex-direction:column;gap:6px;flex:1';
const tt = el('span', null, t); tt.style.cssText = 'font-size:14.5px;font-weight:600;color:var(--ink)';
c.appendChild(tt); c.appendChild(el('span', 'meta', s)); return c; };
three.appendChild(bit('It writes, you read', 'Every fact your agent stores shows up here in plain language — no query needed.'));
three.appendChild(bit('Nothing is overwritten', 'Corrections are added on top, so you can always see what your agent used to believe.'));
three.appendChild(bit('It flags its own mistakes', 'Conflicts and duplicates arrive as suggestions you approve — never applied behind your back.'));
host.appendChild(three);
}
/* One toggle row, shared by Developer mode and Dark mode — same markup the
rail used to own, now built fresh on every render instead of wired once
at boot, since it lives inside a page section that redraws per visit. */
function settingsToggle(label, isOn, onToggle) {
const row = el('div', 'toggle-row');
row.appendChild(el('span', null, label));
const btn = el('button', 'sw' + (isOn ? ' on' : ''));
btn.setAttribute('aria-label', label);
btn.appendChild(el('i'));
btn.onclick = () => onToggle(btn);
row.appendChild(btn);
return row;
}
function renderConnectGeneral(host) {
const appearance = el('div', 'card'); appearance.style.cssText = 'padding:8px 22px 18px;margin-bottom:16px';
appearance.appendChild(el('h2', null, 'This console')).style.padding = '10px 0';
appearance.appendChild(settingsToggle('Developer mode', document.documentElement.classList.contains('dev'), btn => {
const on = document.documentElement.classList.toggle('dev');
localStorage.setItem('areev.dev', on ? '1' : '0');
btn.classList.toggle('on', on);
render();
}));
appearance.appendChild(settingsToggle('Dark mode',
(document.documentElement.dataset.theme || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')) === 'dark',
btn => {
const cur = document.documentElement.dataset.theme || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
const next = cur === 'dark' ? 'light' : 'dark';
document.documentElement.dataset.theme = next;
localStorage.setItem('areev.theme', next);
btn.classList.toggle('on', next === 'dark');
Graph.recolor(); WFGraph.recolor(); render();
}));
host.appendChild(appearance);
const c = CONFIG;
if (!c || c.ok === false) { host.appendChild(el('div', 'empty', 'Configuration unavailable.')); return; }
const warn = (c.warnings || []);
if (warn.length) {
const b = el('div', 'banner'); b.style.marginBottom = '8px';
b.appendChild(el('span', 'grow', warn.join(' · ')));
host.appendChild(b);
}
const box = el('div', 'card'); box.style.cssText = 'padding:8px 22px 18px';
const add = (k, v) => { const r = el('div', 'kv');
r.appendChild(el('span', 'k', k)); r.appendChild(el('span', 'v', v)); box.appendChild(r); };
add('Memory file', c.db || DB_NAME());
add('Full-text search', c.file && c.file.text_index ? 'on — your agent can search by words' : 'off');
add('Vector search', c.recall && c.recall.legs && c.recall.legs.vector
? 'on' + (c.file && c.file.embedding ? ' — ' + c.file.embedding.model : '') : 'off — no embedding backend attached');
add('How recall ranks', 'structural' + (c.recall && c.recall.legs && c.recall.legs.bm25 ? ' + words' : '')
+ (c.recall && c.recall.legs && c.recall.legs.vector ? ' + meaning' : '') + ', fused with RRF');
add('Namespace', (c.session && c.session.namespace) || 'shared');
add('Console access', c.server && c.server.auth_required
? (c.server.auth_all ? 'protected — every request needs the token' : 'writes need the token')
: 'open — anyone who can reach this port can read and change memory');
add('Result limit', ((c.executor && c.executor.default_limit) || '?') + ' default, '
+ ((c.executor && c.executor.max_limit) || '?') + ' max');
host.appendChild(box);
const ah = el('div', 'grp-head');
ah.appendChild(el('h2', null, 'What it checks itself for'));
ah.appendChild(el('span', 'meta', 'analyzers that produce suggestions'));
host.appendChild(ah);
const alist = el('div'); host.appendChild(alist);
api('/api/loop/analyzers').then(r => {
const list = (r && r.ok && r.analyzers) || [];
if (!list.length) { alist.appendChild(el('div', 'empty', 'No analyzers reported.')); return; }
for (const a of list) {
const row = el('div', 'srow'); row.style.cursor = 'default'; row.style.alignItems = 'flex-start';
const d = el('span'); d.style.cssText = 'width:6px;height:6px;border-radius:3px;flex-shrink:0;margin-top:8px;background:'
+ (a.enabled ? 'var(--ok)' : 'var(--ghost)');
row.appendChild(d);
/* Name over the analyzer's own one-line description: a toggle you cannot
read is a toggle nobody touches. */
const body = el('div', 't');
body.style.cssText = 'display:flex;flex-direction:column;gap:2px;min-width:0';
body.appendChild(el('span', null, a.title || analyzerName(a.id)));
if (a.description) {
const sub = el('span', 'tiny', a.description);
sub.style.lineHeight = '18px';
body.appendChild(sub);
}
row.appendChild(body);
const sw = el('button', 'btn ghost sm', a.enabled ? 'On' : 'Off');
sw.onclick = async () => {
sw.disabled = true;
const res = await api('/api/loop/config', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ analyzer_id: a.id, enabled: !a.enabled }) });
sw.disabled = false;
if (res && res.ok) { toast(a.enabled ? 'Turned off' : 'Turned on'); render(); }
else toast('Could not change it: ' + ((res && res.error) || 'the console may be read-only'));
};
row.appendChild(lock(sw));
const dev = el('span', 'mono dev-only'); dev.textContent = a.id + ' · ' + (a.tier || '');
dev.style.cssText = 'margin-left:10px';
row.appendChild(dev);
alist.appendChild(row);
}
});
/* Anonymization (docs/anonymization-proposal.md §8.3): declared per-
namespace policies, the host floor, and a plain-language declare/clear
form. Modes only — the placeholder→value mappings never reach the
browser (D5 custody). */
const anh = el('div', 'grp-head');
anh.appendChild(el('h2', null, 'Anonymization'));
anh.appendChild(el('span', 'meta', 'what leaves for the model, pseudonymized'));
host.appendChild(anh);
const abox = el('div', 'card'); abox.style.cssText = 'padding:12px 22px 16px';
const anon = (c.anonymization || { policies: [], floor: false, audit_counts: [] });
if (anon.floor) {
const fr = el('div', 'kv');
fr.appendChild(el('span', 'k', 'Host floor'));
fr.appendChild(el('span', 'v', 'on — every namespace is pseudonymized on the way out'));
abox.appendChild(fr);
}
if (!anon.policies.length) {
abox.appendChild(el('div', 'empty', anon.floor
? 'No per-namespace policies declared.'
: 'No policies declared — memories leave for the model as-is.'));
} else {
for (const p of anon.policies) {
const r = el('div', 'kv');
r.appendChild(el('span', 'k', p.ns));
r.appendChild(el('span', 'v', p.mode === 'egress'
? 'pseudonymized on the way to the model'
: p.mode === 'audit' ? 'counting what would be hidden (audit)'
: p.mode));
abox.appendChild(r);
}
}
const form = el('div');
form.style.cssText = 'display:flex;gap:8px;align-items:center;margin-top:10px;flex-wrap:wrap';
const nsIn = el('input'); nsIn.className = 'qin'; nsIn.placeholder = 'namespace';
nsIn.style.cssText = 'flex:0 1 160px;min-width:120px';
const modeSel = document.createElement('select'); modeSel.className = 'qin';
for (const [v, label] of [['egress', 'Pseudonymize for the model'], ['audit', 'Audit only'], ['off', 'Off']]) {
const o = document.createElement('option'); o.value = v; o.textContent = label; modeSel.appendChild(o);
}
const declare = el('button', 'btn sm', 'Declare');
declare.onclick = async () => {
const ns = nsIn.value.trim();
if (!ns) { toast('Name the namespace first'); return; }
declare.disabled = true;
const res = await api('/api/anon/config', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ns, policy: { mode: modeSel.value } }) });
declare.disabled = false;
if (res && res.ok) { toast('Policy declared — it travels with the file'); loadConfig().then(render); }
else toast('Could not declare it: ' + ((res && res.error) || 'the console may be read-only'));
};
const clear = el('button', 'btn ghost sm', 'Clear');
clear.onclick = async () => {
const ns = nsIn.value.trim();
if (!ns) { toast('Name the namespace first'); return; }
clear.disabled = true;
const res = await api('/api/anon/config', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ns, clear: true }) });
clear.disabled = false;
if (res && res.ok) { toast('Policy cleared'); loadConfig().then(render); }
else toast('Could not clear it: ' + ((res && res.error) || 'the console may be read-only'));
};
form.appendChild(nsIn); form.appendChild(styledSelect(modeSel));
form.appendChild(lock(declare)); form.appendChild(lock(clear));
abox.appendChild(form);
const auditRows = anon.audit_counts || [];
if (auditRows.length) {
const ad = el('div', 'mono dev-only');
ad.style.cssText = 'margin-top:8px';
ad.textContent = 'audit: ' + auditRows.map(r => r.ns + '/' + r.category + '=' + r.count).join(' · ');
abox.appendChild(ad);
}
host.appendChild(abox);
}
/* ══ developer tab (Settings → Developer) ════════════════════════════
Used to be #devbar, a fixed 330px card sticky-pinned to the right of
every page whenever Developer mode was on. It carried no state of its
own beyond that toggle, so it belongs beside the toggle that reveals it
— a normal tab in Settings — rather than floating over the page. */
function renderConnectDeveloper(host) {
const statsCard = el('div', 'card'); statsCard.style.cssText = 'padding:14px 22px 18px;margin-bottom:16px';
statsCard.appendChild(el('h2', null, 'Store')).style.padding = '10px 0';
const s = el('div'); statsCard.appendChild(s);
const kv = (k, v) => { const r = el('div'); r.style.cssText = 'display:flex;align-items:baseline;gap:10px;padding:5px 0';
const a = el('span', null, k); a.style.cssText = 'flex:1;font-size:13.5px;color:var(--text)';
const b = el('span', null, v); b.style.cssText = 'font-family:var(--mono);font-size:13px;color:var(--ink)';
r.appendChild(a); r.appendChild(b); s.appendChild(r); };
kv('grains / current', (STATS.grains != null ? STATS.grains : '?') + ' / ' + (STATS.current != null ? STATS.current : '?'));
kv('triples / terms', (STATS.triples != null ? STATS.triples : '?') + ' / ' + (STATS.terms != null ? STATS.terms : '?'));
const legs = CONFIG && CONFIG.recall && CONFIG.recall.legs;
kv('recall legs', legs ? ['struct', legs.bm25 && 'bm25', legs.vector && 'vec'].filter(Boolean).join(' · ') : '?');
kv('ops', STATS.ops != null ? String(STATS.ops) : '?');
host.appendChild(statsCard);
const logCard = el('div', 'card'); logCard.style.cssText = 'padding:4px 22px 8px;margin-bottom:16px';
logCard.appendChild(el('h2', null, 'Op log')).style.padding = '10px 0';
const l = el('div'); logCard.appendChild(l);
for (const o of LOG.slice().sort((a, b) => (b.op_seq || 0) - (a.op_seq || 0)).slice(0, 14)) {
const r = el('div', 'oprow');
r.appendChild(el('span', 't', shortWhen(hlcMs(o.hlc))));
const op = el('span', 'o', o.op);
op.style.color = o.op === 'add' ? 'var(--ok)' : o.op === 'forget' ? 'var(--danger)' : 'var(--warn)';
r.appendChild(op);
/* A hash says an operation happened but not what it did. Resolve it to the
grain and show what was written; keep the address on hover, and fall back
to it when the grain is not in the loaded window (or was erased). */
const g = BYHASH[o.hash];
/* Bookkeeping the engine writes for itself (__loop_state__ and friends)
has no sentence worth reading — name the machinery instead. */
const said = !g ? shortHash(o.hash)
: isInternal(g) ? 'engine bookkeeping · ' + ((g.fields || {}).relation || rgType(g) || '')
: (rgType(g) || 'grain') + ' · ' + sentence(g);
const what = el('span', 'h', said);
if (!g) what.classList.add('addr');
else if (isInternal(g)) what.classList.add('sys');
what.title = (g ? said + '\n' : '') + o.hash;
r.appendChild(what);
r.onclick = () => openPanel(o.hash);
l.appendChild(r);
}
if (!LOG.length) logCard.appendChild(el('div', 'empty', 'No operations logged yet.'));
host.appendChild(logCard);
const calCard = el('div', 'card'); calCard.style.cssText = 'padding:14px 22px 18px;display:flex;flex-direction:column;gap:9px';
calCard.appendChild(el('h2', null, 'CAL')).style.padding = '0 0 2px';
calCard.appendChild(el('span', 'tiny', 'Every view here runs CAL underneath. The full workbench — '
+ 'history, saved queries, templates and every output format — lives on the Query page.'));
const openQ = el('button', 'btn ghost sm', 'Open Query →');
openQ.style.width = 'fit-content';
openQ.onclick = () => go('query');
calCard.appendChild(openQ);
host.appendChild(calCard);
}
/* ══ graph ════════════════════════════════════════════════════════════ */
const Graph = (() => {
let cv, ctx, W = 0, H = 0, dpr = 1;
let nodes = [], links = [], byId = new Map();
let focus = null, depth = 1, near = new Set();
let scale = 1, tx = 0, ty = 0, alpha = 0, raf = 0;
let drag = null, panning = null, hover = null, moved = false;
let cut = 1; /* 0..1 over the op-log — the rewind position */
let colors = {};
function recolor() {
colors = { person: cssVar('--cat-person'), org: cssVar('--cat-org'), project: cssVar('--cat-project'),
thing: cssVar('--cat-thing'), note: cssVar('--cat-note'), line: cssVar('--line2'),
ink: cssVar('--ink'), dim: cssVar('--dim'), faint: cssVar('--faint'), accent: cssVar('--accent'),
surface: cssVar('--surface'), well: cssVar('--well') };
}
function maxSeq() { return memRows().reduce((m, g) => Math.max(m, g.op_seq || 0), 0); }
function cutSeq() { return Math.round(maxSeq() * cut); }
/* Start positions are derived from the name, not Math.random(): the same
file lays out the same way on every reload, so the picture you learned
yesterday is the picture you get today — and a screenshot of it is
reproducible. */
function seedPos(id) {
let h = 2166136261;
for (let i = 0; i < id.length; i++) { h ^= id.charCodeAt(i); h = Math.imul(h, 16777619); }
h >>>= 0;
/* Keep the starting spread tight — the settle pass below has a fixed
budget, and a wide ring leaves stragglers stranded outside it. */
const a = (h % 3600) / 3600 * Math.PI * 2, r = 25 + ((h >>> 12) % 135);
return { x: Math.cos(a) * r, y: Math.sin(a) * r };
}
function build() {
const limit = cutSeq();
const upTo = memRows().filter(g => (g.op_seq || 0) <= limit)
.filter(g => !isGone(g) && !isInternal(g))
/* a supersede that happened after the cut has not happened yet */
.filter(g => !g.superseded_by || (memByHash()[g.superseded_by] && (memByHash()[g.superseded_by].op_seq || 0) > limit));
/* heads are resolved *as of the cut*, so rewinding shows the value that
was live then, not the one that is live now */
const heads = headHashes(upTo);
const grains = upTo.filter(g => (g.type && g.type !== 'fact') || heads.has(g.hash));
/* Entities only. A memory whose relations we don't recognise could be
filtered down to nothing — if that happens, show it unfiltered rather
than an empty canvas. */
let ents = buildEntities(grains, { tools: false, entityObjects: true });
if (ents.filter(e => e.deg).length < 3) ents = buildEntities(grains, { tools: false });
const keep = new Map();
for (const e of ents) if (e.count || e.deg) keep.set(e.name, e);
const prev = byId;
let placedAnew = false;
nodes = []; links = []; byId = new Map();
for (const e of keep.values()) {
const old = prev.get(e.name);
if (!old) placedAnew = true;
const n = { id: e.name, kind: e.kind, count: e.count, deg: e.deg,
x: old ? old.x : seedPos(e.name).x, y: old ? old.y : seedPos(e.name).y,
vx: 0, vy: 0, r: 0 };
n.r = Math.max(13, Math.min(34, 12 + (e.count + e.deg) * 3));
nodes.push(n); byId.set(n.id, n);
}
for (const g of grains) {
const f = g.fields || {};
if (g.type === 'fact' && f.subject && typeof f.object === 'string'
&& byId.has(f.subject) && byId.has(f.object)) {
links.push({ a: f.subject, b: f.object, label: String(f.relation || '').replace(/_/g, ' '), hash: g.hash });
}
}
if (focus && !byId.has(focus)) focus = null;
if (!focus && nodes.length) focus = nodes.slice().sort((a, b) => (b.count + b.deg) - (a.count + a.deg))[0].id;
computeNear();
/* Settle before the first paint so fit() frames a finished layout
instead of chasing nodes that are still flying apart. A rebuild that
placed nothing new — dragging the rewind scrubber, a data refresh —
keeps the layout it already has: re-converging the whole graph under
the cursor is what made scrubbing feel like an earthquake, and it
left the settled positions dependent on how many rebuilds happened
to run. */
if (placedAnew) {
alpha = 1;
for (let i = 0; i < 420; i++) tick();
alpha = 0.12;
} else {
alpha = 0.03;
for (let i = 0; i < 40; i++) tick();
alpha = 0.02;
}
}
function computeNear() {
near = new Set();
if (!focus) { for (const n of nodes) near.add(n.id); return; }
near.add(focus);
let frontier = [focus];
for (let d = 0; d < depth; d++) {
const next = [];
for (const l of links) {
if (frontier.includes(l.a) && !near.has(l.b)) { near.add(l.b); next.push(l.b); }
if (frontier.includes(l.b) && !near.has(l.a)) { near.add(l.a); next.push(l.a); }
}
frontier = next;
}
}
function tick() {
if (alpha < 0.005) return;
const k = alpha;
for (let i = 0; i < nodes.length; i++) {
const a = nodes[i];
for (let j = i + 1; j < nodes.length; j++) {
const b = nodes[j];
let dx = b.x - a.x, dy = b.y - a.y;
let d2 = dx * dx + dy * dy;
/* Two nodes exactly on top of each other have no direction to push
apart in; nudge them deterministically so the layout stays
reproducible. */
if (d2 < 1) { dx = ((i % 7) - 3) / 7 || .5; dy = ((j % 5) - 2) / 5 || .5; d2 = 1; }
if (d2 > 160000) continue;
const f = (4200 * k) / d2;
const d = Math.sqrt(d2);
a.vx -= (dx / d) * f; a.vy -= (dy / d) * f;
b.vx += (dx / d) * f; b.vy += (dy / d) * f;
}
}
for (const l of links) {
const a = byId.get(l.a), b = byId.get(l.b);
if (!a || !b) continue;
const dx = b.x - a.x, dy = b.y - a.y;
const d = Math.max(1, Math.hypot(dx, dy));
const f = (d - 150) * 0.015 * k;
a.vx += (dx / d) * f; a.vy += (dy / d) * f;
b.vx -= (dx / d) * f; b.vy -= (dy / d) * f;
}
for (const n of nodes) {
const pull = n.id === focus ? 0.03 : 0.004;
n.vx += -n.x * pull * k; n.vy += -n.y * pull * k;
if (drag && drag.id === n.id) { n.vx = 0; n.vy = 0; continue; }
n.x += (n.vx *= 0.82); n.y += (n.vy *= 0.82);
}
alpha *= 0.985;
}
function draw() {
if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, W, H);
ctx.save();
ctx.translate(W / 2 + tx, H / 2 + ty);
ctx.scale(scale, scale);
const labels = [];
/* links */
for (const l of links) {
const a = byId.get(l.a), b = byId.get(l.b);
if (!a || !b) continue;
const lit = focus && (l.a === focus || l.b === focus);
const on = near.has(l.a) && near.has(l.b);
ctx.strokeStyle = lit ? colors.accent : colors.line;
ctx.globalAlpha = lit ? 0.55 : on ? 0.5 : 0.16;
ctx.lineWidth = lit ? 2 : 1.4;
ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
/* Only label edges with room for it — on a short edge the text lands
on top of the node names at either end. */
const len = Math.hypot(b.x - a.x, b.y - a.y);
if (lit && l.label && scale > 0.55 && len > 130) {
const nx = -(b.y - a.y) / len, ny = (b.x - a.x) / len; /* perpendicular */
labels.push({ pri: 1, text: l.label, edge: [(a.x + b.x) / 2, (a.y + b.y) / 2, nx, ny],
font: '12px ' + cssVar('--sans'), fill: colors.dim, alpha: 1 });
}
}
/* nodes */
for (const n of nodes) {
const on = near.has(n.id);
const c = colors[n.kind] || colors.thing;
if (n.id === focus) {
ctx.globalAlpha = 0.09; ctx.fillStyle = c;
ctx.beginPath(); ctx.arc(n.x, n.y, n.r + 20, 0, 7); ctx.fill();
ctx.globalAlpha = 0.35; ctx.strokeStyle = c; ctx.lineWidth = 1.6;
ctx.beginPath(); ctx.arc(n.x, n.y, n.r + 7, 0, 7); ctx.stroke();
}
ctx.globalAlpha = on ? 1 : 0.32;
ctx.fillStyle = c;
ctx.beginPath(); ctx.arc(n.x, n.y, n.r, 0, 7); ctx.fill();
if (hover === n.id) { ctx.globalAlpha = 1; ctx.strokeStyle = colors.ink; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(n.x, n.y, n.r + 3, 0, 7); ctx.stroke(); }
if (n.id === focus && n.r > 24) {
labels.push({ pri: 0, nid: n.id, text: clip(n.id, 12), x: n.x, y: n.y + 5, inside: true,
font: '700 14px ' + cssVar('--sans'), fill: colors.surface, alpha: 1 });
} else {
labels.push({ pri: on ? 2 : 3, nid: n.id, text: clip(n.id, 22), x: n.x, y: n.y, r: n.r,
font: (on ? '600 ' : '') + '13px ' + cssVar('--sans'),
fill: on ? colors.ink : colors.faint, alpha: on ? 1 : 0.45 });
}
}
/* ── labels ──
Node names and relation names compete for the same pixels, so they
are placed by priority — the focused node, then the relations coming
off it, then names, near before far — and one that would land on a
label already placed is dropped. A missing label is recoverable by
hovering or zooming; two labels stacked on each other are not. */
/* The circles are obstacles too — a name printed across a node reads as
that node's name. Every label may sit on its OWN circle, which is how
the focused node carries its name inside itself. */
const placed = nodes.map(n => ({ nid: n.id, b: [n.x - n.r, n.y - n.r, n.x + n.r, n.y + n.r] }));
/* Where a label may go, best spot first: a name prefers to sit under its
node but will take any side; a relation prefers the outside of its
edge but will take the other. Only when every spot is taken is the
label dropped. */
const spots = (L, w) => L.inside ? [[L.x, L.y]]
: L.edge ? [[L.edge[0] + L.edge[2] * 13, L.edge[1] + L.edge[3] * 13 + 4],
[L.edge[0] - L.edge[2] * 13, L.edge[1] - L.edge[3] * 13 + 4],
[L.edge[0] + L.edge[2] * 26, L.edge[1] + L.edge[3] * 26 + 4],
[L.edge[0] - L.edge[2] * 26, L.edge[1] - L.edge[3] * 26 + 4]]
: [[L.x, L.y + L.r + 17], [L.x, L.y - L.r - 8],
[L.x + L.r + w + 6, L.y + 5], [L.x - L.r - w - 6, L.y + 5]];
for (const L of labels.sort((x, y) => x.pri - y.pri)) {
ctx.font = L.font;
const w = ctx.measureText(L.text).width / 2 + 2;
for (const [sx, sy] of spots(L, w)) {
const box = [sx - w, sy - 12, sx + w, sy + 3];
let clash = false;
for (const o of placed) {
if (o.nid && o.nid === L.nid) continue;
const b = o.b;
if (box[0] < b[2] && box[2] > b[0] && box[1] < b[3] && box[3] > b[1]) { clash = true; break; }
}
if (clash) continue;
placed.push({ nid: null, b: box });
ctx.globalAlpha = L.alpha;
if (L.inside) { ctx.textAlign = 'center'; ctx.fillStyle = L.fill; ctx.fillText(L.text, sx, sy); }
else halo(L.text, sx, sy, L.font, L.fill);
break;
}
}
ctx.restore();
ctx.globalAlpha = 1;
}
const clip = (s, n) => s.length > n ? s.slice(0, n - 1) + '…' : s;
/* Labels sit on top of edges; a surface-coloured outline keeps them
readable wherever the layout puts them. */
function halo(text, x, y, font, fill) {
ctx.textAlign = 'center';
ctx.font = font;
ctx.lineWidth = 3.5;
ctx.lineJoin = 'round';
ctx.strokeStyle = colors.well;
ctx.strokeText(text, x, y);
ctx.fillStyle = fill;
ctx.fillText(text, x, y);
}
function loop() {
/* Only burn frames while the graph is actually on screen. */
if (PAGE === 'memory' && MVIEW === 'graph') { tick(); draw(); }
raf = requestAnimationFrame(loop);
}
function resize() {
if (!cv) return;
dpr = window.devicePixelRatio || 1;
W = cv.clientWidth; H = cv.clientHeight;
cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
}
function toWorld(e) {
const r = cv.getBoundingClientRect();
return { x: (e.clientX - r.left - W / 2 - tx) / scale, y: (e.clientY - r.top - H / 2 - ty) / scale };
}
function hit(p) {
for (let i = nodes.length - 1; i >= 0; i--) {
const n = nodes[i];
if (Math.hypot(n.x - p.x, n.y - p.y) <= n.r + 4) return n;
}
return null;
}
function fit() {
if (!nodes.length) { scale = 1; tx = ty = 0; return; }
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (const n of nodes) { x0 = Math.min(x0, n.x - n.r - 40); y0 = Math.min(y0, n.y - n.r - 30);
x1 = Math.max(x1, n.x + n.r + 40); y1 = Math.max(y1, n.y + n.r + 30); }
/* Keep the graph clear of the floating inspector and the toolbar. */
const padR = $('ginspect').hidden ? 24 : 312;
const padT = 64, padB = 60, padL = 24;
const availW = Math.max(160, W - padL - padR), availH = Math.max(160, H - padT - padB);
/* 2.2, not 1.4: a memory with a few dozen entities used to sit as a
small cluster marooned in a large canvas. */
scale = Math.max(0.25, Math.min(2.2, Math.min(availW / (x1 - x0), availH / (y1 - y0))));
tx = (padL + availW / 2) - W / 2 - ((x0 + x1) / 2) * scale;
ty = (padT + availH / 2) - H / 2 - ((y0 + y1) / 2) * scale;
}
function inspect() {
const box = $('ginspect');
const n = focus && byId.get(focus);
if (!n) { box.hidden = true; return; }
box.hidden = false; box.textContent = '';
const head = el('div'); head.style.cssText = 'display:flex;align-items:center;gap:11px';
const av = el('span', null, n.id.charAt(0).toUpperCase());
av.style.cssText = 'display:flex;align-items:center;justify-content:center;width:34px;height:34px;flex-shrink:0;'
+ 'border-radius:17px;color:#fff;font-size:14px;font-weight:600;background:' + (colors[n.kind] || colors.thing);
head.appendChild(av);
const ht = el('div'); ht.style.cssText = 'display:flex;flex-direction:column;gap:2px;flex:1;min-width:0';
const nm = el('span', null, n.id);
nm.style.cssText = 'font-size:15.5px;font-weight:600;color:var(--ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap';
ht.appendChild(nm);
const kindWord = { person: 'Person', org: 'Company or place', project: 'Project', thing: 'Thing', note: 'Note' }[n.kind] || 'Thing';
ht.appendChild(el('span', 'meta', kindWord + ' · ' + n.count + (n.count === 1 ? ' memory' : ' memories')
+ ' · ' + links.filter(l => l.a === n.id || l.b === n.id).length + ' links'));
head.appendChild(ht);
box.appendChild(head);
const list = el('div'); list.style.cssText = 'display:flex;flex-direction:column;border-top:1px solid var(--hair)';
const mine = memGrains().filter(g => (g.fields || {}).subject === n.id).slice(0, 3);
for (const g of mine) {
const r = el('div', null, predicate(g));
r.style.cssText = 'font-size:13.5px;color:var(--ink);padding:9px 0;border-bottom:1px solid var(--hair);cursor:pointer';
r.onclick = () => openPanel(g.hash);
list.appendChild(r);
}
if (!mine.length) list.appendChild(el('span', 'meta', 'Mentioned by other memories.')).style.padding = '9px 0';
box.appendChild(list);
const acts = el('div'); acts.style.cssText = 'display:flex;align-items:center;gap:8px';
const all = el('button', 'btn sm', 'See all ' + (n.count || links.filter(l => l.a === n.id || l.b === n.id).length));
all.style.flex = '1';
all.onclick = () => { ENTITY = n.id; MVIEW = 'list'; render(); };
const ex = el('button', 'btn ghost sm', depth === 1 ? 'Expand' : 'Collapse');
ex.onclick = () => setDepth(depth === 1 ? 2 : 1);
acts.appendChild(all); acts.appendChild(ex);
box.appendChild(acts);
}
function legend() {
const host = $('glegend'); host.textContent = '';
/* Neutral words: this legend labels whatever the file happens to hold.
"Things they like" read as a personal-assistant memory and misnamed
every invoice and process in a business one. */
const items = [['person', 'People'], ['org', 'Companies & places'],
['project', 'Projects & processes'], ['thing', 'Everything else'],
['note', 'Things it noticed']];
const present = new Set(nodes.map(n => n.kind));
for (const [k, label] of items) {
if (!present.has(k)) continue;
const s = el('span');
const d = el('span'); d.style.cssText = 'width:8px;height:8px;border-radius:4px;background:' + (colors[k] || colors.thing);
s.appendChild(d); s.appendChild(el('span', null, label));
host.appendChild(s);
}
host.hidden = !host.childElementCount;
}
function ticks() {
const host = $('gticks'); host.textContent = '';
// LOG is the whole file's op-log (capped to the most recent 400) —
// scoped to one namespace, only the ops this page can actually resolve
// (via memByHash()) belong on its own timeline; otherwise the tick
// labels could span a wider window than what the cut slider is
// actually slicing through memRows()'s own op_seq range.
const scoped = MEM_NS && MEM_NS !== '*';
let ops = LOG.slice().sort((a, b) => (a.op_seq || 0) - (b.op_seq || 0));
if (scoped) ops = ops.filter(o => !!memByHash()[o.hash]);
if (!ops.length) return;
const first = hlcMs(ops[0].hlc), last = hlcMs(ops[ops.length - 1].hlc);
/* Everything from one session? Then dates all read the same — show clocks. */
const sameDay = (last - first) < 36 * 3600 * 1000;
const fmt = ms => sameDay ? clock(ms)
: new Date(ms).toLocaleDateString(undefined, { day: 'numeric', month: 'short' });
for (let i = 0; i < 4; i++) host.appendChild(el('span', null, fmt(first + (last - first) * (i / 4))));
const now = el('span', null, cut >= 1 ? 'now' : fmt(first + (last - first) * cut));
now.style.cssText = 'color:var(--accent);font-weight:600';
host.appendChild(now);
}
function setDepth(d) {
depth = d;
$('gdepth').querySelectorAll('button').forEach(b => b.classList.toggle('on', +b.dataset.d === d));
computeNear(); inspect();
}
return {
recolor,
wire() {
cv = $('gcanvas'); ctx = cv.getContext('2d'); recolor();
window.addEventListener('resize', () => { resize(); fit(); });
cv.addEventListener('mousedown', e => {
const p = toWorld(e); const n = hit(p); moved = false;
if (n) { drag = { id: n.id, dx: n.x - p.x, dy: n.y - p.y }; }
else { panning = { x: e.clientX - tx, y: e.clientY - ty }; cv.classList.add('grabbing'); }
});
window.addEventListener('mousemove', e => {
if (drag) { const p = toWorld(e); const n = byId.get(drag.id);
if (n) { n.x = p.x + drag.dx; n.y = p.y + drag.dy; alpha = Math.max(alpha, 0.25); } moved = true; return; }
if (panning) { tx = e.clientX - panning.x; ty = e.clientY - panning.y; moved = true; return; }
if (!cv) return;
const r = cv.getBoundingClientRect();
if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) { hover = null; return; }
const n = hit(toWorld(e));
hover = n ? n.id : null;
cv.style.cursor = n ? 'pointer' : 'grab';
});
window.addEventListener('mouseup', e => {
if (drag && !moved) { focus = drag.id; computeNear(); inspect(); alpha = Math.max(alpha, .4); }
drag = null; panning = null; cv.classList.remove('grabbing');
});
cv.addEventListener('wheel', e => {
e.preventDefault();
const f = e.deltaY < 0 ? 1.12 : 0.89;
scale = Math.max(0.2, Math.min(3, scale * f));
}, { passive: false });
cv.addEventListener('dblclick', () => fit());
$('gin').onclick = () => { scale = Math.min(3, scale * 1.2); };
$('gout').onclick = () => { scale = Math.max(0.2, scale / 1.2); };
$('gfit').onclick = () => fit();
$('gdepth').querySelectorAll('button').forEach(b => { b.onclick = () => setDepth(+b.dataset.d); });
$('gjump').addEventListener('input', () => {
const v = $('gjump').value.trim().toLowerCase();
if (!v) return;
const n = nodes.find(x => x.id.toLowerCase().includes(v));
if (n) { focus = n.id; computeNear(); inspect(); alpha = Math.max(alpha, .5); }
});
$('grange').addEventListener('input', () => {
cut = (+$('grange').value) / 100;
$('gnow').textContent = cut >= 1 ? 'now' : 'rewound';
$('gnow').classList.toggle('on', cut >= 1);
build(); ticks(); inspect(); legend();
});
},
mount() { resize(); build(); fit(); legend(); ticks(); inspect(); if (!raf) loop(); },
rebuild() { if (!cv || !cv.clientWidth) return; resize(); build(); legend(); ticks(); inspect(); if (!raf) loop(); },
};
})();
/* ══ workflows: plans as an editable graph ═══════════════════════════
A Workflow grain is nodes+edges+bindings — content-addressed and
immutable like every grain here, so "editing" one means authoring a
new one. SAVE always writes `ADD workflow`, never `SUPERSEDE workflow`:
the SUPERSEDE form has no surface syntax to carry a `name` forward
(areev-cal/src/executor.rs builds its fields map from scratch), so a
supersede would silently drop it. A plan whose edges carry a bounded
cycle (`max_cycles`) or whose nodes carry a retry count opens
view-only — `ADD workflow`'s `* N` populates `retries`, not
`max_cycles`, and has no way to re-emit either on a resave, so editing
one through the console would silently unbound its loop. */
function workflowGrains() { return wfRows().filter(g => g.type === 'workflow' && isCurrent(g)); }
function toolDefs() { return wfRows().filter(g => g.type === 'tool' && (g.fields || {}).kind === 'definition' && isCurrent(g)); }
function wfLabel(g) {
const f = g.fields || {};
if (f.name) return f.name;
if (Array.isArray(f.nodes) && f.nodes.length) return f.nodes.slice(0, 3).join(' → ') + (f.nodes.length > 3 ? ' …' : '');
return shortHash(g.hash);
}
function wfIsCalEditable(g) {
const f = g.fields || {};
const edges = Array.isArray(f.edges) ? f.edges : [];
if (edges.some(e => e.max_cycles != null)) return false;
if (f.retries && Object.keys(f.retries).length) return false;
return true;
}
function wfNodeExecutor(bindings, nodeId) {
const raw = bindings ? bindings[nodeId] : null;
if (!raw) return { kind: 'abstract', tool: null, hash: null };
const hash = String(raw).replace(/^sha256:/, '');
const target = wfByHash()[hash];
if (!target) return { kind: 'host', tool: null, hash };
if (target.type === 'workflow') return { kind: 'subgraph', tool: target, hash };
const ek = (target.fields || {}).executor_kind;
return { kind: ek === 'client' ? 'client' : 'host', tool: target, hash };
}
const WF_KIND_LABEL = { host: 'Host tool', client: 'Human approval', abstract: 'Abstract (LLM step)', subgraph: 'Subgraph (another plan)' };
/* The second line on a node's card — what actually runs, not just what
kind it is, so reading the graph tells you what each step does without
opening the inspector for every one. */
function wfNodeSubtitle(ex) {
if (ex.kind === 'abstract') return 'Abstract (LLM step)';
const toolName = ex.tool ? ((ex.tool.fields || {}).tool_name || shortHash(ex.hash)) : (ex.hash ? shortHash(ex.hash) : '?');
const label = ex.kind === 'client' ? 'Human approval' : ex.kind === 'subgraph' ? 'Subgraph' : 'Host tool';
return label + ' · ' + toolName;
}
const calEsc = s => String(s == null ? '' : s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
let WF_SEL = null, WF_DRAFT = null, WF_LOCKED = false, WF_PICK = null;
/* null = the bound session default (read straight off the global BROWSE/
BYHASH, already loaded at boot — no extra fetch). Any other value means
this page fetched and cached that namespace's rows separately (see
browseForNamespace); switching pages back to the default is instant and
never disturbs BROWSE, which the rail/entities/graph still depend on. */
let WF_NS = null, WF_ROWS = null, WF_BYHASH_NS = null;
/* Which run the canvas is tinted by. null = whichever ran most recently;
'' = the user turned the overlay off and wants structure only. */
let WF_RUN = null;
/* The triggers that start the open plan, and the run overlay, resolved once
per render rather than per frame — draw() runs on every mouse move. */
let WF_TRG = [], WF_STEPS = null, WF_RUN_ACTIVE = null;
/* Which run the canvas is tinted by, and what each step did in it.
`WF_RUN === ''` is the user asking for structure only; `null` means "the
most recent", which is what someone opening a plan cold wants to see. */
function wfSyncRun() {
WF_STEPS = null; WF_RUN_ACTIVE = null;
if (!WF_SEL || !RUNIDX || WF_RUN === '') return;
const runs = RUNIDX.byPlan.get(bareHash(WF_SEL)) || [];
if (!runs.length) return;
const pick = WF_RUN ? runs.find(r => r.run_id === WF_RUN) : runs[0];
if (!pick) return;
WF_RUN_ACTIVE = pick;
WF_STEPS = runStepStates(pick.run_id, pick.outcome);
}
function wfTriggerClicked(hash) { WF_PICK = { kind: 'trigger', hash }; renderInspect(); }
const wfRows = () => WF_ROWS || BROWSE;
const wfByHash = () => WF_BYHASH_NS || BYHASH;
async function wfSetNamespace(ns) {
WF_NS = (!ns || ns === boundNamespace()) ? null : ns;
if (WF_NS) {
WF_ROWS = await browseForNamespace(WF_NS);
WF_BYHASH_NS = {};
for (const g of WF_ROWS) WF_BYHASH_NS[g.hash] = g;
} else {
WF_ROWS = null; WF_BYHASH_NS = null;
}
// A namespace switch closes whatever was open — its hash may not even exist
// here. render() rather than renderWorkflows(): the Tools page shares this
// picker, and it must not re-render the workflow page it isn't on.
WF_SEL = null; WF_DRAFT = null; WF_PICK = null; WF_RUN = null;
render();
}
function wfOpen(hash) {
const g = wfByHash()[hash];
if (!g) { toast('No workflow found at ' + shortHash(hash)); return; }
const f = g.fields || {};
WF_SEL = hash;
// A saved workflow always writes to this console's bound namespace (CAL's
// `ADD workflow` has no `SET namespace = ...` clause to target another
// one) — so a plan opened while browsing a different namespace is
// view-only, same as a plan CAL genuinely cannot re-author.
WF_LOCKED = !wfIsCalEditable(g) || !!WF_NS;
WF_DRAFT = {
name: f.name || '',
nodes: Array.isArray(f.nodes) ? f.nodes.slice() : [],
edges: (Array.isArray(f.edges) ? f.edges : []).map(e => ({
src: e.src, dst: e.dst, cond: e.cond || null,
max_cycles: e.max_cycles != null ? e.max_cycles : null,
})),
bindings: Object.assign({}, f.bindings || {}),
};
WF_PICK = null;
WFGraph.resetOverrides();
renderWorkflows();
}
function wfNew() {
if (WF_NS) { toast('Switch back to "' + boundNamespace() + '" to create a plan — a save always writes there'); return; }
WF_SEL = null; WF_LOCKED = false;
WF_DRAFT = { name: '', nodes: ['start'], edges: [], bindings: {} };
WF_PICK = { kind: 'node', id: 'start' };
WFGraph.resetOverrides();
renderWorkflows();
}
function wfClose() {
WF_SEL = null; WF_DRAFT = null; WF_PICK = null;
renderWorkflows();
}
function wfNodeExists(id) { return WF_DRAFT.nodes.includes(id); }
function wfAddNode() {
if (WF_LOCKED || !WF_DRAFT) return;
let n = 1, id = 'step_1';
while (wfNodeExists(id)) { n++; id = 'step_' + n; }
WF_DRAFT.nodes.push(id);
WF_PICK = { kind: 'node', id };
WFGraph.rebuild(); WFGraph.draw(); renderInspect();
}
function wfRenameNode(oldId, nextRaw) {
const next = String(nextRaw || '').trim();
if (!WF_DRAFT || !next || next === oldId) return false;
if (wfNodeExists(next)) { toast('A step named "' + next + '" already exists'); return false; }
WF_DRAFT.nodes = WF_DRAFT.nodes.map(n => n === oldId ? next : n);
WF_DRAFT.edges.forEach(e => { if (e.src === oldId) e.src = next; if (e.dst === oldId) e.dst = next; });
if (WF_DRAFT.bindings[oldId] != null) { WF_DRAFT.bindings[next] = WF_DRAFT.bindings[oldId]; delete WF_DRAFT.bindings[oldId]; }
if (WF_PICK && WF_PICK.kind === 'node' && WF_PICK.id === oldId) WF_PICK.id = next;
WFGraph.renameOverride(oldId, next);
WFGraph.rebuild(); WFGraph.draw();
return true;
}
function wfDeleteNode(id) {
if (WF_LOCKED || !WF_DRAFT || WF_DRAFT.nodes.length <= 1) return;
WF_DRAFT.nodes = WF_DRAFT.nodes.filter(n => n !== id);
WF_DRAFT.edges = WF_DRAFT.edges.filter(e => e.src !== id && e.dst !== id);
delete WF_DRAFT.bindings[id];
WF_PICK = null;
WFGraph.rebuild(); WFGraph.draw(); renderInspect();
}
function wfBindNode(id, hashOrEmpty) {
if (!WF_DRAFT) return;
if (hashOrEmpty) WF_DRAFT.bindings[id] = hashOrEmpty; else delete WF_DRAFT.bindings[id];
WFGraph.draw(); renderInspect();
}
/* Connecting two steps is a drag gesture (from a node's connector dot to
another node) rather than a click-click mode toggle — see WFGraph.wire's
handle drag handling. These three are the plain selection path. */
/* Is there already a path start -> ... -> end through these edges? Used to
refuse a new edge that would close a cycle: every edge drawn in this
editor is hardcoded `max_cycles: null` (unbounded), and `ADD workflow`'s
`* N` syntax populates `retries`, not `max_cycles` — there is no CAL this
console can author that would re-emit a bound on save. A plan opens
view-only the moment any of its edges already carries one
(`wfIsCalEditable`), so every edge reachable from here is unbounded —
nothing to filter on, just walk them. An unbounded cycle a user can't
see coming here would only surface later, as `RUN-E002` at run-load time. */
function wfCanReach(edges, start, end) {
const seen = new Set([start]), stack = [start];
while (stack.length) {
const cur = stack.pop();
if (cur === end) return true;
for (const e of edges) {
if (e.src === cur && !seen.has(e.dst)) { seen.add(e.dst); stack.push(e.dst); }
}
}
return false;
}
function wfConnectNodes(fromId, toId) {
if (!WF_DRAFT || WF_LOCKED || fromId === toId) return;
const dup = WF_DRAFT.edges.some(e => e.src === fromId && e.dst === toId);
if (dup) { toast('That edge already exists'); return; }
if (wfCanReach(WF_DRAFT.edges, toId, fromId)) {
toast('That would create a cycle this console has no way to bound — it would fail at run time. '
+ 'Undo the loop, or author a bounded repeat outside the console.');
return;
}
WF_DRAFT.edges.push({ src: fromId, dst: toId, cond: null, max_cycles: null });
WF_PICK = { kind: 'edge', idx: WF_DRAFT.edges.length - 1 };
WFGraph.rebuild(); WFGraph.draw(); renderInspect();
}
function wfNodeClicked(id) {
WF_PICK = { kind: 'node', id };
WFGraph.draw(); renderInspect();
}
function wfEdgeClicked(idx) {
WF_PICK = { kind: 'edge', idx };
WFGraph.draw(); renderInspect();
}
function wfCanvasBgClicked() {
WF_PICK = null;
WFGraph.draw(); renderInspect();
}
function wfSetEdgeCond(idx, condRaw) {
const e = WF_DRAFT.edges[idx]; if (!e || e.max_cycles != null) return;
const cond = String(condRaw || '').trim();
e.cond = cond || null;
WFGraph.draw();
}
function wfDeleteEdge(idx) {
const e = WF_DRAFT.edges[idx]; if (!e || WF_LOCKED || e.max_cycles != null) return;
WF_DRAFT.edges.splice(idx, 1);
WF_PICK = null;
WFGraph.rebuild(); WFGraph.draw(); renderInspect();
}
function renderInspect() {
const box = $('wfinspect');
if (!WF_DRAFT || !WF_PICK) { box.hidden = true; WFGraph.setSelection(null); WFGraph.draw(); return; }
if (WF_PICK.kind === 'node' && !WF_DRAFT.nodes.includes(WF_PICK.id)) { WF_PICK = null; box.hidden = true; return; }
if (WF_PICK.kind === 'edge' && !WF_DRAFT.edges[WF_PICK.idx]) { WF_PICK = null; box.hidden = true; return; }
box.hidden = false; box.textContent = '';
WFGraph.setSelection(WF_PICK);
if (WF_PICK.kind === 'trigger') {
const g = triggersFor(WF_SEL).find(t => t.hash === WF_PICK.hash);
if (!g) { WF_PICK = null; box.hidden = true; WFGraph.setSelection(null); WFGraph.draw(); return; }
trgInspect(box, g);
WFGraph.draw();
return;
}
if (WF_PICK.kind === 'node') {
const id = WF_PICK.id;
const ex = wfNodeExecutor(WF_DRAFT.bindings, id);
const badge = el('span', 'wf-badge', WF_KIND_LABEL[ex.kind]);
badge.style.cssText = 'background:var(--well);color:' + WFGraph.kindColor(ex.kind);
box.appendChild(badge);
/* What this step did in the run the canvas is tinted by. Only while an
overlay is on — with no run selected there is no answer, and "not
reached" without a run to be un-reached in reads as broken. */
if (WF_STEPS && WF_RUN_ACTIVE) {
const st = WF_STEPS.get(id);
const d = el('div', 'wf-ro');
d.appendChild(el('span', 'k', 'In ' + WF_RUN_ACTIVE.run_id));
const v = el('span', 'v', st ? STEP_WORD[st.state] : 'not reached');
v.style.color = 'var(--' + (st ? STEP_TONE[st.state] : 'faint') + ')';
d.appendChild(v);
box.appendChild(d);
if (st) {
const open = el('button', 'btn ghost sm', 'See the call ▸');
open.onclick = () => { TOOLTAB = 'executions'; TOOL_SEL = st.grain.hash; go('tools'); };
box.appendChild(open);
}
}
const nameField = el('div', 'wf-field');
nameField.appendChild(el('span', 'tiny', 'Step name'));
const nameInput = document.createElement('input'); nameInput.type = 'text'; nameInput.value = id;
nameInput.disabled = WF_LOCKED;
nameInput.addEventListener('change', () => { if (!wfRenameNode(id, nameInput.value)) { nameInput.value = id; } else { renderInspect(); } });
nameField.appendChild(nameInput);
box.appendChild(nameField);
const bindField = el('div', 'wf-field');
bindField.appendChild(el('span', 'tiny', 'Runs as'));
const sel = document.createElement('select'); sel.disabled = WF_LOCKED;
const opt0 = document.createElement('option'); opt0.value = ''; opt0.textContent = '— unbound (abstract LLM step) —';
sel.appendChild(opt0);
/* The option list below is built from Tool definitions only — there is
no way to author a subgraph binding through this select. Without a
matching <option>, a node actually bound to a Workflow grain (its
hash never equals any tool's) fell through to "unbound" here even
though the badge above correctly says "Subgraph". Represent the
current binding so the panel doesn't contradict itself; disabled
because re-selecting it wouldn't rebind to anything new. */
if (ex.kind === 'subgraph') {
const optSub = document.createElement('option');
optSub.value = ex.hash; optSub.disabled = true; optSub.selected = true;
optSub.textContent = 'Subgraph — ' + (ex.tool ? wfLabel(ex.tool) : shortHash(ex.hash));
sel.appendChild(optSub);
}
for (const t of toolDefs()) {
const tf = t.fields || {};
const opt = document.createElement('option');
opt.value = t.hash;
opt.textContent = (tf.tool_name || shortHash(t.hash)) + (tf.executor_kind === 'client' ? ' (human approval)' : '');
if (ex.hash === t.hash) opt.selected = true;
sel.appendChild(opt);
}
sel.addEventListener('change', () => wfBindNode(id, sel.value || null));
bindField.appendChild(styledSelect(sel));
if (ex.tool && (ex.tool.fields || {}).tool_description) bindField.appendChild(el('span', 'tiny', ex.tool.fields.tool_description));
if (ex.kind === 'subgraph') bindField.appendChild(el('span', 'tiny', 'Bound to another plan — runs as a child run.'));
box.appendChild(bindField);
const orig = WF_SEL && wfByHash()[WF_SEL] ? (wfByHash()[WF_SEL].fields || {}).retries : null;
if (orig && orig[id] != null) box.appendChild(el('span', 'tiny', 'Retries on failure: ' + orig[id] + ' (read-only here)'));
const del = el('button', 'btn ghost sm', 'Delete step');
del.disabled = WF_LOCKED || WF_DRAFT.nodes.length <= 1;
del.onclick = () => wfDeleteNode(id);
box.appendChild(del);
} else {
const idx = WF_PICK.idx;
const e = WF_DRAFT.edges[idx];
const hd = el('span', null, e.src + ' → ' + e.dst);
hd.style.cssText = 'font-size:15px;font-weight:600;color:var(--ink)';
box.appendChild(hd);
if (e.max_cycles != null) {
const b = el('span', 'wf-badge', '↻ repeats up to ' + e.max_cycles + '×');
b.style.cssText = 'background:var(--warn-soft);color:var(--warn)';
box.appendChild(b);
box.appendChild(el('span', 'tiny', 'A bounded-cycle edge — not editable through the console yet.'));
} else {
const condField = el('div', 'wf-field');
condField.appendChild(el('span', 'tiny', 'Only when (leave blank for always)'));
const inp = document.createElement('input'); inp.type = 'text'; inp.value = e.cond || '';
inp.placeholder = 'e.g. approved == true'; inp.disabled = WF_LOCKED;
inp.addEventListener('change', () => wfSetEdgeCond(idx, inp.value));
condField.appendChild(inp);
box.appendChild(condField);
const del = el('button', 'btn ghost sm', 'Delete edge');
del.disabled = WF_LOCKED;
del.onclick = () => wfDeleteEdge(idx);
box.appendChild(del);
}
}
WFGraph.draw();
}
/** "3 steps · 2 edges" — what the subtitle slot shows now that it is not an
invitation to set something inert. */
function wfShape(d) {
const n = (d.nodes || []).length, e = (d.edges || []).length;
return n + (n === 1 ? ' step' : ' steps') + ' · ' + e + (e === 1 ? ' edge' : ' edges');
}
function wfCard(g) {
const f = g.fields || {};
const nodesN = Array.isArray(f.nodes) ? f.nodes.length : 0;
const edgesN = Array.isArray(f.edges) ? f.edges.length : 0;
const b = el('button', 'starter');
b.appendChild(el('b', '', wfLabel(g)));
const bits = [nodesN + (nodesN === 1 ? ' step' : ' steps'), edgesN + (edgesN === 1 ? ' edge' : ' edges')];
if (!wfIsCalEditable(g)) bits.push('view-only');
if (WF_NS === '*' && f.namespace) bits.push(f.namespace); // "All namespaces" — say which one each card is
bits.push(relTime(createdMs(f)));
b.appendChild(el('span', 'meta', bits.join(' · ')));
/* What starts it, and how it last went — the two questions the flat trigger
list and the Runs page used to answer separately. Without these the card
is a shape with no cause and no history. */
const trg = triggersFor(g.hash);
const runs = (RUNIDX && RUNIDX.byPlan.get(g.hash)) || [];
if (trg.length || runs.length) {
const foot = el('span', 'meta');
foot.style.cssText = 'display:flex;align-items:center;gap:12px;flex-wrap:wrap';
if (trg.length) {
const live = trg.filter(t => (t.fields || {}).enabled !== false).length;
const t = el('span');
t.style.cssText = 'display:flex;align-items:center;gap:6px;color:var(--' + (live ? 'ok' : 'dim') + ')';
const ring = el('span');
ring.style.cssText = 'width:7px;height:7px;border-radius:4px;border:1.6px solid currentColor';
t.appendChild(ring);
t.appendChild(el('span', null, trg.length === 1 ? trgWhen(trg[0].fields || {})
: trg.length + ' triggers'));
foot.appendChild(t);
}
if (runs.length) {
const r = runs[0];
const rr = el('span');
rr.style.cssText = 'display:flex;align-items:center;gap:6px;color:var(--' + outcomeTone(r.outcome) + ')';
const d = el('span');
d.style.cssText = 'width:7px;height:7px;border-radius:4px;background:currentColor';
rr.appendChild(d);
rr.appendChild(el('span', null, 'last run ' + r.outcome));
foot.appendChild(rr);
}
b.appendChild(foot);
}
b.onclick = () => wfOpen(g.hash);
return b;
}
/* One action slot, top right: "New workflow" on the list, "Save as new
plan" in the editor — never both, never scattered across the page. */
/* Why editing is off, in plain words — covers both reasons a plan can be
locked: CAL genuinely cannot re-author it (a bounded cycle / retry count),
or a save from here would land in the wrong namespace. */
/* Plain text — this ends up in a native `title` tooltip, which can't render
the <code> markup the old inline banner used. */
function wfLockReason() {
if (WF_NS) return 'Browsing "' + WF_NS + '" — switch back to "' + boundNamespace()
+ '" (this console\'s own namespace) to edit or save. A save always writes there.';
const g = WF_SEL && wfByHash()[WF_SEL];
if (g && !wfIsCalEditable(g)) return 'This plan has a bounded-cycle edge or a per-node retry count — '
+ 'CAL can visualize both but has no syntax yet to author them through ADD workflow. Open for viewing '
+ 'only; edit this one via the Rust or Python API.';
return '';
}
/* Which run the canvas is showing, and the switch to change it. In the header
rather than floating on the canvas: the tools sit top-left and the inspector
top-right, so a third float has nowhere to be at a narrow width. */
function wfRunBar() {
const host = $('wfRunHost'); host.textContent = '';
const show = !!WF_DRAFT && !!WF_SEL;
host.hidden = !show;
if (!show) return;
const bar = el('div', 'runbar');
if (!RUNIDX) { bar.appendChild(el('span', 'tally', 'checking runs…')); host.appendChild(bar); return; }
const runs = RUNIDX.byPlan.get(bareHash(WF_SEL)) || [];
if (!runs.length) {
const d = el('span', 'dot'); d.style.background = 'var(--ghost)';
bar.appendChild(d);
bar.appendChild(el('span', 'tally', 'Never run'));
host.appendChild(bar); return;
}
const active = WF_RUN_ACTIVE;
const dot = el('span', 'dot');
dot.style.background = 'var(--' + (active ? outcomeTone(active.outcome) : 'ghost') + ')';
bar.appendChild(dot);
if (active && WF_STEPS) {
const tally = { done: 0, waiting: 0, failed: 0, stopped: 0 };
for (const v of WF_STEPS.values()) tally[v.state]++;
const total = (WF_DRAFT.nodes || []).length;
const parts = [tally.done + ' of ' + total + ' done'];
if (tally.waiting) parts.push(tally.waiting + ' waiting');
if (tally.failed) parts.push(tally.failed + ' failed');
bar.tallyText = parts.join(' · ');
}
const sel = document.createElement('select');
sel.title = 'Tint the steps by what happened in a run';
const none = document.createElement('option');
none.value = '__none__'; none.textContent = 'Structure only';
sel.appendChild(none);
for (const r of runs) {
const o = document.createElement('option');
o.value = r.run_id; o.textContent = r.run_id + ' · ' + r.outcome;
if (active && active.run_id === r.run_id) o.selected = true;
sel.appendChild(o);
}
if (!active) none.selected = true;
bar.appendChild(styledSelect(sel));
if (bar.tallyText) bar.appendChild(el('span', 'tally', bar.tallyText));
sel.onchange = () => {
WF_RUN = sel.value === '__none__' ? '' : sel.value;
wfSyncRun(); renderWorkflowHeader(); WFGraph.refresh(); renderInspect();
};
const jump = el('button', 'go', 'Runs ▸');
jump.title = 'Open this run on the Runs page';
jump.onclick = () => go('runs');
bar.appendChild(jump);
host.appendChild(bar);
}
function renderWorkflowHeader() {
const editing = !!WF_DRAFT;
wfRunBar();
$('wfNsHost').hidden = editing;
$('wfNewBtn').hidden = editing;
$('wfNewBtn').disabled = !!WF_NS;
$('wfNewBtn').title = WF_NS ? 'Switch back to "' + boundNamespace() + '" to create a plan' : '';
$('wfSave').hidden = !editing;
const nsHost = $('wfNsHost'); nsHost.textContent = '';
nsHost.appendChild(nsCombo('wfNs', WF_NS || boundNamespace(), ns => wfSetNamespace(ns)));
if (!editing) {
renderCrumbHeader('wfCrumb', [{ label: 'Workflows' }],
'Plans <code>areev run</code> executes: nodes are steps, edges are the order they can happen in. '
+ 'Plans are content-addressed and immutable, like every memory here — saving a change writes a new '
+ 'plan; the old one stays recallable by its hash.');
return;
}
const fallbackName = (WF_SEL && wfByHash()[WF_SEL]) ? wfLabel(wfByHash()[WF_SEL]) : 'New workflow';
renderCrumbHeader('wfCrumb', [{ label: 'Workflows', onClick: wfClose }], null, {
editTitle: {
value: WF_DRAFT.name || '', placeholder: fallbackName, disabled: WF_LOCKED,
onCommit: v => { WF_DRAFT.name = v; renderWorkflowHeader(); },
},
// Read-only: a plan is its graph. The editable field here used to write
// `trigger`, which nothing ever read — so it invited someone to "set a
// trigger" and then quietly did nothing. Real triggers are their own grains
// that point at this plan, and they are drawn in the canvas's own lane.
editDesc: {
value: wfShape(WF_DRAFT), disabled: true,
},
lockHint: WF_LOCKED ? wfLockReason() : null,
});
const canSave = !WF_LOCKED && canWrite() && stmtSupported('ADD');
$('wfSave').disabled = !canSave;
$('wfSave').title = WF_LOCKED ? (WF_NS ? 'Browsing a different namespace — view only' : 'This plan is view-only in the console')
: !canWrite() ? READONLY_WHY
: !stmtSupported('ADD') ? 'This build has no ADD workflow support'
: 'Write a new plan grain with these steps';
}
/* ---------- Triggers ----------------------------------------------------
A trigger is a standing rule that starts a workflow. The binding points
trigger → plan and never the reverse — a plan is content-addressed, so one
that grew a list of triggers would change address every time a trigger was
added and orphan its own run history. That direction is why a trigger is
only fully legible NEXT TO the plan it starts, and why these render on the
canvas instead of on a page of their own: a flat list of four triggers
cannot show you that two of them start the same plan.
Read-only, and not by preference. CAL has no `ADD trigger`, and
`ADD workflow`'s `ON "..."` clause was removed in 1.3, so a console that
writes only through /api/cal has no way to author one. Firing is withheld
for the same reason `run.respond` refuses a shared token: it spends budgets
and executes effects, and the declaring principal IS the audit record. */
function triggerGrains() {
return wfRows().filter(g => g.type === 'trigger' && isCurrent(g));
}
const bareHash = h => String(h == null ? '' : h).replace(/^sha256:/, '');
/** The triggers that start one plan, newest first. */
function triggersFor(hash) {
if (!hash) return [];
const h = bareHash(hash);
return triggerGrains()
.filter(g => bareHash((g.fields || {}).workflow) === h)
.sort((a, b) => createdMs(b.fields) - createdMs(a.fields));
}
/** Seconds as something a person reads. */
function everyPhrase(n) {
n = Number(n);
if (!isFinite(n) || n <= 0) return null;
if (n % 86400 === 0) return 'every ' + (n / 86400) + 'd';
if (n % 3600 === 0) return 'every ' + (n / 3600) + 'h';
if (n % 60 === 0) return 'every ' + (n / 60) + 'm';
return 'every ' + n + 's';
}
/* A serialized CAL Condition tree, said out loud. `memory` and `composite`
triggers carry their whole rule in here, so rendering it as JSON would hide
the one thing the reader came for. Unknown shapes fall back to JSON rather
than guessing — a wrong sentence is worse than an honest blob. */
const PRED_CMP = { eq: '=', ne: '≠', lt: '<', lte: '≤', gt: '>', gte: '≥',
contains: 'contains', starts_with: 'starts with', ends_with: 'ends with', in: 'in' };
function predValueText(v) {
if (v == null) return '?';
if (typeof v !== 'object') return String(v);
if (v.kind === 'string') return '"' + v.value + '"';
if (Array.isArray(v.values)) return '[' + v.values.map(predValueText).join(', ') + ']';
if ('value' in v) return String(v.value);
return JSON.stringify(v);
}
function predicateText(p, depth) {
depth = depth || 0;
if (p == null) return '';
if (typeof p !== 'object') return String(p);
const k = String(p.kind || '');
if (k === 'and' || k === 'or') {
const t = predicateText(p.left, depth + 1) + ' ' + k.toUpperCase() + ' ' + predicateText(p.right, depth + 1);
return depth ? '(' + t + ')' : t;
}
if (k === 'not') return 'NOT ' + predicateText(p.inner || p.operand || p.left, depth + 1);
if (k === 'comparison' || p.field) {
return (p.field || '?') + ' ' + (PRED_CMP[p.comparator] || p.comparator || '=') + ' ' + predValueText(p.value);
}
return JSON.stringify(p);
}
/* What this trigger is actually waiting for, in one line. The kind alone is a
category ("memory"); this is the rule. */
function trgWhen(f) {
const kind = String(f.kind || 'interval');
if (kind === 'interval') return everyPhrase(f.interval_secs) || 'on an interval';
if (kind === 'polling') {
const who = (f.connector || 'a connector') + (f.scope ? ' ' + f.scope : '');
return 'poll ' + who + (everyPhrase(f.interval_secs) ? ' · ' + everyPhrase(f.interval_secs) : '');
}
if (kind === 'schedule') return f.cron ? 'cron ' + f.cron : 'on a schedule';
if (kind === 'once') return f.at_ms ? 'once · ' + dayLabel(Number(f.at_ms)) : 'once';
if (kind === 'memory') return f.predicate ? 'when ' + predicateText(f.predicate) : 'when memory changes';
if (kind === 'webhook') return 'on delivery' + (f.scope ? ' · ' + f.scope : '');
if (kind === 'manual') return 'when fired by hand';
if (kind === 'composite') return f.predicate ? 'when ' + predicateText(f.predicate) : 'when its members agree';
return kind;
}
/** The short line drawn under a trigger node on the canvas. */
function trgSubtitle(f) {
const bits = [String(f.kind || 'interval')];
if (f.enabled === false) bits.push('disabled');
return bits.join(' · ');
}
/* The inspector for a trigger node. Every row is read-only text — no inputs,
no toggles: an input this console cannot honour is a worse lie than an
absent one. The escape hatch is the exact CLI command, ready to copy. */
function trgInspect(box, g) {
const f = g.fields || {};
const live = f.enabled !== false;
const badge = el('span', 'wf-badge', 'Trigger · ' + String(f.kind || 'interval'));
badge.style.cssText = 'background:var(--well);color:var(--' + (live ? 'ok' : 'ghost') + ')';
box.appendChild(badge);
const row = (k, v, mono) => {
if (v == null || v === '') return;
const d = el('div', 'wf-ro');
d.appendChild(el('span', 'k', k));
d.appendChild(el('span', 'v' + (mono ? ' mono' : ''), String(v)));
box.appendChild(d);
};
row('Fires', trgWhen(f));
if (!live) row('State', 'Disabled in the declaration — it will not fire.');
row('Because', f.because);
row('Connector', f.connector);
row('Watches', f.scope);
if (Array.isArray(f.dedup_key) && f.dedup_key.length) row('Same item when', f.dedup_key.join(' + '), true);
if (f.correlate) row('Correlated on', f.correlate, true);
if (f.window_ms) row('Match window', everyPhrase(Number(f.window_ms) / 1000) || (f.window_ms + 'ms'));
if (f.members && Object.keys(f.members).length) {
row('Members', Object.keys(f.members).map(a => a + ' → ' + shortHash(bareHash(f.members[a]))).join('\n'), true);
}
if (f.concurrency) row('If one is still running', f.concurrency);
if (f.catchup) row('Missed firings', f.catchup);
row('Declared', relTime(createdMs(f)));
/* Whether it has actually fired is per-host state — a `trg:` row in the
meta table that deliberately does NOT replicate, so a dev memory restored
from prod cannot inherit prod's cursor. This console genuinely cannot
know it for another machine; say so rather than drawing an empty column
that reads as "never fired". */
const note = el('div', 'wf-ro');
note.appendChild(el('span', 'k', 'Has it fired?'));
const nv = el('span', 'v'); nv.style.fontSize = '12.5px'; nv.style.color = 'var(--dim)';
nv.textContent = 'Per-host state — it does not travel with the memory. Run '
+ '`areev trigger status` on the machine that evaluates it.';
note.appendChild(nv);
box.appendChild(note);
const copy = el('button', 'btn ghost sm', 'Copy `trigger show`');
copy.onclick = () => copyText('areev trigger show ' + g.hash, 'command');
box.appendChild(copy);
}
function renderWorkflows() {
const listHost = $('wfList');
listHost.hidden = !!WF_DRAFT;
WF_TRG = WF_SEL ? triggersFor(WF_SEL) : [];
wfSyncRun();
/* The list cards and the canvas overlay want the same run index. Fetch it
once and repaint whichever is on screen — never block first paint on it,
because a plan must be visible without the runtime answering. */
if (!RUNIDX && !RUNIDX_INFLIGHT) {
loadRuns().then(() => {
if (PAGE !== 'workflows') return;
if (WF_DRAFT && WF_SEL) { wfSyncRun(); renderWorkflowHeader(); WFGraph.refresh(); renderInspect(); }
else renderWorkflows();
});
}
if (!WF_DRAFT) {
const grains = workflowGrains();
const byLabel = new Map();
for (const g of grains) {
const k = wfLabel(g);
const cur = byLabel.get(k);
if (!cur || createdMs(g.fields) > createdMs(cur.fields)) byLabel.set(k, g);
}
const items = [...byLabel.values()].sort((a, b) => createdMs(b.fields) - createdMs(a.fields));
listHost.textContent = '';
if (!items.length) {
listHost.innerHTML = '<div class="empty">No workflows yet. A plan is what <code>areev run</code> executes — start one with "New workflow" above.</div>';
} else {
for (const g of items) listHost.appendChild(wfCard(g));
}
renderOrphanTriggers();
}
renderWorkflowHeader();
const wrap = $('wfEditorWrap');
wrap.hidden = !WF_DRAFT;
if (!WF_DRAFT) return;
$('wfAddNode').disabled = WF_LOCKED;
WFGraph.mount();
renderInspect();
}
/* A trigger whose plan is not among these rows still fires. It used to be
visible on the Triggers tab; with that tab gone, an unreferenced trigger
would simply disappear from the console, which is the one thing a standing
rule must never do. */
function renderOrphanTriggers() {
const host = $('wfOrphans');
if (!host) return;
const known = new Set(workflowGrains().map(g => g.hash));
const orphans = triggerGrains().filter(t => !known.has(bareHash((t.fields || {}).workflow)));
host.textContent = '';
host.hidden = !orphans.length;
if (!orphans.length) return;
const card = el('div', 'card');
card.style.cssText = 'padding:16px 18px;display:flex;flex-direction:column;gap:10px';
const hd = el('div');
hd.style.cssText = 'font-size:13.5px;font-weight:600;color:var(--ink)';
hd.textContent = orphans.length === 1 ? '1 trigger points somewhere else'
: orphans.length + ' triggers point somewhere else';
card.appendChild(hd);
card.appendChild(el('div', 'tiny', 'Their plan is not in ' + (WF_NS || boundNamespace())
+ ' — superseded, forgotten, or in another namespace. They still fire.'));
for (const t of orphans) {
const f = t.fields || {};
const row = el('div', 'tiny');
row.style.color = 'var(--text)';
row.textContent = trgWhen(f) + ' · ' + String(f.kind || '') + ' → plan ' + shortHash(bareHash(f.workflow));
card.appendChild(row);
}
host.appendChild(card);
}
/* A plain sentence describing what changed, so saving rarely means typing
a reason from scratch — it means glancing at one and hitting Save. */
function wfDiffSummary() {
const d = WF_DRAFT;
const name = d.name.trim() || 'this plan';
if (!WF_SEL) {
return 'Created "' + name + '" — ' + d.nodes.length + (d.nodes.length === 1 ? ' step' : ' steps')
+ (d.edges.length ? ', ' + d.edges.length + (d.edges.length === 1 ? ' edge' : ' edges') : '') + '.';
}
const orig = (wfByHash()[WF_SEL] || {}).fields || {};
const origNodes = new Set(orig.nodes || []), curNodes = new Set(d.nodes);
const addedNodes = d.nodes.filter(n => !origNodes.has(n));
const removedNodes = (orig.nodes || []).filter(n => !curNodes.has(n));
const key = e => e.src + ' → ' + e.dst;
const origEdges = new Map((orig.edges || []).map(e => [key(e), e]));
const curEdges = new Map(d.edges.map(e => [key(e), e]));
const addedEdges = [...curEdges.keys()].filter(k => !origEdges.has(k));
const removedEdges = [...origEdges.keys()].filter(k => !curEdges.has(k));
const changedConds = [...curEdges.keys()].filter(k => origEdges.has(k)
&& (origEdges.get(k).cond || null) !== (curEdges.get(k).cond || null));
const origB = orig.bindings || {}, curB = d.bindings || {};
const rebound = [...new Set([...Object.keys(origB), ...Object.keys(curB)])]
.filter(n => String(origB[n] || '').replace(/^sha256:/, '') !== String(curB[n] || '').replace(/^sha256:/, ''));
const bits = [];
if (addedNodes.length) bits.push('added ' + addedNodes.join(', '));
if (removedNodes.length) bits.push('removed ' + removedNodes.join(', '));
if (addedEdges.length) bits.push('connected ' + addedEdges.join('; '));
if (removedEdges.length) bits.push('disconnected ' + removedEdges.join('; '));
if (changedConds.length) bits.push('updated the condition on ' + changedConds.join('; '));
if (rebound.length) bits.push('rebound ' + rebound.join(', '));
if ((orig.name || '') !== d.name.trim()) bits.push('renamed the plan');
if (!bits.length) return 'Resaved "' + name + '" with no structural change.';
const s = bits.join('; ') + '.';
return (s.charAt(0).toUpperCase() + s.slice(1)).slice(0, 240);
}
function wfArmSave() {
if (!WF_DRAFT || WF_LOCKED) return;
if (!WF_DRAFT.name.trim()) {
toast('Name the plan before saving');
const titleInput = document.querySelector('#wfCrumb input.ctitle');
if (titleInput) titleInput.focus();
return;
}
if (!WF_DRAFT.nodes.length) { toast('Add at least one step'); return; }
const reason = wfDiffSummary();
/* A brand-new plan has nothing to justify yet — write it straight away
with an auto-generated reason. An edit to something that already
existed still gets a beat to look before it writes: the reason IS
that change's audit trail, just pre-filled instead of blank. */
if (!WF_SEL) { wfSave(reason); return; }
const box = $('wfReasonBox'); box.textContent = '';
const composer = el('div', 'reason');
composer.appendChild(el('span', 'meta', 'Why this change? Filled in from what you edited — adjust it if you like.'));
const line = el('div', 'line');
const why = document.createElement('input'); why.type = 'text'; why.value = reason;
const conf = el('button', 'btn sm', 'Save'); const cancel = el('button', 'btn ghost sm', 'Cancel');
line.appendChild(why); line.appendChild(conf); line.appendChild(cancel);
composer.appendChild(line);
box.appendChild(composer);
why.focus(); why.select();
cancel.onclick = () => { box.textContent = ''; };
conf.onclick = async () => {
if (!why.value.trim()) { toast('A reason is required — it goes in the audit trail'); why.focus(); return; }
conf.disabled = true; cancel.disabled = true;
await wfSave(why.value.trim());
conf.disabled = false; cancel.disabled = false;
};
}
async function wfSave(reason) {
const btn = $('wfSave'), prevLabel = btn.textContent;
btn.disabled = true; btn.textContent = 'Saving…';
const d = WF_DRAFT;
const seen = new Set();
let body = '';
for (const e of d.edges) {
body += '"' + calEsc(e.src) + '" -> "' + calEsc(e.dst) + '"';
if (e.cond) body += ' WHEN "' + calEsc(e.cond) + '"';
body += ' ';
seen.add(e.src); seen.add(e.dst);
}
for (const n of d.nodes) if (!seen.has(n)) body += '"' + calEsc(n) + '" ';
let stmt = 'ADD workflow "' + calEsc(d.name.trim()) + '"';
stmt += ' ' + body.trim();
/* Every other interpolated value here (node names, WHEN, trigger, reason,
the BIND key itself) goes through calEsc() into a quoted string —
`hash` is the one value emitted bare. A plan opened here can have been
authored outside this UI (Rust/Python/Node API, or a synced bundle),
and `wfOpen` copies its `bindings` map verbatim into the draft, so a
crafted binding value could otherwise append arbitrary CAL clauses
(rebinding other steps, overriding REASON/ON) to this statement the
moment someone re-saves that plan. HASH_RE (a full hex sha256, the
only shape a real binding ever has) is the same check the rest of the
console already uses to recognize a content address. */
const skippedBindings = [];
for (const [node, hash] of Object.entries(d.bindings)) {
if (!hash) continue;
if (!HASH_RE.test(String(hash))) { skippedBindings.push(node); continue; }
stmt += ' BIND "' + calEsc(node) + '" = sha256:' + String(hash).replace(/^sha256:/, '');
}
stmt += ' REASON "' + calEsc(reason) + '"';
const r = await cal(stmt);
btn.textContent = prevLabel;
if (!r.ok || !r.result || !r.result.hash) { toast('Could not save: ' + errText(r)); btn.disabled = false; return; }
toast('Saved as a new plan · ' + shortHash(r.result.hash)
+ (skippedBindings.length ? ' — dropped a malformed binding on ' + skippedBindings.join(', ') : ''));
$('wfReasonBox').textContent = '';
await loadBrowse();
wfOpen(r.result.hash);
}
/* ── the canvas: a deterministic layered layout, not a physics sim — a
plan reads as "what happens after what", which a left-to-right rank
order shows and a force-directed blob does not. Forward edges (no
`max_cycles`) decide rank; a bounded-cycle back-edge draws as a dashed
arc instead of feeding the ranking, or every node in its cycle would
collapse to the same rank. */
const WFGraph = (() => {
let cv, ctx, W = 0, H = 0, dpr = 1;
let nodes = [], byId = new Map(), edgesGeo = [];
/* Triggers live in their OWN arrays, never in `nodes`. That is not tidiness:
`nodes` is the draft the Save button serializes, and a plan grain has no
field for a trigger (the binding points the other way). Keeping them
structurally separate makes it impossible for the lane to be saved. */
let trgNodes = [], trgEdges = [];
let scale = 1, tx = 0, ty = 0;
let drag = null, panning = null, moved = false, hoverId = null, trgDown = null;
let connectFrom = null, connectPt = null, connectTarget = null; // live drag-to-connect
let colors = {};
let posOverride = {};
let sel = null;
function recolor() {
colors = { host: cssVar('--accent'), client: cssVar('--warn'), abstract: cssVar('--cat-project'),
subgraph: cssVar('--hash'), line: cssVar('--line2'), ink: cssVar('--ink'), dim: cssVar('--dim'),
faint: cssVar('--faint'), surface: cssVar('--surface'), well: cssVar('--well'),
/* a trigger is armed, not a step — green reads as "live", and it is the
one hue the four node kinds do not already use */
trg: cssVar('--ok'), ok: cssVar('--ok'), warn: cssVar('--warn'),
danger: cssVar('--danger'), ghost: cssVar('--ghost') };
}
const clip = (s, n) => s.length > n ? s.slice(0, n - 1) + '…' : s;
const COL_W = 240, ROW_H = 96;
const HANDLE_R = 7, HANDLE_HIT = 11;
const TRG_W = 196, TRG_H = 52, TRG_GAP = 78, TRG_ROW = 76;
function layout() {
const draft = WF_DRAFT;
const ids = draft ? draft.nodes.slice() : [];
const forward = draft ? draft.edges.filter(e => e.max_cycles == null) : [];
const adj = new Map(ids.map(n => [n, []]));
const indeg = new Map(ids.map(n => [n, 0]));
for (const e of forward) {
if (!adj.has(e.src) || !adj.has(e.dst)) continue;
adj.get(e.src).push(e.dst);
indeg.set(e.dst, (indeg.get(e.dst) || 0) + 1);
}
const rank = new Map(ids.map(n => [n, 0]));
const queue = ids.filter(n => (indeg.get(n) || 0) === 0);
/* Snapshot before the topological walk decrements `indeg` out from under
us — these are the steps a run actually starts at, and so the steps a
trigger points into. */
const entryIds = queue.slice();
const seen = new Set(queue);
let i = 0, guard = 0;
while (i < queue.length && guard++ < ids.length * ids.length + 10) {
const n = queue[i++];
for (const m of adj.get(n) || []) {
if (rank.get(m) < rank.get(n) + 1) rank.set(m, rank.get(n) + 1);
indeg.set(m, (indeg.get(m) || 0) - 1);
if (indeg.get(m) <= 0 && !seen.has(m)) { seen.add(m); queue.push(m); }
}
}
const maxRank = ids.length ? Math.max(...ids.map(n => rank.get(n) || 0)) : 0;
for (const n of ids) if (!seen.has(n)) rank.set(n, maxRank + 1);
const buckets = new Map();
for (const n of ids) { const r = rank.get(n) || 0; if (!buckets.has(r)) buckets.set(r, []); buckets.get(r).push(n); }
nodes = [];
for (const [r, list] of buckets) {
list.forEach((id, i2) => {
const defX = r * COL_W, defY = (i2 - (list.length - 1) / 2) * ROW_H;
const o = posOverride[id];
nodes.push({ id, x: o ? o.x : defX, y: o ? o.y : defY, w: 150, h: 56 });
});
}
if (ctx) {
const draftB = draft ? draft.bindings : {};
for (const n of nodes) {
const ex = wfNodeExecutor(draftB, n.id);
ctx.font = '600 13.5px ' + cssVar('--sans');
const w1 = ctx.measureText(clip(n.id, 24)).width;
ctx.font = '11.5px ' + cssVar('--sans');
const w2 = ctx.measureText(clip(wfNodeSubtitle(ex), 30)).width;
n.w = Math.max(150, Math.max(w1, w2) + 44);
}
}
byId = new Map(nodes.map(n => [n.id, n]));
edgesGeo = (draft ? draft.edges : []).map((e, idx) => ({ e, idx, a: byId.get(e.src), b: byId.get(e.dst) }));
layoutTriggers(entryIds);
}
/* The lane sits to the LEFT of wherever the entry steps currently are, not
at a fixed x — nodes are draggable, and a lane pinned to the origin ends
up behind the plan the moment someone rearranges it. Right-aligned to one
shared edge so the dashed arrows all span the same gap. */
function layoutTriggers(entryIds) {
trgNodes = []; trgEdges = [];
const list = WF_TRG || [];
if (!list.length || !nodes.length) return;
let anchor = (entryIds || []).map(id => byId.get(id)).filter(Boolean);
if (!anchor.length) anchor = [nodes.reduce((a, b) => (b.x < a.x ? b : a))];
let left = Infinity, cy = 0;
for (const n of anchor) { left = Math.min(left, n.x - n.w / 2); cy += n.y; }
cy /= anchor.length;
trgNodes = list.map((g, i) => ({
g, hash: g.hash, w: TRG_W, h: TRG_H,
x: 0, y: cy + (i - (list.length - 1) / 2) * TRG_ROW,
}));
if (ctx) {
for (const t of trgNodes) {
const f = t.g.fields || {};
ctx.font = '600 13px ' + cssVar('--sans');
const w1 = ctx.measureText(clip(trgWhen(f), 34)).width;
ctx.font = '11.5px ' + cssVar('--sans');
const w2 = ctx.measureText(clip(trgSubtitle(f), 28)).width;
t.w = Math.max(TRG_W, Math.max(w1, w2) + 46);
}
}
const rightEdge = left - TRG_GAP;
for (const t of trgNodes) {
t.x = rightEdge - t.w / 2;
for (const n of anchor) trgEdges.push({ a: t, b: n });
}
}
function hitTrigger(p) {
for (let i = trgNodes.length - 1; i >= 0; i--) {
const t = trgNodes[i];
if (Math.abs(p.x - t.x) <= t.w / 2 + 3 && Math.abs(p.y - t.y) <= t.h / 2 + 3) return t;
}
return null;
}
function resetOverrides() { posOverride = {}; }
function renameOverride(oldId, next) { if (posOverride[oldId]) { posOverride[next] = posOverride[oldId]; delete posOverride[oldId]; } }
function setSelection(s) { sel = s; }
function kindColor(kind) { return colors[kind] || colors.dim; }
function handlePt(n) { return { x: n.x + n.w / 2 + 14, y: n.y }; }
function toWorld(e) {
const r = cv.getBoundingClientRect();
return { x: (e.clientX - r.left - W / 2 - tx) / scale, y: (e.clientY - r.top - H / 2 - ty) / scale };
}
function hitNode(p) {
for (let i = nodes.length - 1; i >= 0; i--) {
const n = nodes[i];
if (Math.abs(p.x - n.x) <= n.w / 2 + 3 && Math.abs(p.y - n.y) <= n.h / 2 + 3) return n;
}
return null;
}
function hitHandle(p) {
for (let i = nodes.length - 1; i >= 0; i--) {
const n = nodes[i], hp = handlePt(n);
if (Math.hypot(p.x - hp.x, p.y - hp.y) <= HANDLE_HIT) return n;
}
return null;
}
/* The curve `draw()` actually strokes, as a single source of truth — its
endpoints sit on the node borders (offset by half-width, toward
whichever side the other node is on), not the centers, so an edge
between two node boxes doesn't visibly cut into either of them. The
control points still bow off the raw centers (`midx`) — using the
border x there too would barely change the curve's shape, and this
keeps the bow symmetric regardless of node width. */
function edgeCurve(a, b, back) {
const midx = (a.x + b.x) / 2, bow = back ? -70 - Math.abs(a.x - b.x) * 0.15 : 0;
return {
ax: a.x + (b.x >= a.x ? a.w / 2 : -a.w / 2), ay: a.y,
bx: b.x - (b.x >= a.x ? b.w / 2 : -b.w / 2), by: b.y,
c1x: midx, c1y: a.y + bow, c2x: midx, c2y: b.y + bow,
};
}
/* Evaluated on that same curve — this used to plug the raw node centers
in as P0/P3 while `draw()` stroked the border-adjusted curve above, so
the arrowhead (t≈0.985) landed inside the destination node's box and
was painted over, and `hitEdge()`'s hit-testing didn't line up with
what was on screen. */
function bezierPoint(a, b, back, t) {
const c = edgeCurve(a, b, back), u = 1 - t;
return { x: u*u*u*c.ax + 3*u*u*t*c.c1x + 3*u*t*t*c.c2x + t*t*t*c.bx, y: u*u*u*c.ay + 3*u*u*t*c.c1y + 3*u*t*t*c.c2y + t*t*t*c.by };
}
function hitEdge(p) {
let best = -1, bestD = 9;
for (let i = 0; i < edgesGeo.length; i++) {
const { a, b, e } = edgesGeo[i];
if (!a || !b) continue;
for (let s = 0; s <= 20; s++) {
const pt = bezierPoint(a, b, e.max_cycles != null, s / 20);
const d = Math.hypot(pt.x - p.x, pt.y - p.y);
if (d < bestD) { bestD = d; best = i; }
}
}
return best;
}
function roundRect(x, y, w, h, r) {
ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath();
}
function halo(text, x, y, font, fill) {
ctx.textAlign = 'center'; ctx.font = font; ctx.lineWidth = 3.5; ctx.lineJoin = 'round';
ctx.strokeStyle = colors.well; ctx.strokeText(text, x, y);
ctx.fillStyle = fill; ctx.fillText(text, x, y);
}
function arrow(x, y, ang, color) {
ctx.save(); ctx.translate(x, y); ctx.rotate(ang);
ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(-9, -4.5); ctx.lineTo(-9, 4.5); ctx.closePath();
ctx.fillStyle = color; ctx.fill(); ctx.restore();
}
function draw() {
if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, W, H);
ctx.save();
ctx.translate(W / 2 + tx, H / 2 + ty);
ctx.scale(scale, scale);
/* Under the plan's own edges: a trigger arrow is the cause arriving from
outside, not a step in the graph. Dashed for the same reason — the plan
does not contain it, and a solid line would read as one more edge you
could select and delete. */
for (const te of trgEdges) {
const live = (te.a.g.fields || {}).enabled !== false;
const c = edgeCurve(te.a, te.b, false);
ctx.beginPath();
ctx.moveTo(c.ax, c.ay);
ctx.bezierCurveTo(c.c1x, c.c1y, c.c2x, c.c2y, c.bx, c.by);
ctx.strokeStyle = live ? colors.trg : colors.ghost;
ctx.lineWidth = 1.6; ctx.setLineDash([6, 5]); ctx.globalAlpha = live ? 0.75 : 0.45;
ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1;
const end = bezierPoint(te.a, te.b, false, 0.985), near = bezierPoint(te.a, te.b, false, 0.9);
ctx.globalAlpha = live ? 0.8 : 0.45;
arrow(end.x, end.y, Math.atan2(end.y - near.y, end.x - near.x), live ? colors.trg : colors.ghost);
ctx.globalAlpha = 1;
}
for (let i = 0; i < edgesGeo.length; i++) {
const { a, b, e } = edgesGeo[i];
if (!a || !b) continue;
const back = e.max_cycles != null;
const selected = sel && sel.kind === 'edge' && sel.idx === i;
const c = edgeCurve(a, b, back);
ctx.beginPath();
ctx.moveTo(c.ax, c.ay);
ctx.bezierCurveTo(c.c1x, c.c1y, c.c2x, c.c2y, c.bx, c.by);
ctx.strokeStyle = selected ? colors.ink : (back ? colors.faint : colors.line);
ctx.lineWidth = selected ? 2.4 : 1.8;
if (back) ctx.setLineDash([5, 4]);
ctx.globalAlpha = 0.9;
ctx.stroke();
ctx.setLineDash([]);
const end = bezierPoint(a, b, back, 0.985), near = bezierPoint(a, b, back, 0.9);
arrow(end.x, end.y, Math.atan2(end.y - near.y, end.x - near.x), selected ? colors.ink : (back ? colors.faint : colors.dim));
const mid = bezierPoint(a, b, back, 0.5);
let label = e.cond ? clip(e.cond, 26) : '';
if (back) label = (label ? label + ' ' : '') + '↻ ×' + e.max_cycles;
if (label && scale > 0.5) halo(label, mid.x, mid.y - 8, '11.5px ' + cssVar('--sans'), back ? colors.faint : colors.dim);
}
/* the edge being drawn right now, if any */
if (connectFrom && connectPt) {
const a = byId.get(connectFrom);
if (a) {
ctx.beginPath();
ctx.moveTo(a.x + a.w / 2, a.y);
ctx.lineTo(connectPt.x, connectPt.y);
ctx.strokeStyle = colors.ink; ctx.lineWidth = 2; ctx.setLineDash([4, 4]); ctx.globalAlpha = 0.7;
ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1;
}
}
ctx.globalAlpha = 1;
if (trgNodes.length) {
const topY = Math.min.apply(null, trgNodes.map(t => t.y - t.h / 2));
const leftX = Math.min.apply(null, trgNodes.map(t => t.x - t.w / 2));
if (scale > 0.45) {
ctx.textAlign = 'left';
ctx.font = '600 10.5px ' + cssVar('--sans');
ctx.fillStyle = colors.faint;
ctx.fillText('STARTED BY', leftX + 2, topY - 12);
}
for (const t of trgNodes) {
const f = t.g.fields || {};
const live = f.enabled !== false;
const c = live ? colors.trg : colors.ghost;
const selected = sel && sel.kind === 'trigger' && sel.hash === t.hash;
const x0 = t.x - t.w / 2, y0 = t.y - t.h / 2;
ctx.beginPath(); roundRect(x0, y0, t.w, t.h, 13);
ctx.fillStyle = colors.surface; ctx.fill();
ctx.lineWidth = selected ? 2.6 : 1.6;
ctx.strokeStyle = selected ? colors.ink : c;
ctx.setLineDash(selected ? [] : [5, 4]);
ctx.stroke(); ctx.setLineDash([]);
/* A ring, where a step draws a filled dot — the shape says "not one of
the steps" before the colour or the dashes do. */
ctx.beginPath(); ctx.arc(x0 + 15, y0 + 15, 4, 0, 7);
ctx.lineWidth = 1.8; ctx.strokeStyle = c; ctx.stroke();
ctx.textAlign = 'left';
ctx.fillStyle = live ? colors.ink : colors.dim;
ctx.font = (selected ? '700 ' : '600 ') + '13px ' + cssVar('--sans');
ctx.fillText(clip(trgWhen(f), 34), x0 + 26, y0 + 20);
ctx.fillStyle = colors.faint;
ctx.font = '11.5px ' + cssVar('--sans');
ctx.fillText(clip(trgSubtitle(f), 28), x0 + 26, y0 + 37);
}
}
for (const n of nodes) {
const ex = wfNodeExecutor(WF_DRAFT ? WF_DRAFT.bindings : {}, n.id);
/* The run overlay. A step with no row in this run was never reached, so
it is dimmed rather than tinted — an absence, not an outcome. */
const st = WF_STEPS ? (WF_STEPS.get(n.id) || null) : null;
const unreached = !!WF_STEPS && !st;
if (unreached) ctx.globalAlpha = 0.5;
const c = colors[ex.kind] || colors.dim;
const selected = sel && sel.kind === 'node' && sel.id === n.id;
const isDropTarget = connectFrom && connectFrom !== n.id && connectTarget === n.id;
const x0 = n.x - n.w / 2, y0 = n.y - n.h / 2;
ctx.beginPath(); roundRect(x0, y0, n.w, n.h, 11);
ctx.fillStyle = colors.surface; ctx.fill();
ctx.lineWidth = selected || isDropTarget ? 2.6 : 1.6;
ctx.strokeStyle = isDropTarget ? colors.ink : (selected ? colors.ink : c);
if (ex.kind === 'abstract') ctx.setLineDash([4, 3]);
ctx.stroke(); ctx.setLineDash([]);
if (isDropTarget) {
ctx.globalAlpha = 0.08; ctx.fillStyle = colors.ink;
ctx.beginPath(); roundRect(x0, y0, n.w, n.h, 11); ctx.fill(); ctx.globalAlpha = 1;
}
if (WF_STEPS) {
ctx.save();
ctx.beginPath(); roundRect(x0, y0, n.w, n.h, 11); ctx.clip();
ctx.fillStyle = st ? colors[STEP_TONE[st.state]] : colors.line;
ctx.fillRect(x0, y0, 7, n.h);
ctx.restore();
}
ctx.beginPath(); ctx.arc(x0 + 14, y0 + 16, 4, 0, 7); ctx.fillStyle = c; ctx.fill();
ctx.textAlign = 'left';
ctx.fillStyle = colors.ink;
ctx.font = (selected ? '700 ' : '600 ') + '13.5px ' + cssVar('--sans');
ctx.fillText(clip(n.id, 24), x0 + 25, y0 + 21);
ctx.fillStyle = colors.dim;
ctx.font = '11.5px ' + cssVar('--sans');
ctx.fillText(clip(wfNodeSubtitle(ex), 30), x0 + 25, y0 + 38);
/* the connector handle — always visible, brighter on hover so it
reads as grabbable before the user has ever dragged one */
const hp = handlePt(n);
const hot = hoverId === n.id || connectFrom === n.id;
ctx.beginPath(); ctx.arc(hp.x, hp.y, hot ? HANDLE_R + 1.5 : HANDLE_R, 0, 7);
ctx.fillStyle = colors.surface; ctx.fill();
ctx.lineWidth = hot ? 2.2 : 1.6; ctx.strokeStyle = hot ? colors.ink : colors.line; ctx.stroke();
ctx.beginPath(); ctx.arc(hp.x, hp.y, 2.5, 0, 7); ctx.fillStyle = hot ? colors.ink : colors.faint; ctx.fill();
if (unreached) ctx.globalAlpha = 1;
}
ctx.restore();
ctx.globalAlpha = 1;
}
/* A guessed CSS calc() for "fill to the bottom of the window" drifts the
moment the header above it changes height — measure the canvas's own
rendered top instead, so it is always exactly right regardless of what
changed above it. */
function resize() {
if (!cv) return;
const top = cv.getBoundingClientRect().top;
cv.style.height = Math.max(480, Math.round(window.innerHeight - top - 32)) + 'px';
dpr = window.devicePixelRatio || 1;
W = cv.clientWidth; H = cv.clientHeight;
cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
}
function fit() {
if (!nodes.length) { scale = 1; tx = ty = 0; draw(); return; }
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (const n of nodes.concat(trgNodes)) {
x0 = Math.min(x0, n.x - n.w / 2 - 30); y0 = Math.min(y0, n.y - n.h / 2 - 40);
x1 = Math.max(x1, n.x + n.w / 2 + 40); y1 = Math.max(y1, n.y + n.h / 2 + 40);
}
const padR = $('wfinspect').hidden ? 24 : 322, padT = 60, padB = 30, padL = 24;
const availW = Math.max(160, W - padL - padR), availH = Math.max(160, H - padT - padB);
scale = Math.max(0.3, Math.min(1.5, Math.min(availW / (x1 - x0), availH / (y1 - y0))));
tx = (padL + availW / 2) - W / 2 - ((x0 + x1) / 2) * scale;
ty = (padT + availH / 2) - H / 2 - ((y0 + y1) / 2) * scale;
draw();
}
function legend() {
const host = $('wflegend'); host.textContent = '';
const add = (color, label, ring) => {
const s = el('span');
const d = el('span');
d.style.cssText = 'width:8px;height:8px;border-radius:4px;flex-shrink:0;'
+ (ring ? 'border:1.6px solid ' + color : 'background:' + color);
s.appendChild(d); s.appendChild(el('span', null, label));
host.appendChild(s);
};
for (const [k, label] of [['host', 'Host tool'], ['client', 'Human approval'],
['abstract', 'Abstract (LLM)'], ['subgraph', 'Subgraph']]) add(colors[k], label);
if (trgNodes.length) add(colors.trg, 'Trigger', true);
/* Only while an overlay is on: a key for colours that aren't on screen is
just clutter, and this legend has to stay readable at one or two lines. */
if (WF_STEPS) {
host.appendChild(el('span', 'legsep', '·'));
for (const [k, label] of [['ok', 'done'], ['warn', 'waiting'], ['danger', 'failed']]) add(colors[k], label);
}
}
return {
recolor, resetOverrides, renameOverride, setSelection, kindColor, draw,
rebuild() { layout(); },
refresh() { if (!ctx) return; layout(); legend(); draw(); },
wire() {
cv = $('wfcanvas'); ctx = cv.getContext('2d'); recolor();
window.addEventListener('resize', () => { if (!$('wfEditorWrap').hidden) { resize(); fit(); } });
cv.addEventListener('mousedown', e => {
const p = toWorld(e); moved = false;
const h = hitHandle(p);
if (h && !WF_LOCKED) { connectFrom = h.id; connectPt = p; connectTarget = null; return; }
const n = hitNode(p);
if (n) { drag = { id: n.id, dx: n.x - p.x, dy: n.y - p.y }; return; }
/* Triggers are neither draggable nor connectable: the lane is not the
user's to arrange, and a plan grain has no field that could record
where a trigger sits. Panning still arms, so a drag starting on one
pans exactly like a drag on the background; the click only lands if
the pointer never moved. */
const t = hitTrigger(p);
trgDown = t ? t.hash : null;
panning = { x: e.clientX - tx, y: e.clientY - ty };
if (!t) cv.classList.add('grabbing');
});
window.addEventListener('mousemove', e => {
if (connectFrom) {
const p = toWorld(e); connectPt = p;
const n = hitNode(p);
connectTarget = (n && n.id !== connectFrom) ? n.id : null;
draw(); return;
}
if (drag) {
const p = toWorld(e); const n = byId.get(drag.id);
if (n) { n.x = p.x + drag.dx; n.y = p.y + drag.dy; posOverride[n.id] = { x: n.x, y: n.y }; }
moved = true; draw(); return;
}
if (panning) { tx = e.clientX - panning.x; ty = e.clientY - panning.y; moved = true; draw(); return; }
if (!cv) return;
const r = cv.getBoundingClientRect();
if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) return;
const p = toWorld(e);
const h = hitHandle(p), n = h ? null : hitNode(p);
const nextHover = h ? h.id : null;
if (nextHover !== hoverId) { hoverId = nextHover; draw(); }
cv.style.cursor = h ? 'crosshair' : (n || hitTrigger(p) || hitEdge(p) >= 0) ? 'pointer' : 'grab';
});
window.addEventListener('mouseup', e => {
if (connectFrom) {
const p = toWorld(e); const n = hitNode(p);
if (n && n.id !== connectFrom) wfConnectNodes(connectFrom, n.id);
connectFrom = null; connectPt = null; connectTarget = null; draw();
return;
}
if (drag) { if (!moved) wfNodeClicked(drag.id); drag = null; return; }
if (panning) {
if (!moved) {
if (trgDown) wfTriggerClicked(trgDown);
else {
const p = toWorld(e); const ei = hitEdge(p);
if (ei >= 0) wfEdgeClicked(ei); else wfCanvasBgClicked();
}
}
panning = null; trgDown = null; cv.classList.remove('grabbing');
}
});
cv.addEventListener('mouseleave', () => { if (hoverId) { hoverId = null; draw(); } });
cv.addEventListener('wheel', e => { e.preventDefault();
const f = e.deltaY < 0 ? 1.12 : 0.89; scale = Math.max(0.25, Math.min(2.2, scale * f)); draw(); }, { passive: false });
cv.addEventListener('dblclick', () => fit());
$('wfin').onclick = () => { scale = Math.min(2.2, scale * 1.2); draw(); };
$('wfout').onclick = () => { scale = Math.max(0.25, scale / 1.2); draw(); };
$('wffit').onclick = () => fit();
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && connectFrom) { connectFrom = null; connectPt = null; connectTarget = null; draw(); }
});
},
mount() { if (!cv || !cv.clientWidth) { requestAnimationFrame(() => WFGraph.mount()); return; } resize(); layout(); fit(); legend(); draw(); },
};
})();
/* ══ tools: the catalog, and every call made against it ═══════════════
Definition and execution are the same grain type split by `kind` — "what
can run" and "what did run" are two questions about ONE catalog, so they
are two tabs here rather than two pages. Configuration is not a third tab:
a tool's schema, locked params and executor ARE the catalog entry, and a
separate table of the same fields is the kind of duplicate surface that
drifts out of agreement with the one beside it.
Everything comes from /api/browse, which is already loaded — no new server
route, the same way the workflow canvas is built. */
function toolExecs() {
return wfRows().filter(g => {
const f = g.fields || {};
return g.type === 'tool' && f.kind !== 'definition' && isCurrent(g);
}).sort((a, b) => createdMs(b.fields) - createdMs(a.fields));
}
/** Where a definition is actually wired in: plan → node. */
function toolBoundIn(hash) {
const out = [];
for (const g of workflowGrains()) {
const b = (g.fields || {}).bindings || {};
for (const node of Object.keys(b)) if (bareHash(b[node]) === hash) out.push({ plan: g, node });
}
return out;
}
const toolIsClient = f => (f || {}).executor_kind === 'client';
const toolKindWord = f => toolIsClient(f) ? 'Human approval' : 'Host tool';
const toolKindTone = f => toolIsClient(f) ? 'warn' : 'accent';
function renderTools() {
const nsHost = $('toolNsHost'); nsHost.textContent = '';
nsHost.appendChild(nsCombo('toolNs', WF_NS || boundNamespace(), ns => wfSetNamespace(ns)));
const host = $('toolBody');
host.textContent = '';
/* Execution rows resolve their state against the run's outcome, so without
the index a Pending step in a canceled run would read as "waiting on a
person" — an approval that can never arrive. Correctness, not a label. */
if (!RUNIDX && !RUNIDX_INFLIGHT) loadRuns().then(() => { if (PAGE === 'tools') render(); });
if (TOOLTAB === 'catalog' && TOOL_SEL) { renderToolDetail(host); return; }
renderCrumbHeader('toolCrumb', [{ label: 'Tools' }],
'What a step can call. A <b>definition</b> is the catalog entry a plan binds a node to — its schema is '
+ 'the contract the model must fill; an <b>execution</b> is one call that was actually made, journaled '
+ 'as its own immutable grain.');
if (TOOLTAB === 'catalog') renderToolCatalog(host); else renderToolExecs(host);
}
function renderToolCatalog(host) {
const defs = toolDefs().slice().sort((a, b) =>
String((a.fields || {}).tool_name || '').localeCompare(String((b.fields || {}).tool_name || '')));
if (!defs.length) {
host.innerHTML = '<div class="empty">No tools defined in this memory. A definition is what a plan node '
+ 'binds to — write one with <code>bind_tool</code>, or <code>ADD tool</code> in CAL.</div>';
return;
}
const grid = el('div', 'toolgrid');
for (const g of defs) grid.appendChild(toolCard(g));
host.appendChild(grid);
}
function toolCard(g) {
const f = g.fields || {};
const b = el('button', 'toolcard');
const hd = el('div', 'hd');
hd.appendChild(el('b', null, f.tool_name || shortHash(g.hash)));
const badge = el('span', 'wf-badge', toolKindWord(f));
badge.style.cssText = 'background:var(--well);color:var(--' + toolKindTone(f) + ')';
hd.appendChild(badge);
b.appendChild(hd);
if (f.tool_description) b.appendChild(el('div', 'desc', f.tool_description));
const ann = f.annotations || {};
const tags = [];
if (ann.read_only) tags.push('read-only');
if (ann.destructive) tags.push('destructive');
if (ann.idempotent) tags.push('idempotent');
const bound = toolBoundIn(g.hash);
const calls = toolExecs().filter(e => (e.fields || {}).tool_name === f.tool_name).length;
const parts = [];
if (tags.length) parts.push(tags.join(' · '));
parts.push(bound.length ? 'bound in ' + bound.map(x => wfLabel(x.plan)).filter((v, i, a) => a.indexOf(v) === i).join(', ')
: 'not bound in any plan');
if (calls) parts.push(calls + (calls === 1 ? ' call' : ' calls'));
b.appendChild(el('div', 'use', parts.join(' — ')));
b.onclick = () => { TOOL_SEL = f.tool_name || g.hash; render(); };
return b;
}
function renderToolDetail(host) {
const g = toolDefs().find(t => ((t.fields || {}).tool_name || t.hash) === TOOL_SEL);
if (!g) { TOOL_SEL = null; renderTools(); return; }
const f = g.fields || {};
renderCrumbHeader('toolCrumb', [
{ label: 'Tools', onClick: () => { TOOL_SEL = null; render(); } },
{ label: f.tool_name || shortHash(g.hash) },
], f.tool_description ? esc(f.tool_description) : null);
const card = el('div', 'card');
card.style.cssText = 'padding:4px 20px 18px';
const row = (k, v, mono) => {
if (v == null || v === '') return;
const d = el('div', 'kv');
d.appendChild(el('span', 'k', k));
const val = el('span', 'v', String(v));
if (mono) { val.style.fontFamily = 'var(--mono)'; val.style.fontSize = '12.5px'; }
d.appendChild(val);
card.appendChild(d);
};
row('Runs as', toolKindWord(f) + (toolIsClient(f)
? ' — the run pauses here until a person responds'
: ' — executed by the host through $AREEV_RUN_TOOL_CMD'));
const ann = f.annotations || {};
const tags = [ann.read_only && 'read-only', ann.destructive && 'destructive', ann.idempotent && 'idempotent']
.filter(Boolean);
if (tags.length) row('Declared effects', tags.join(' · '));
const bound = toolBoundIn(g.hash);
if (bound.length) {
const d = el('div', 'kv');
d.appendChild(el('span', 'k', 'Bound in'));
const v = el('span', 'v');
v.style.cssText = 'display:flex;flex-direction:column;gap:4px;align-items:flex-start';
for (const x of bound) {
const link = el('button', 'link');
link.style.cssText = 'border:0;background:none;color:var(--accent);font:inherit;font-size:13.5px;padding:0;text-align:left';
link.textContent = wfLabel(x.plan) + ' › ' + x.node;
link.onclick = () => { location.hash = '#workflows/' + x.plan.hash; };
v.appendChild(link);
}
d.appendChild(v);
card.appendChild(d);
} else {
row('Bound in', 'No plan binds a node to this tool yet.');
}
/* An opaque host reference that may carry an endpoint or credentials —
SR-F5 keeps it out of logs, so keep it out of the default view too. */
if (f.executor_uri) {
const d = el('div', 'kv dev-flex');
d.appendChild(el('span', 'k', 'Executor'));
const v = el('span', 'v'); v.style.fontFamily = 'var(--mono)'; v.style.fontSize = '12.5px';
v.textContent = f.executor_uri;
d.appendChild(v);
card.appendChild(d);
}
if (f.spec_hash) {
const d = el('div', 'kv dev-flex');
d.appendChild(el('span', 'k', 'Spec at bind time'));
const v = el('span', 'v'); v.style.fontFamily = 'var(--mono)'; v.style.fontSize = '12.5px';
v.textContent = bareHash(f.spec_hash);
d.appendChild(v);
card.appendChild(d);
}
row('Declared', relTime(createdMs(f)));
host.appendChild(card);
section(host, 'What the model may fill in', schemaBlock(f.input_schema)
|| el('div', 'tiny', 'No input schema — this tool takes no arguments.'));
if (f.output_schema) section(host, 'What it returns', schemaBlock(f.output_schema) || jsonBlock(f.output_schema));
if (f.locked_params) section(host, 'Locked parameters (the model may not choose these)', jsonBlock(f.locked_params));
if (Array.isArray(f.examples) && f.examples.length) section(host, 'Examples', jsonBlock(f.examples));
const mine = toolExecs().filter(e => (e.fields || {}).tool_name === (f.tool_name || ''));
if (mine.length) {
const wrap = el('div', 'card execwrap');
for (const e of mine.slice(0, 12)) wrap.appendChild(execRow(e));
section(host, 'Recent calls · ' + mine.length, wrap);
}
}
function section(host, title, body) {
const h = el('div');
h.style.cssText = 'display:flex;flex-direction:column;gap:9px;margin-top:12px';
const t = el('div', 'sec-label', title.toUpperCase());
h.appendChild(t);
h.appendChild(body);
host.appendChild(h);
}
/** A JSON Schema object rendered as a property table, or null if it isn't one. */
function schemaBlock(schema) {
const props = schema && schema.properties;
if (!props || typeof props !== 'object') return null;
const keys = Object.keys(props);
if (!keys.length) return null;
const req = new Set(Array.isArray(schema.required) ? schema.required : []);
const host = el('div', 'card schema');
host.style.padding = '4px 18px';
for (const k of keys) {
const p = props[k] || {};
const r = el('div', 'r');
r.appendChild(el('span', 'n', k));
r.appendChild(el('span', 't', p.type || (p.enum ? 'enum' : 'any')));
if (req.has(k)) r.appendChild(el('span', 'req', 'required'));
if (p.description) r.appendChild(el('span', 'd', p.description));
host.appendChild(r);
}
return host;
}
/* Executions, grouped by the run they belong to. A tool call made outside a
run is a real thing too (an agent calling a tool directly), so it gets its
own group rather than being filtered out of existence. */
function renderToolExecs(host) {
const all = toolExecs();
if (!all.length) {
host.innerHTML = '<div class="empty">No tool calls recorded yet. Every call a run makes is journaled '
+ 'here as its own grain — start one with <code>areev run start --tool-cmd …</code>.</div>';
return;
}
const groups = new Map();
for (const g of all) {
const k = (g.fields || {}).run_id || '';
if (!groups.has(k)) groups.set(k, []);
groups.get(k).push(g);
}
const order = [...groups.keys()].sort((a, b) => {
if (!a) return 1;
if (!b) return -1;
return createdMs(groups.get(b)[0].fields) - createdMs(groups.get(a)[0].fields);
});
for (const key of order) {
const rows = groups.get(key);
const grp = el('div', 'rungroup');
const hd = el('div', 'hd');
const run = RUNIDX && RUNIDX.byId.get(key);
hd.appendChild(el('h3', null, key ? key + ' · ' + rows.length : 'Outside a run · ' + rows.length));
hd.appendChild(el('span', 'tiny', key
? (run ? planLabel(run.plan_hash) + ' · ' + run.outcome : 'a governed run')
: 'called directly by an agent, not journaled against a plan'));
grp.appendChild(hd);
const wrap = el('div', 'card execwrap');
for (const g of rows) wrap.appendChild(execRow(g));
grp.appendChild(wrap);
host.appendChild(grp);
}
}
function execRow(g) {
const f = g.fields || {};
const run = RUNIDX && f.run_id ? RUNIDX.byId.get(f.run_id) : null;
const state = stepState(f, run ? run.outcome : null);
const wrap = el('div');
const btn = el('button', 'exec');
const bar = el('span', 'bar');
bar.style.background = 'var(--' + STEP_TONE[state] + ')';
btn.appendChild(bar);
const nm = el('span', 'nm');
nm.appendChild(document.createTextNode(f.tool_name || shortHash(g.hash)));
const sub = [];
if (f.node && f.node !== f.tool_name) sub.push(f.node);
sub.push(STEP_WORD[state]);
if (f.attempt && f.attempt > 1) sub.push('attempt ' + f.attempt);
if (f.duration_ms != null) sub.push(f.duration_ms + 'ms');
nm.appendChild(el('span', null, ' ' + sub.join(' · ')));
btn.appendChild(nm);
btn.appendChild(el('span', 'when', relTime(createdMs(f))));
const det = el('div', 'execdet');
det.hidden = true;
btn.onclick = () => {
if (!det.hidden) { det.hidden = true; return; }
if (!det.childElementCount) buildExecDetail(det, f, g);
det.hidden = false;
};
wrap.appendChild(btn);
wrap.appendChild(det);
/* Deep-linked from a canvas node's "See the call" — open it already
expanded, otherwise the link lands on a closed row and looks inert. */
if (TOOL_SEL === g.hash) {
buildExecDetail(det, f, g);
det.hidden = false;
requestAnimationFrame(() => btn.scrollIntoView({ block: 'center' }));
}
return wrap;
}
function buildExecDetail(det, f, g) {
const add = (label, body) => {
det.appendChild(el('div', 'lab', label.toUpperCase()));
det.appendChild(body);
};
if (f.error) {
const e = el('div', 'tiny'); e.style.color = 'var(--danger)'; e.textContent = f.error;
add('Error', e);
}
if (f.input != null) add('Arguments', codeBlock(f.input));
const out = f.tool_content != null ? f.tool_content : f.content;
if (out != null) add('Result', codeBlock(out));
const meta = [];
if (f.author_did) meta.push('by ' + f.author_did);
if (f.superstep != null) meta.push('superstep ' + f.superstep);
if (f.usage_usd_micros) meta.push('$' + (f.usage_usd_micros / 1e6).toFixed(4));
if (f.usage_input_tokens || f.usage_output_tokens) {
meta.push((f.usage_input_tokens || 0) + ' in / ' + (f.usage_output_tokens || 0) + ' out tokens');
}
if (meta.length) det.appendChild(el('div', 'tiny', meta.join(' · ')));
const dv = el('div', 'tiny dev-only');
dv.style.fontFamily = 'var(--mono)';
dv.textContent = 'grain ' + g.hash + (f.tool_call_id ? ' · call ' + f.tool_call_id : '');
det.appendChild(dv);
}
/* ══ query workbench ══════════════════════════════════════════════════
Everything goes through /api/cal. Saved queries and templates are CAL
statements (DEFINE / RUN / DESCRIBE / DROP), not console-local state, so
they live in the .db file and work from the CLI and MCP too. Only the
history is browser-local — that is personal and ephemeral. */
const READ_ONLY_STMTS = new Set(['RECALL','ASSEMBLE','EXPLAIN','HISTORY','EXISTS','DESCRIBE','COUNT']);
const WRITEY = new Set(['ADD','SUPERSEDE','ACCUMULATE','FORGET','DEFINE','DROP','BATCH','RUN']);
const leadKeyword = q => (String(q || '').trim().split(/[^A-Za-z0-9]/)[0] || '').toUpperCase();
const QUERY_NAME_RE = /^[a-zA-Z][a-zA-Z0-9 _-]{0,63}$/;
const Q = { res: null, view: null, text: '', fmtTab: null };
/* The engine reports what it can actually execute. DEFINE/RUN parse but are
not in `supported_statements` on this build — the facade has no query or
template registry — so gate the UI on the engine rather than on the docs. */
let CAPS = null;
const stmtSupported = kw => !CAPS || (CAPS.supported_statements || []).includes(kw);
async function loadCaps() {
const r = await cal('DESCRIBE CAPABILITIES');
CAPS = (r.ok && r.result && r.result.info) || null;
}
/* ── history: this browser, this file ── */
const histKey = () => 'areev.hist.' + (String(DB_PATH).split('/').pop() || 'db');
function histLoad() { try { return JSON.parse(localStorage.getItem(histKey()) || '[]'); } catch (e) { return []; } }
function histPush(q, summary) {
const h = histLoad().filter(x => x.q !== q);
h.unshift({ q, at: Date.now(), s: summary });
try { localStorage.setItem(histKey(), JSON.stringify(h.slice(0, 100))); } catch (e) { /* quota */ }
}
/* ── the on-ramp ───────────────────────────────────────────────────────
A blank editor is a wall for anyone who does not already know CAL. These
questions write real statements into that same editor, so the first answer
also teaches the language that produced it. Keep the CAL current — bare `|`
is deprecated since CAL 1.1 (CAL-W007).
"john"/"acme-corp" as hardcoded example subjects almost never exist in a
real memory, so the very first thing a new user tries reliably comes back
empty. Pull an actual subject (and an actual value) from this file's own
Facts instead — BROWSE is already loaded at boot, so this costs nothing —
and fall back to filter-free forms (still true, just less specific) only
when the file genuinely has no facts yet to draw from. */
function starterFact() {
for (const g of BROWSE) {
if (isGone(g) || isInternal(g) || g.type !== 'fact') continue;
const f = g.fields || {};
if (typeof f.subject === 'string' && f.subject && f.object != null) return f;
}
return null;
}
function buildStarters() {
const f = starterFact();
if (!f) return [
['What is in this memory right now?', 'RECALL facts LIMIT 20'],
['Search the whole memory in plain words', 'RECALL facts ABOUT "notes"'],
['How much does it hold, in total?', 'RECALL facts COUNT'],
['Build a context brief to paste into a model',
'ASSEMBLE "brief me on this memory" FROM notes: (RECALL facts LIMIT 20) BUDGET 300 tokens FORMAT markdown'],
];
const q = s => '"' + String(s).replace(/"/g, '\\"') + '"';
const clip = s => { s = String(s); return s.length > 40 ? s.slice(0, 40) + '…' : s; };
const subj = f.subject, subjQ = q(subj), aboutQ = q(clip(f.object));
return [
['What do we know about a person or account?', 'RECALL facts WHERE subject = ' + subjQ],
['Search the whole memory in plain words', 'RECALL facts ABOUT ' + aboutQ],
['How much does it know about one thing?', 'RECALL facts WHERE subject = ' + subjQ + ' COUNT'],
['Build a context brief to paste into a model',
'ASSEMBLE "brief me on ' + subj.replace(/"/g, '\\"') + '" FROM notes: (RECALL facts WHERE subject = '
+ subjQ + ') BUDGET 300 tokens FORMAT markdown'],
];
}
function renderStarters() {
const box = $('qstarters'); box.textContent = '';
for (const [question, stmt] of buildStarters()) {
const b = el('button', 'starter');
b.appendChild(el('b', '', question));
b.appendChild(el('code', '', stmt));
b.onclick = () => { setQueryText(stmt); runQuery(stmt); };
box.appendChild(b);
}
}
/* Saved queries live in the file; history is this browser. Both were behind ▾
menus, which is where the two most useful things on the page went to hide. */
async function renderRecents() {
const box = $('qrecents'); box.textContent = '';
const savedCol = el('div'), recentCol = el('div');
savedCol.appendChild(el('div', 'sec-label', 'SAVED'));
recentCol.appendChild(el('div', 'sec-label', 'RECENT'));
box.appendChild(savedCol); box.appendChild(recentCol);
const h = histLoad().slice(0, 5);
if (!h.length) recentCol.appendChild(el('div', 'rempty', 'Nothing run yet in this browser'));
for (const it of h) {
const b = el('button', 'rrow');
b.appendChild(el('div', 'rq', it.q));
b.appendChild(el('div', 'rm', relTime(it.at) + (it.s ? ' · ' + it.s : '')));
b.onclick = () => runQuery(it.q);
recentCol.appendChild(b);
}
const qs = await cal('DESCRIBE QUERIES');
const list = qs.ok ? pickList((qs.result || {}).info) : [];
if (!list.length) savedCol.appendChild(el('div', 'rempty',
stmtSupported('DEFINE') ? 'None saved yet — run something, then Save'
: 'This build has no registry for saved queries yet'));
for (const it of list.slice(0, 5)) {
const name = itemName(it);
const b = el('button', 'rrow');
b.appendChild(el('div', 'rn', name));
b.appendChild(el('div', 'rm', itemDesc(it) || 'RUN "' + name + '"'));
b.onclick = () => runQuery('RUN "' + name + '"');
savedCol.appendChild(b);
}
}
function renderOnramp() { renderStarters(); renderRecents(); }
/* ── the editor ────────────────────────────────────────────────────────
A textarea cannot hold colour, so the caret stays in a transparent one and
a mirror underneath carries the highlighting. Keep the two in lockstep:
same font, same padding, same wrapping, or the colours drift off the text.
The keyword list is additive on purpose — a word CAL gains before this list
does simply renders unstyled, which is the harmless failure. */
const CAL_KEYWORDS = new Set(['RECALL', 'ASSEMBLE', 'EXPLAIN', 'HISTORY', 'EXISTS', 'DESCRIBE',
'COUNT', 'ADD', 'SUPERSEDE', 'ACCUMULATE', 'FORGET', 'DEFINE', 'DROP', 'BATCH', 'RUN', 'LET',
'WHERE', 'LIMIT', 'ABOUT', 'LIKE', 'FROM', 'BUDGET', 'TOKENS', 'FORMAT', 'PRESET', 'TEMPLATE',
'ORDER', 'BY', 'ASC', 'DESC', 'AND', 'OR', 'NOT', 'AS', 'SET', 'WITH', 'SINCE', 'UNTIL', 'OF',
'PRIORITY', 'QUERY', 'QUERIES', 'TEMPLATES', 'CAPABILITIES', 'ELEMENT', 'SECTION', 'PROGRESSIVE',
'IN', 'TRUE', 'FALSE', 'NULL']);
function highlightCal(src) {
const s = String(src); let out = '', i = 0;
while (i < s.length) {
const ch = s[i];
if (ch === '"') {
let j = i + 1;
while (j < s.length && s[j] !== '"') j += (s[j] === '\\' ? 2 : 1);
out += '<span class="s">' + esc(s.slice(i, Math.min(j + 1, s.length))) + '</span>';
i = j + 1; continue;
}
if (ch === '-' && s[i + 1] === '-') {
let j = s.indexOf('\n', i); if (j < 0) j = s.length;
out += '<span class="c">' + esc(s.slice(i, j)) + '</span>'; i = j; continue;
}
if (/[0-9]/.test(ch) && !/[A-Za-z0-9_]/.test(s[i - 1] || '')) {
let j = i; while (j < s.length && /[0-9._]/.test(s[j])) j++;
out += '<span class="n">' + esc(s.slice(i, j)) + '</span>'; i = j; continue;
}
if (/[A-Za-z_]/.test(ch)) {
let j = i; while (j < s.length && /[A-Za-z0-9_]/.test(s[j])) j++;
const w = s.slice(i, j);
out += CAL_KEYWORDS.has(w.toUpperCase()) ? '<span class="k">' + esc(w) + '</span>' : esc(w);
i = j; continue;
}
out += esc(ch); i++;
}
return out;
}
/* Grow with the statement rather than making people drag a corner, but stop
at max-height so a long ASSEMBLE cannot push the results off the screen. */
function syncEditor() {
const ta = $('qtext'), hl = $('qhl');
hl.innerHTML = highlightCal(ta.value) + '\n'; /* spacer: a trailing newline has no box */
ta.style.height = 'auto';
ta.style.height = Math.min(ta.scrollHeight, 340) + 'px';
hl.scrollTop = ta.scrollTop;
}
function setQueryText(s) { $('qtext').value = s; syncEditor(); queryNotice(); }
/* ── result shape helpers ── */
const rType = r => (r && r.type) || 'unknown';
const rGrains = r => (r && r.grains) || [];
function isHomogeneous(gs) {
if (gs.length < 2) return true;
const key = g => (rgType(g) || '') + '|' + Object.keys(rgFields(g)).sort().join(',');
const k0 = key(gs[0]);
return gs.every(g => key(g) === k0);
}
function defaultQView(r) {
const t = rType(r);
if (t === 'explain') return 'plan';
if (t === 'multi_formatted') { const n = Object.keys(r.formats || {})[0]; return n ? 'fmt:' + n : 'raw'; }
if (t === 'formatted') return 'format';
if (t === 'grains' || t === 'assembled') return isHomogeneous(rGrains(r)) ? 'table' : 'cards';
if (t === 'history') return 'history';
return 'raw';
}
function viewsFor(r) {
const t = rType(r), v = [];
if (t === 'grains' || t === 'assembled') {
v.push(['cards', 'Cards'], ['table', 'Table']);
if (rGrains(r).some(g => rgFields(g).subject && typeof rgFields(g).object === 'string')) v.push(['graph', 'Graph']);
}
if (t === 'formatted') v.push(['format', r.format || 'Rendered']);
if (t === 'multi_formatted') for (const n of Object.keys(r.formats || {})) v.push(['fmt:' + n, n]);
if (t === 'history') v.push(['history', 'Timeline']);
if (t === 'explain') v.push(['plan', 'Plan']);
v.push(['raw', 'Raw']);
return v;
}
function summarise(res) {
const r = res.result || {}, t = rType(r);
if (t === 'grains' || t === 'assembled') return rGrains(r).length + ' grains';
if (t === 'count') return r.count + ' count';
if (t === 'history') return (r.versions || []).length + ' versions';
if (t === 'multi_formatted') return Object.keys(r.formats || {}).length + ' formats';
return t;
}
/* ── running ── */
async function runQuery(text) {
const t = (text != null ? text : $('qtext').value).trim();
if (!t) return;
if (text != null) setQueryText(t);
Q.text = t;
$('qerr').hidden = true;
$('qrun').disabled = true;
const res = await cal(t);
$('qrun').disabled = false;
if (!res.ok) { Q.res = null; showQueryError(t, res); $('qresult').hidden = true; return; }
Q.res = res; Q.view = defaultQView(res.result); Q.fmtTab = null;
histPush(t, summarise(res));
renderQueryResult();
if (WRITEY.has(leadKeyword(t))) refresh();
}
function showQueryError(q, res) {
const box = $('qerr');
let html = '<span class="code">' + esc(res.code || 'CAL') + '</span>' + esc(res.error || 'error');
if (res.span && res.span.line) {
const line = q.split('\n')[res.span.line - 1] || '';
const col = Math.max(1, res.span.col || 1);
const width = Math.max(1, (res.span.end || 0) - (res.span.start || 0));
html += '<pre>' + esc(line) + '\n' + ' '.repeat(col - 1)
+ '^'.repeat(Math.min(width, Math.max(1, line.length - col + 1))) + '</pre>';
}
if (res.suggestion) html += '<div class="hint">hint: ' + esc(res.suggestion) + '</div>';
box.innerHTML = html; box.hidden = false;
}
/* Classification is by leading keyword, so a read-only query that opens with
LET is refused on a token-less console. Say so before they press Run. */
function queryNotice() {
const kw = leadKeyword($('qtext').value);
const n = $('qnotice');
if (!kw || canWrite() || READ_ONLY_STMTS.has(kw)) { n.textContent = ''; return; }
n.textContent = kw + ' needs a console started with --token-env';
n.style.color = 'var(--warn)';
}
/* ── the result viewer ── */
const GRAIN_VAR = { fact: '--cat-person', observation: '--cat-note', event: '--cat-thing',
goal: '--cat-project', tool: '--cat-org', skill: '--cat-project', state: '--cat-thing' };
const FMT_META = { markdown: ['md', 'text/markdown'], table: ['md', 'text/markdown'],
json: ['json', 'application/json'], yaml: ['yaml', 'text/yaml'], csv: ['csv', 'text/csv'],
sml: ['sml', 'text/plain'], toon: ['toon', 'text/plain'], text: ['txt', 'text/plain'],
triples: ['txt', 'text/plain'] };
/* Restate the statement in plain words. Derived from the CAL that was run —
never guessed from the result — so a non-technical reader can check the
query asked what they meant before trusting the rows. */
function describeQuery(text) {
const t = String(text || ''), kw = leadKeyword(t);
if (kw === 'ASSEMBLE') return 'a context brief, budgeted for a model';
if (kw === 'EXPLAIN') return 'how the engine would run this — nothing was read';
if (kw === 'HISTORY') return 'every version of it, newest first';
const kind = (t.match(/\b(?:RECALL|EXISTS)\s+([a-z_]+)/i) || [])[1];
const subj = (t.match(/subject\s*=\s*"([^"]+)"/i) || [])[1];
const about = (t.match(/\bABOUT\s+"([^"]+)"/i) || [])[1];
const bits = [];
if (kind && kind.toLowerCase() !== 'facts') bits.push('from ' + kind);
if (subj) bits.push('about ' + subj);
if (about) bits.push('matching “' + about + '”');
bits.push('newest first');
return bits.join(', ');
}
function renderQuerySummary() {
const box = $('qsummary'); box.textContent = '';
const res = Q.res; if (!res) return;
const r = res.result || {}, t = rType(r), gs = rGrains(r);
let head;
if (t === 'count') head = r.count + (r.count === 1 ? ' match' : ' matches');
else if (t === 'grains' || t === 'assembled') head = gs.length + (gs.length === 1 ? ' memory' : ' memories');
else if (t === 'history') head = (r.versions || []).length + ' versions';
else if (t === 'explain') head = 'Query plan';
/* A FORMAT result counts renderings, not answers — say how many memories
went in, so "2 formats" cannot be misread as two results. */
else if (t === 'formatted' || t === 'multi_formatted') {
const n = r.grain_count;
head = n != null ? n + (n === 1 ? ' memory' : ' memories') : 'Rendered';
}
else head = summarise(res);
const h = el('div', 'h', head + ' ');
h.appendChild(el('em', '', describeQuery(Q.text)));
box.appendChild(h);
const sup = gs.filter(g => g.superseded_by || rgFields(g).superseded_by).length;
if (sup) box.appendChild(el('div', 'tiny', sup + (sup === 1 ? ' has' : ' have')
+ ' been superseded since it was written — the older wording is kept so the change stays auditable'));
else if (res.elapsed_ms != null) box.appendChild(el('div', 'tiny', 'Ran in ' + res.elapsed_ms + ' ms'
+ (r.total_available != null && r.total_available > gs.length
? ' · ' + r.total_available + ' match in total' : '')));
}
/* Back to the on-ramp without reloading — the editor keeps its text so the
last query is still there to edit. */
function resetQuery() {
Q.res = null; Q.view = null;
$('qresult').hidden = true; $('qerr').hidden = true;
$('qonramp').hidden = false; $('qintro').hidden = false; $('qreset').hidden = true;
renderOnramp(); $('qtext').focus();
}
function renderQueryResult() {
const res = Q.res;
$('qresult').hidden = !res;
$('qonramp').hidden = !!res;
$('qintro').hidden = !!res;
$('qreset').hidden = !res;
if (!res) return;
renderQuerySummary();
const r = res.result || {}, t = rType(r);
/* The view can survive a re-render (page switch) into a result that has no
such view — fall back rather than render an empty pane. */
const available = viewsFor(r).map(v => v[0]);
if (!available.includes(Q.view)) Q.view = defaultQView(r);
const bar = $('qbar'); bar.textContent = '';
const gs = rGrains(r);
const total = r.total_available;
const seg = el('div', 'seg sm');
for (const [v, name] of viewsFor(r)) {
const b = el('button', Q.view === v ? 'on' : '', name);
b.onclick = () => { Q.view = v; renderQueryResult(); };
seg.appendChild(b);
}
bar.appendChild(seg);
const sp = el('div'); sp.style.flex = '1'; bar.appendChild(sp);
bar.appendChild(resultMenu('Copy', m => {
/* Ordered by where results actually go: a doc or ticket, a spreadsheet,
then code. `text` only exists on a FORMAT result — offer it first when
it does, because that is the thing the person asked to be rendered. */
if (r.text) mi(m, 'Copy as shown', 'the rendered ' + (r.format || 'output'),
() => copyText(r.text, 'Result'));
if (t === 'grains' || t === 'assembled') {
mi(m, 'Copy as Markdown', 'a table you can paste into a doc',
() => copyText(grainsMarkdown(gs), 'Markdown table'));
mi(m, 'Copy as CSV', 'for a spreadsheet', () => copyText(grainsCsv(gs), 'CSV'));
}
mi(m, 'Copy as JSON', 'the raw result', () => copyText(JSON.stringify(r, null, 2), 'Result JSON'));
}));
bar.appendChild(resultMenu('Download', m => {
mi(m, 'JSON', 'areev-result.json', () => download('areev-result.json', JSON.stringify(r, null, 2)));
if (t === 'grains' || t === 'assembled') {
mi(m, 'CSV', 'areev-result.csv', () => download('areev-result.csv', grainsCsv(gs), 'text/csv'));
}
}));
const body = $('qbody'); body.textContent = '';
if (t === 'assembled') body.appendChild(assembledSources(r));
if (Q.view === 'cards') body.appendChild(qCards(gs));
else if (Q.view === 'table') body.appendChild(qTable(gs));
else if (Q.view === 'graph') body.appendChild(qGraphNote(gs));
else if (Q.view === 'format' || String(Q.view).startsWith('fmt:')) body.appendChild(qFormats(r));
else if (Q.view === 'history') body.appendChild(qHistory(r));
else if (Q.view === 'plan') body.appendChild(qPlan(r));
else body.appendChild(jsonBlock(r));
/* Lay out immediately (reading scrollHeight forces the reflow we need),
then once more on the next frame in case web fonts shift the metrics. */
if (Q.view === 'cards') { layoutMasonry(); requestAnimationFrame(layoutMasonry); }
/* Honest paging: the engine tells us the true total, so never imply the
page is the whole answer. Re-runs with a larger LIMIT (CAL is bounded,
there is no stream to scroll). */
const more = $('qmore'); more.textContent = ''; more.hidden = true;
if ((t === 'grains' || t === 'assembled') && total != null && total > gs.length) {
more.hidden = false;
const b = el('button', 'btn ghost', 'Load 20 more (' + (total - gs.length) + ' not shown)');
b.onclick = () => runQuery(growLimit(Q.text, 20));
more.appendChild(b);
}
}
function growLimit(text, by) {
const m = /\bLIMIT\s+(\d+)/i.exec(text);
if (m) return text.replace(/\bLIMIT\s+\d+/i, 'LIMIT ' + (parseInt(m[1], 10) + by));
/* FORMAT closes the statement, so a LIMIT appended after it would not
parse — insert before the clause instead of at the end. */
const f = /\sFORMAT\s/i.exec(text);
if (f) return text.slice(0, f.index) + ' LIMIT ' + (20 + by) + text.slice(f.index);
return text.trim() + ' LIMIT ' + (20 + by);
}
/* A dropdown built where the bar is rebuilt each render. It carries the same
classes as the static menus, so the document-level click handler closes it. */
function resultMenu(label, build) {
const wrap = el('div', 'menuwrap');
const btn = el('button', 'btn ghost sm hasmenu', label);
const menu = el('div', 'menu'); menu.hidden = true;
btn.onclick = () => {
const wasOpen = !menu.hidden;
for (const x of document.querySelectorAll('.menu')) x.hidden = true;
if (wasOpen) return;
menu.textContent = ''; build(menu); menu.hidden = false;
};
wrap.appendChild(btn); wrap.appendChild(menu);
return wrap;
}
/* Markdown, because a result usually ends up in a ticket or a doc. Pipes in a
value would break the table, so escape them rather than dropping them. */
function grainsMarkdown(gs) {
const keys = new Set(); for (const g of gs) for (const k of Object.keys(rgFields(g))) keys.add(k);
const cols = ['kind', ...keys];
const cell = v => (v == null ? '' : (typeof v === 'object' ? JSON.stringify(v) : String(v)))
.replace(/\|/g, '\\|').replace(/\n/g, ' ');
return ['| ' + cols.join(' | ') + ' |', '| ' + cols.map(() => '---').join(' | ') + ' |']
.concat(gs.map(g => '| ' + cols.map(c =>
cell(c === 'kind' ? rgType(g) : rgFields(g)[c])).join(' | ') + ' |')).join('\n');
}
/* Colour JSON the same way values are coloured elsewhere in the console. The
regex runs before quote-escaping — escaping `"` first would hide the very
delimiter it matches on — so only &, < and > are escaped up front. */
function highlightJson(text) {
const safe = String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return safe.replace(
/("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false)\b|\b(null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g,
(m, str, colon, bool, nul, num) => {
if (str) return '<span class="' + (colon ? 'jk' : 'js') + '">' + str + '</span>' + (colon || '');
if (bool) return '<span class="jb">' + bool + '</span>';
if (nul) return '<span class="jz">' + nul + '</span>';
if (num) return '<span class="jn">' + num + '</span>';
return m;
});
}
function jsonBlock(value) {
const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
const pre = el('pre', 'code jsonv');
pre.innerHTML = highlightJson(text);
return pre;
}
/* A tool's content is often not prose — a JSON result, a script's stdout, a
snippet an agent generated. jsonBlock()'s highlighter is JSON-shaped
regexes; running it over arbitrary source would mis-colour perfectly
ordinary code (a quoted string, a bare number). Parse first: real JSON
(already an object, or a string that round-trips through JSON.parse) gets
the highlighted, pretty-printed block; anything else is plain monospace
text, exactly as written, so nothing is invented or miscoloured. */
function codeBlock(value) {
if (value != null && typeof value !== 'string') return jsonBlock(value);
const text = value == null ? '' : value;
try { return jsonBlock(JSON.parse(text)); } catch (e) { /* not JSON — show as-is */ }
return el('pre', 'code', text);
}
function grainsCsv(gs) {
const keys = new Set(); for (const g of gs) for (const k of Object.keys(rgFields(g))) keys.add(k);
const cols = ['hash', ...keys];
const cell = v => { const s = v == null ? '' : (typeof v === 'object' ? JSON.stringify(v) : String(v));
return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; };
return [cols.join(',')].concat(gs.map(g => cols.map(c =>
cell(c === 'hash' ? g.hash : rgFields(g)[c])).join(','))).join('\n');
}
const CARD_SKIP = new Set(['subject','relation','object','type','content','tool_content','description']);
/* Stored values are machine-shaped — epoch millis and raw JSON. Render them
the way a person reads them, but never lie about the value. */
function fmtValue(key, val) {
if (val == null) return '';
if (typeof val === 'number' && /(^|_)(at|ms)$/.test(key) && val > 1e11) {
return new Date(val).toLocaleString();
}
if (typeof val === 'number' && !Number.isInteger(val)) return String(Math.round(val * 1e4) / 1e4);
if (typeof val === 'object') return clampText(JSON.stringify(val));
return clampText(String(val));
}
/* Classify a value so colour can mean something. Hashes are teal wherever they
appear in this console; a failing flag is the one thing worth flagging. */
function valueClass(key, val) {
const k = String(key).toLowerCase();
if (typeof val === 'boolean') return val ? (/error|fail|stale|gone/.test(k) ? 'v-no' : 'v-yes') : 'v-time';
if (typeof val === 'number') return /(^|_)(at|ms)$/.test(k) && val > 1e11 ? 'v-time' : 'v-num';
const s = String(val);
if (/hash|^id$|_by$|derived_from|^svt$/.test(k) && /^[0-9a-f]{12,}$/i.test(s)) return 'v-hash';
if (/^[0-9a-f]{40,}$/i.test(s)) return 'v-hash';
return '';
}
/* Nothing matched is a result, not a failure. Restate the question, then hand
over the two moves that usually find it: search the words instead of the
key, or drop the filter. */
function qNoResults() {
const box = el('div', 'nores');
box.appendChild(el('div', 't', 'Nothing matched'));
box.appendChild(el('div', 'd', 'The query ran without error — this memory simply holds nothing '
+ (describeQuery(Q.text) || 'matching it') + '. Memories are only ever added, so an empty '
+ 'answer means it was never written, not that it was removed.'));
const acts = el('div', 'acts');
const about = (Q.text.match(/subject\s*=\s*"([^"]+)"/i) || [])[1];
if (about) {
const b = el('button', 'btn ghost sm', 'Search the words instead');
b.onclick = () => { const s = 'RECALL facts ABOUT "' + about + '"'; setQueryText(s); runQuery(s); };
acts.appendChild(b);
}
if (/\bWHERE\b/i.test(Q.text)) {
const b = el('button', 'btn ghost sm', 'Drop the filter');
b.onclick = () => { const s = Q.text.replace(/\s+WHERE\b[\s\S]*?(?=\s+(?:LIMIT|ORDER|FORMAT|COUNT)\b|$)/i, '');
setQueryText(s.trim()); runQuery(s.trim()); };
acts.appendChild(b);
}
const b = el('button', 'btn ghost sm', 'Start over');
b.onclick = resetQuery; acts.appendChild(b);
box.appendChild(acts);
return box;
}
/* EXPLAIN answers "how would you run this", so render the plan rather than
dropping the reader into raw JSON. The engine ignores FORMAT here — it has
no rows to render — which is worth saying out loud, because asking for
`EXPLAIN … FORMAT markdown` and getting no markdown tab looks like a bug. */
const PLAN_LABEL = { query_routing: 'routing', index_usage: 'index', estimated_cost: 'cost',
grain_type: 'reads', statement_type: 'statement', pipeline: 'pipeline', filters: 'filters' };
function qPlan(r) {
const plan = r.plan || {};
const wrap = el('div', 'planv');
const order = ['statement_type', 'query_routing', 'index_usage', 'estimated_cost',
'filters', 'pipeline', 'grain_type'];
const keys = order.filter(k => k in plan).concat(Object.keys(plan).filter(k => !order.includes(k)));
for (const k of keys) {
const v = plan[k];
const row = el('div', 'prow');
row.appendChild(el('b', null, PLAN_LABEL[k] || k.replace(/_/g, ' ')));
row.appendChild(el('span', null, Array.isArray(v) ? v.join(' · ') : String(v)));
wrap.appendChild(row);
}
if (/\bFORMAT\b/i.test(Q.text)) {
const n = el('div', 'pnote', 'FORMAT is ignored by EXPLAIN — a plan has no rows to render, '
+ 'so no rendered tab appears. Run the same query without EXPLAIN to see it formatted.');
wrap.appendChild(n);
}
return wrap;
}
function qCards(gs) {
const host = el('div'); host.id = 'qcards';
if (!gs.length) return qNoResults();
for (const g of gs) {
const f = rgFields(g), t = rgType(g);
const c = el('div', 'qcard');
const hd = el('div', 'hd');
const k = el('span', 'kind', t || 'grain');
k.style.color = 'var(' + (GRAIN_VAR[t] || '--cat-thing') + ')';
hd.appendChild(k);
const sp = el('div'); sp.style.flex = '1'; hd.appendChild(sp);
if (g.hlc) hd.appendChild(el('span', 'tiny', relTime(hlcMs(g.hlc))));
c.appendChild(hd);
c.appendChild(el('div', 'say', sentence({ type: t, fields: f })));
for (const [key, val] of Object.entries(f)) {
if (CARD_SKIP.has(key)) continue;
const row = el('div', 'kv');
row.appendChild(el('b', null, key.replace(/_/g, ' ')));
row.appendChild(el('span', valueClass(key, val), fmtValue(key, val)));
c.appendChild(row);
}
if (g.hash) {
const h = el('div', 'mono dev-only', g.hash.slice(0, 20));
c.appendChild(h);
c.style.cursor = 'pointer';
c.onclick = () => openPanel(g.hash);
}
host.appendChild(c);
}
return host;
}
/* Measure the *content*, not the box. Once a card is placed it is already
constrained to its grid rows, so reading the rendered height feeds the
previous answer back in — collapse to one row first, then measure
scrollHeight (overflow is hidden, so that is the natural height). */
function layoutMasonry() {
const grid = $('qcards'); if (!grid) return;
const rowH = 8, gutter = 16;
for (const c of grid.children) c.style.gridRowEnd = 'span 1';
void grid.offsetHeight;
for (const c of grid.children) {
c.style.gridRowEnd = 'span ' + Math.ceil((c.scrollHeight + gutter) / rowH);
}
}
function qTable(gs) {
if (!gs.length) return qNoResults();
const freq = new Map();
for (const g of gs) for (const k of Object.keys(rgFields(g))) freq.set(k, (freq.get(k) || 0) + 1);
/* A memory reads subject → relation → object; sorting columns by how often
a field appears put object before subject and inverted the sentence. Pin
the triple in reading order, then the rest by frequency. */
const LEAD = ['subject', 'relation', 'object'];
const rest = [...freq.entries()].sort((a, b) => b[1] - a[1]).map(e => e[0])
.filter(k => k !== 'type' && !LEAD.includes(k));
const cols = LEAD.filter(k => freq.has(k)).concat(rest).slice(0, 8);
const wrap = el('div'); wrap.style.overflowX = 'auto';
const tb = document.createElement('table'); tb.id = 'qtable';
const thead = document.createElement('thead'); const hr = document.createElement('tr');
hr.appendChild(el('th', null, 'kind'));
for (const c of cols) hr.appendChild(el('th', null, c.replace(/_/g, ' ')));
thead.appendChild(hr); tb.appendChild(thead);
const tbody = document.createElement('tbody');
for (const g of gs) {
const tr = document.createElement('tr');
tr.style.cursor = g.hash ? 'pointer' : 'default';
if (g.hash) tr.onclick = () => openPanel(g.hash);
const kd = el('td', null, rgType(g) || '');
kd.style.color = 'var(' + (GRAIN_VAR[rgType(g)] || '--cat-thing') + ')';
tr.appendChild(kd);
for (const c of cols) {
const v = rgFields(g)[c];
tr.appendChild(el('td', valueClass(c, v), fmtValue(c, v)));
}
tbody.appendChild(tr);
}
tb.appendChild(tbody); wrap.appendChild(tb);
return wrap;
}
function qFormats(r) {
const map = rType(r) === 'multi_formatted' ? (r.formats || {}) : { [r.format || 'text']: r.text || '' };
const names = Object.keys(map);
const wrap = el('div'); wrap.style.cssText = 'display:flex;flex-direction:column;gap:12px;padding-top:14px';
/* Which format to show now lives in Q.view. Test for the key, not the text:
a renderer that produced "" is still a format you asked for, and treating
it as missing made an empty tab impossible to select. */
const want = String(Q.view).startsWith('fmt:') ? String(Q.view).slice(4) : null;
Q.fmtTab = (want != null && want in map) ? want : names[0];
const text = map[Q.fmtTab] != null ? map[Q.fmtTab] : '';
if (!text) wrap.appendChild(el('div', 'pnote', 'The ' + Q.fmtTab + ' renderer returned nothing — '
+ 'there were no grains to render. The query ran fine; it simply matched nothing.'));
else wrap.appendChild(Q.fmtTab === 'json' ? jsonBlock(text) : el('pre', 'code', text));
const row = el('div'); row.style.cssText = 'display:flex;gap:9px';
const cp = el('button', 'btn ghost sm', 'Copy');
cp.onclick = () => copyText(text, Q.fmtTab);
const meta = FMT_META[Q.fmtTab] || ['txt', 'text/plain'];
const dl = el('button', 'btn ghost sm', 'Download .' + meta[0]);
dl.onclick = () => download('areev-result.' + meta[0], text, meta[1]);
row.appendChild(cp); row.appendChild(dl);
wrap.appendChild(row);
return wrap;
}
function qHistory(r) {
const wrap = el('div'); wrap.style.paddingTop = '10px';
for (const v of (r.versions || [])) {
const row = el('div', 'srow');
const f = v.fields || {};
row.appendChild(el('span', 't', typeof f.object === 'string' ? f.object : preview(f)));
row.appendChild(el('span', 'w', relTime(hlcMs(v.hlc))));
if (v.hash) { row.style.cursor = 'pointer'; row.onclick = () => openPanel(v.hash); }
wrap.appendChild(row);
}
return wrap;
}
function qGraphNote(gs) {
const wrap = el('div'); wrap.style.paddingTop = '14px';
wrap.appendChild(el('div', 'meta', 'Showing these ' + gs.length + ' results as a graph — '
+ 'scroll to zoom, drag the background to pan, drag a node to move it, click one to explore it.'));
const stage = el('div'); stage.id = 'qstage'; stage.style.marginTop = '10px';
const cv = document.createElement('canvas');
cv.id = 'qcanvas';
stage.appendChild(cv);
const zoom = el('div', 'float'); zoom.id = 'qzoom';
const btn = (txt, title, cls) => { const b = el('button', cls, txt); b.title = title; return b; };
const bOut = btn('−', 'zoom out'), bIn = btn('+', 'zoom in'), bFit = btn('Fit', 'fit to view', 'lbl');
zoom.append(bOut, bIn, bFit);
stage.appendChild(zoom);
wrap.appendChild(stage);
/* The canvas has no layout size until it is in the document. */
requestAnimationFrame(() => drawResultGraph(cv, gs, { zin: bIn, zout: bOut, fit: bFit }));
return wrap;
}
/* Assembly is Areev's differentiator — show where the budget went. */
function assembledSources(r) {
const wrap = el('div'); wrap.style.cssText = 'display:flex;flex-direction:column;gap:8px;padding:14px 0';
const cap = r.budget_limit || r.total_tokens || 1;
wrap.appendChild(el('span', 'sec-label', 'ASSEMBLY BUDGET · ' + (r.total_tokens || 0)
+ (r.budget_limit ? ' of ' + r.budget_limit : '') + ' tokens'));
for (const s of (r.sources || [])) {
const row = el('div'); row.style.cssText = 'display:flex;align-items:center;gap:12px';
const n = el('span', null, s.name || s.label || 'source');
n.style.cssText = 'width:150px;flex-shrink:0;font-size:13.5px;color:var(--ink)';
row.appendChild(n);
const track = el('div'); track.style.cssText = 'flex:1;height:8px;border-radius:4px;background:var(--raise)';
const fill = el('div');
const pct = Math.max(2, Math.round(100 * (s.tokens || 0) / cap));
fill.style.cssText = 'height:8px;border-radius:4px;background:var(--accent);width:' + pct + '%';
track.appendChild(fill); row.appendChild(track);
row.appendChild(el('span', 'tiny', (s.tokens || 0) + ' tok · ' + (s.grain_count != null ? s.grain_count + ' grains' : '')));
wrap.appendChild(row);
}
return wrap;
}
/* A compact, self-contained layout for result graphs. Deliberately separate
from the memory graph: that one owns rewind, depth and focus state, and
entangling the two would make both harder to reason about. */
function drawResultGraph(cv, gs, ctrls) {
const ctx = cv.getContext('2d');
const nodes = new Map(), links = [];
const add = n => { if (!nodes.has(n)) nodes.set(n, { id: n, x: (Math.random() - .5) * 260,
y: (Math.random() - .5) * 260, vx: 0, vy: 0, deg: 0 }); return nodes.get(n); };
for (const g of gs) {
const f = rgFields(g);
if (!f.subject || typeof f.object !== 'string' || !f.object) continue;
const a = add(f.subject), b = add(f.object);
a.deg++; b.deg++;
links.push({ a: f.subject, b: f.object, label: String(f.relation || '').replace(/_/g, ' ') });
}
const list = [...nodes.values()];
if (!list.length) { ctx.clearRect(0, 0, cv.width, cv.height); return; }
/* Settle once, up front: the layout is the answer's shape, and a graph that
keeps drifting under the cursor is harder to read than one that holds
still. Everything after this is view state — the node positions only move
when a person drags them. */
for (let step = 0; step < 320; step++) {
const k = Math.max(0.05, 1 - step / 320);
for (let i = 0; i < list.length; i++) for (let j = i + 1; j < list.length; j++) {
const a = list[i], b = list[j];
let dx = b.x - a.x, dy = b.y - a.y, d2 = dx * dx + dy * dy;
if (d2 < 1) { dx = Math.random(); dy = Math.random(); d2 = 1; }
if (d2 > 160000) continue;
const d = Math.sqrt(d2), f = (4200 * k) / d2;
a.vx -= dx / d * f; a.vy -= dy / d * f; b.vx += dx / d * f; b.vy += dy / d * f;
}
for (const l of links) {
const a = nodes.get(l.a), b = nodes.get(l.b);
const dx = b.x - a.x, dy = b.y - a.y, d = Math.max(1, Math.hypot(dx, dy));
const f = (d - 150) * 0.015 * k;
a.vx += dx / d * f; a.vy += dy / d * f; b.vx -= dx / d * f; b.vy -= dy / d * f;
}
for (const n of list) { n.vx += -n.x * 0.005 * k; n.vy += -n.y * 0.005 * k;
n.x += (n.vx *= 0.82); n.y += (n.vy *= 0.82); }
}
/* ── view state: one pan/zoom transform over settled world coordinates ── */
let scale = 1, tx = 0, ty = 0, W = 0, H = 0, hover = null, touched = false;
const radius = n => 12 + Math.min(16, n.deg * 3);
const MIN_SCALE = 0.2, MAX_SCALE = 4;
function fit() {
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (const n of list) { const r = radius(n);
x0 = Math.min(x0, n.x - r - 50); x1 = Math.max(x1, n.x + r + 50);
y0 = Math.min(y0, n.y - r - 26); y1 = Math.max(y1, n.y + r + 26); }
scale = Math.max(0.25, Math.min(1.3, Math.min(W / (x1 - x0), H / (y1 - y0))));
tx = W / 2 - (x0 + x1) / 2 * scale;
ty = H / 2 - (y0 + y1) / 2 * scale;
}
const toWorld = e => { const r = cv.getBoundingClientRect();
return { x: (e.clientX - r.left - tx) / scale, y: (e.clientY - r.top - ty) / scale }; };
/* Topmost first, so the node you see on top is the one you grab. */
const hit = p => { for (let i = list.length - 1; i >= 0; i--) { const n = list[i];
if (Math.hypot(n.x - p.x, n.y - p.y) <= radius(n) + 4) return n; } return null; };
function resize() {
W = cv.clientWidth; H = cv.clientHeight;
const dpr = window.devicePixelRatio || 1;
cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
}
/* Coalesce to one paint per frame — a trackpad emits wheel events far faster
than the display refreshes. */
let queued = false;
const redraw = () => { if (queued) return; queued = true;
requestAnimationFrame(() => { queued = false; draw(); }); };
/* Zoom about a point in canvas space, so the thing under the cursor (or the
middle, for the buttons) stays put. */
function zoomAt(px, py, factor) {
const next = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale * factor));
if (next === scale) return;
tx = px - (px - tx) * (next / scale);
ty = py - (py - ty) * (next / scale);
scale = next; touched = true; redraw();
}
function draw() {
const dpr = window.devicePixelRatio || 1;
const ink = cssVar('--ink'), line = cssVar('--line2'), accent = cssVar('--accent'),
well = cssVar('--well'), dim = cssVar('--dim');
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, W, H);
ctx.save();
ctx.translate(tx, ty); ctx.scale(scale, scale);
ctx.strokeStyle = line; ctx.lineWidth = 1.5;
for (const l of links) { const a = nodes.get(l.a), b = nodes.get(l.b);
ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke(); }
const halo = (t, x, y, font, fill) => { ctx.font = font; ctx.textAlign = 'center';
ctx.lineWidth = 3.5; ctx.lineJoin = 'round'; ctx.strokeStyle = well; ctx.strokeText(t, x, y);
ctx.fillStyle = fill; ctx.fillText(t, x, y); };
if (scale > 0.5) for (const l of links) {
const a = nodes.get(l.a), b = nodes.get(l.b);
const len = Math.hypot(b.x - a.x, b.y - a.y);
if (!l.label || len < 130) continue;
const nx = -(b.y - a.y) / len, ny = (b.x - a.x) / len;
halo(l.label, (a.x + b.x) / 2 + nx * 11, (a.y + b.y) / 2 + ny * 11 + 4, '12px ' + cssVar('--sans'), dim);
}
for (const n of list) {
const r = radius(n);
if (n.id === hover) { ctx.strokeStyle = accent; ctx.lineWidth = 2 / scale;
ctx.beginPath(); ctx.arc(n.x, n.y, r + 4, 0, 7); ctx.stroke(); }
ctx.fillStyle = accent; ctx.globalAlpha = 0.9;
ctx.beginPath(); ctx.arc(n.x, n.y, r, 0, 7); ctx.fill();
ctx.globalAlpha = 1;
halo(n.id.length > 22 ? n.id.slice(0, 21) + '…' : n.id, n.x, n.y + r + 16,
'600 13px ' + cssVar('--sans'), ink);
}
ctx.restore();
}
/* ── interaction ──
Drag listeners live on the window only while a gesture is running, so a
result graph that gets replaced (every re-render builds a new canvas)
leaves nothing behind. */
cv.addEventListener('mousedown', e => {
e.preventDefault();
const p = toWorld(e), n = hit(p);
let moved = false;
const drag = n ? { id: n.id, dx: n.x - p.x, dy: n.y - p.y } : null;
const pan = n ? null : { x: e.clientX - tx, y: e.clientY - ty };
if (pan) cv.classList.add('grabbing');
const move = ev => {
moved = moved || Math.abs(ev.clientX - e.clientX) + Math.abs(ev.clientY - e.clientY) > 3;
if (drag) { const q = toWorld(ev); const t = nodes.get(drag.id);
if (t) { t.x = q.x + drag.dx; t.y = q.y + drag.dy; } }
else { tx = ev.clientX - pan.x; ty = ev.clientY - pan.y; }
touched = true; redraw();
};
const up = () => {
window.removeEventListener('mousemove', move);
window.removeEventListener('mouseup', up);
cv.classList.remove('grabbing');
/* A click that never moved is a click, not a gesture. */
if (n && !moved) runQuery('RECALL facts WHERE subject = "' + n.id.replace(/"/g, '') + '" LIMIT 50');
};
window.addEventListener('mousemove', move);
window.addEventListener('mouseup', up);
});
cv.addEventListener('mousemove', e => {
const n = hit(toWorld(e));
const id = n ? n.id : null;
cv.style.cursor = n ? 'pointer' : 'grab';
if (id !== hover) { hover = id; redraw(); }
});
cv.addEventListener('mouseleave', () => { if (hover) { hover = null; redraw(); } });
cv.addEventListener('wheel', e => {
e.preventDefault();
const r = cv.getBoundingClientRect();
/* macOS trackpad pinch arrives as ctrl+wheel — finer steps, or it snaps. */
const f = e.ctrlKey ? Math.exp(-e.deltaY * 0.01) : (e.deltaY < 0 ? 1.12 : 0.89);
zoomAt(e.clientX - r.left, e.clientY - r.top, f);
}, { passive: false });
cv.addEventListener('dblclick', () => { touched = false; fit(); redraw(); });
if (ctrls) {
ctrls.zin.onclick = () => zoomAt(W / 2, H / 2, 1.2);
ctrls.zout.onclick = () => zoomAt(W / 2, H / 2, 1 / 1.2);
ctrls.fit.onclick = () => { touched = false; fit(); redraw(); };
}
/* Re-fit on resize only while the view is untouched: once someone has zoomed
somewhere deliberately, yanking them back to the whole graph is worse. */
const ro = new ResizeObserver(() => {
if (!cv.isConnected) { ro.disconnect(); return; }
if (!cv.clientWidth) return;
resize(); if (!touched) fit(); redraw();
});
ro.observe(cv);
resize(); fit(); draw();
}
/* ── menus: saved queries, templates, history, formats ── */
function openMenu(id, build) {
const m = $(id);
const wasOpen = !m.hidden;
for (const x of document.querySelectorAll('.menu')) x.hidden = true;
if (wasOpen) return;
m.textContent = '';
build(m);
m.hidden = false;
}
document.addEventListener('click', e => {
if (!e.target.closest('.menuwrap')) for (const x of document.querySelectorAll('.menu')) x.hidden = true;
});
function mi(parent, label, sub, fn) {
const d = el('div', 'mi');
d.appendChild(document.createTextNode(label));
if (sub) d.appendChild(el('small', null, sub));
d.onclick = fn;
parent.appendChild(d);
return d;
}
const FORMATS = ['sml', 'toon', 'markdown', 'json', 'yaml', 'csv', 'table', 'triples'];
function setFormat(spec) {
let t = $('qtext').value.trim().replace(/\s+FORMAT\s+(\[[^\]]*\]|preset\s+"[^"]*"|template\s+"[^"]*"|\w+)\s*$/i, '');
$('qtext').value = t + ' FORMAT ' + spec;
runQuery();
}
function buildFormatMenu(m) {
m.appendChild(el('div', 'sep', 'RENDER AS'));
for (const f of FORMATS) mi(m, f, null, () => setFormat(f));
m.appendChild(el('div', 'sep', 'SEVERAL AT ONCE'));
mi(m, 'json + markdown', 'FORMAT [json AS data, markdown AS readable]',
() => setFormat('[json AS data, markdown AS readable]'));
mi(m, 'sml + markdown', 'FORMAT [sml AS compact, markdown AS readable]',
() => setFormat('[sml AS compact, markdown AS readable]'));
}
function buildHistoryMenu(m) {
const h = histLoad();
if (!h.length) { m.appendChild(el('div', 'sep', 'NOTHING YET')); return; }
m.appendChild(el('div', 'sep', 'THIS BROWSER ONLY · ' + h.length));
for (const it of h.slice(0, 40)) {
mi(m, (it.s || 'ran') + ' · ' + relTime(it.at), it.q, () => runQuery(it.q));
}
const c = mi(m, 'Clear history', null, () => {
localStorage.removeItem(histKey()); toast('History cleared'); openMenu('histMenu', buildHistoryMenu);
});
c.style.color = 'var(--danger)';
}
/* DESCRIBE returns a free-form `info` blob; find the list wherever it is. */
function pickList(info) {
if (Array.isArray(info)) return info;
if (info && typeof info === 'object') {
for (const k of ['queries', 'templates', 'items', 'names', 'list']) if (Array.isArray(info[k])) return info[k];
for (const v of Object.values(info)) if (Array.isArray(v)) return v;
}
return [];
}
const itemName = it => typeof it === 'string' ? it : (it.name || it.id || JSON.stringify(it).slice(0, 40));
const itemDesc = it => typeof it === 'string' ? '' : (it.description || it.desc || '');
async function buildSavedMenu(m) {
if (!stmtSupported('DEFINE')) {
const n = el('div', 'mi', 'This build cannot save queries or templates — the memory file '
+ 'has no registry for them yet. DESCRIBE QUERIES still lists any that exist.');
n.style.cssText = 'color:var(--warn);white-space:normal;cursor:default';
m.appendChild(n);
}
m.appendChild(el('div', 'sep', 'SAVED QUERIES'));
const loading = el('div', 'mi', 'loading…'); m.appendChild(loading);
const [qs, ts] = await Promise.all([cal('DESCRIBE QUERIES'), cal('DESCRIBE TEMPLATES')]);
loading.remove();
const qlist = qs.ok ? pickList((qs.result || {}).info) : [];
if (!qlist.length) m.appendChild(el('div', 'mi', qs.ok ? 'none saved yet' : 'could not list'));
for (const it of qlist) {
const n = itemName(it);
mi(m, n, itemDesc(it) || 'RUN "' + n + '"', () => runQuery('RUN "' + n + '"'));
}
m.appendChild(el('div', 'sep', 'TEMPLATES'));
const tlist = ts.ok ? pickList((ts.result || {}).info) : [];
if (!tlist.length) m.appendChild(el('div', 'mi', ts.ok ? 'none defined yet' : 'could not list'));
for (const it of tlist) {
const n = itemName(it);
mi(m, n, 'FORMAT preset "' + n + '"', () => setFormat('preset "' + n + '"'));
}
}
async function saveCurrentQuery() {
const body = $('qtext').value.trim();
if (!body) { toast('Nothing to save'); return; }
if (!stmtSupported('DEFINE')) {
toast('This build cannot save queries — DEFINE is not in the engine’s supported statements');
return;
}
if (!canWrite()) { toast('Saving needs a console started with --token-env'); return; }
const name = window.prompt('Name this query (letters, numbers, spaces, _ and -):');
if (!name) return;
if (!QUERY_NAME_RE.test(name)) { toast('That name will not be accepted — start with a letter, max 64 chars'); return; }
const desc = window.prompt('Describe it (optional):') || '';
const stmt = 'DEFINE QUERY "' + name + '"'
+ (desc ? ' DESCRIPTION "' + desc.replace(/"/g, "'") + '"' : '')
+ ' AS { ' + body + ' }';
const res = await cal(stmt);
if (res.ok) toast('Saved — it lives in the memory file, not this browser');
else toast('Could not save: ' + (res.error || 'unknown') + (res.code ? ' [' + res.code + ']' : ''));
}
boot();
</script>