From 4204005ca32bd3294c081841183cdf2bf90fa268 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 9 Aug 2026 23:18:02 +1000 Subject: [PATCH 01/13] fix(webui): tighten configuration KV row spacing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each row in the read-only configuration view was ~45px tall but the text was only ~20px — empty space outweighed content by ~2:1, making the page hard to scan. The combined effect of `gap: var(--sp-2)` on the flex container and `padding: var(--sp-2) 0` on each row doubled the breathing room. Tables on the same page (Repositories, Providers) already use the target density; configuration rows now match them. Scope the override to `.cfg-section` descendants because the Workflows "Start work" form reuses `.cfg-rows` for its input fields (form.cfg-rows, no .cfg-row children) and would otherwise lose its 8px inter-field gap. The form is unaffected: the override only matches when an ancestor carries .cfg-section. Rows go from ~45px to ~25px, with the border carrying the visual rhythm instead of doubled padding. --- ui/dist/assets/index.css | 2 +- ui/src/settings/settings.css | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/ui/dist/assets/index.css b/ui/dist/assets/index.css index 6451f3cc1..cab20eb9d 100644 --- a/ui/dist/assets/index.css +++ b/ui/dist/assets/index.css @@ -1 +1 @@ -:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}@media (width<=1220px) and (width>=901px){.topbar{flex-wrap:wrap}.nav{border-radius:var(--radius-lg);flex-wrap:wrap;order:3;justify-content:center;width:100%;margin:0}}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;flex-wrap:nowrap;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{background:0 0;border:0;padding:0;overflow:hidden}.topbar-search-icon{display:none}.mobile-search-toggle{display:grid}.topbar-search input{opacity:0;pointer-events:none;width:0;transition:width var(--transition), opacity var(--transition);padding:0}.topbar-search.is-open,.topbar-search:focus-within{padding-right:var(--sp-2);border:1px solid var(--hairline);background:var(--surface-glass-strong)}.topbar-search.is-open input,.topbar-search:focus-within input{opacity:1;pointer-events:auto;width:min(9rem,34vw)}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-complete-actions{align-items:center;gap:var(--sp-2);display:flex}.setup-dismiss{width:28px;height:28px;font-size:var(--text-lg);line-height:1}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row{cursor:pointer}.task-expand{width:1.5rem;height:1.5rem;margin-right:var(--sp-2);color:var(--fg-muted);border:1px solid var(--border);font:inherit;cursor:pointer;background:0 0;border-radius:50%;padding:0;line-height:1}.task-expand:hover,.task-expand:focus-visible{color:var(--fg);border-color:var(--accent)}.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-actions{gap:var(--sp-1);white-space:nowrap;flex-wrap:wrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:180px;color:var(--danger);font-size:var(--text-xs);white-space:normal}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-detail-actions{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);padding-bottom:var(--sp-3);border-bottom:1px solid var(--hairline);display:flex}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}.table-scroll:has(.task-row){overflow:visible}.table:has(.task-row){display:block}.table:has(.task-row) tbody{display:block}.table-scroll>.table:has(.task-row){width:100%;min-width:0}.table:has(.task-row) thead{display:none}.task-row{gap:var(--sp-2) var(--sp-4);margin-bottom:var(--sp-3);padding:var(--sp-3);border:1px solid var(--hairline);border-radius:var(--radius-lg);background:var(--surface-glass);grid-template-columns:1fr 1fr;display:grid}.task-row td{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-1) 0;text-align:right;border:0;display:flex}.task-row td:before{content:attr(data-label);color:var(--fg-subtle);font-size:var(--text-xs);text-align:left;font-weight:500}.task-row td:nth-child(3),.task-row td:last-child{grid-column:1/-1}.task-row td:last-child{align-items:flex-start}.task-timeline-row,.task-timeline-row td{width:100%;display:block}.task-timeline-row td{margin:calc(var(--sp-2) * -1) 0 var(--sp-4);border-radius:0 0 var(--radius-lg) var(--radius-lg)}.task-detail-actions{flex-direction:column;align-items:flex-start}}@media (width<=480px){.task-row{grid-template-columns:1fr}.task-row td:nth-child(3),.task-row td:last-child{grid-column:auto}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-4) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.cfg-rows{gap:var(--sp-2);flex-direction:column;display:flex}.cfg-row{justify-content:space-between;align-items:baseline;gap:var(--sp-4);padding:var(--sp-2) 0;border-bottom:1px solid var(--border);display:flex}.cfg-row:last-child{border-bottom:0}.cfg-label{font-size:var(--text-sm);color:var(--fg-muted)}.cfg-value{font-size:var(--text-sm);color:var(--fg);text-align:right}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.chat-page{flex-direction:column;height:calc(100vh - 5rem);display:flex;overflow:hidden}.chat-page-content{flex-direction:column;flex:auto;min-height:0;display:flex;overflow:hidden}.chat-topbar{flex:none;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;display:flex}.chat-kicker,.chat-workspace-label{color:var(--fg-muted);letter-spacing:.12em;font-size:.68rem;font-weight:700}.chat-topbar-actions{align-items:center;gap:.55rem;display:flex}.chat-topbar-actions .chat-select{min-width:0;max-width:14rem}.chat-update-panel{border:1px solid var(--border);color:var(--fg-muted);border-radius:.75rem;flex:none;justify-content:space-between;align-items:center;gap:1rem;margin:0 0 .75rem;padding:.7rem .9rem;font-size:.8rem;display:flex}.chat-update-panel>div:first-child{gap:.2rem;display:grid}.chat-update-panel strong{color:var(--fg)}.chat-update-actions{flex-shrink:0;gap:.45rem;display:flex}.chat-dangerous-panel{border:1px solid color-mix(in srgb, var(--danger) 45%, var(--border));border-radius:.75rem;flex:none;margin:0 0 .75rem;padding:.8rem .9rem}.chat-dangerous-head,.chat-dangerous-controls,.chat-dangerous-pending{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-dangerous-head{margin-bottom:.7rem}.chat-dangerous-controls{flex-wrap:wrap;align-items:stretch}.chat-dangerous-controls>div{flex:18rem;gap:.45rem;display:flex}.chat-dangerous-input{background:var(--surface-hover);min-width:0;color:var(--fg);border:1px solid var(--border-strong);font:inherit;border-radius:.5rem;flex:1;padding:.5rem .65rem}.chat-dangerous-pending-list{gap:.45rem;margin-top:.75rem;display:grid}.chat-dangerous-pending{border-top:1px solid var(--border);color:var(--fg-muted);padding-top:.55rem;font-size:.8rem}.chat-layout{flex:auto;grid-template-columns:242px minmax(0,1fr);gap:.75rem;min-height:0;display:grid;overflow:hidden}.chat-sidebar,.chat-workspace{background:var(--surface);border:1px solid var(--border);border-radius:1rem}.chat-sidebar{padding:.8rem;overflow-y:auto}.chat-sidebar-head,.chat-toolbar,.chat-compose-actions{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-session-list{gap:.35rem;margin-top:1rem;display:grid}.chat-session{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.65rem;gap:.25rem;padding:.7rem;display:grid}.chat-session:hover,.chat-session.active{background:var(--surface-hover);color:var(--fg);border-color:var(--border-strong)}.chat-session span{font-size:.72rem}.chat-workspace{grid-template-rows:auto minmax(0,1fr) auto;min-width:0;display:grid;overflow:hidden}.chat-workspace-head{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;padding:.85rem 1.1rem;display:flex}.chat-session-tools{color:var(--fg-muted);margin-left:.6rem;font-size:.78rem;position:relative}.chat-session-tools summary{cursor:pointer}.chat-session-tool-list{z-index:2;background:var(--surface);border:1px solid var(--border-strong);border-radius:.65rem;flex-wrap:wrap;gap:.35rem;width:min(22rem,72vw);padding:.55rem;display:flex;position:absolute;top:calc(100% + .45rem);right:0;box-shadow:0 .7rem 2rem #0000004d}.chat-select{background:var(--surface-hover);color:var(--fg);border:1px solid var(--border-strong);border-radius:.5rem;padding:.5rem .65rem}.chat-transcript{align-content:start;gap:1rem;padding:1.25rem;display:grid;overflow:auto}.chat-empty-state{text-align:center;place-self:center;width:min(100%,40rem);padding:3rem 1rem}.chat-empty-mark{border:1px solid var(--border-strong);width:2.6rem;height:2.6rem;color:var(--accent);border-radius:.8rem;place-items:center;margin:0 auto 1rem;font-weight:700;display:grid}.chat-empty-state h2{letter-spacing:-.04em;margin:0;font-size:clamp(1.5rem,3vw,2.25rem)}.chat-empty-state p{color:var(--fg-muted);margin:.6rem 0 1.4rem}.chat-prompt-grid{flex-wrap:wrap;justify-content:center;gap:.5rem;display:flex}.chat-prompt{border:1px solid var(--border);background:var(--surface-hover);color:var(--fg-muted);cursor:pointer;border-radius:999px;padding:.55rem .75rem}.chat-prompt:hover{color:var(--fg);border-color:var(--border-strong)}.chat-bubble-row{display:flex}.chat-bubble-row.user{justify-content:flex-end}.chat-bubble{background:var(--surface-hover);border-radius:.85rem;max-width:min(78ch,86%);padding:.8rem 1rem;line-height:1.5}.chat-bubble-row.user .chat-bubble{background:color-mix(in srgb, var(--accent) 18%, var(--surface))}.chat-bubble-meta{color:var(--fg-muted);margin-bottom:.3rem;font-size:.7rem}.chat-bubble-text{white-space:pre-wrap;overflow-wrap:anywhere}.chat-bubble-text p{margin:0 0 .7rem}.chat-bubble-text p:last-child{margin-bottom:0}.chat-bubble-text h1,.chat-bubble-text h2,.chat-bubble-text h3{letter-spacing:-.02em;margin:.2rem 0 .6rem;line-height:1.2}.chat-bubble-text h1{font-size:1.25rem}.chat-bubble-text h2{font-size:1.1rem}.chat-bubble-text h3{font-size:1rem}.chat-bubble-text ul,.chat-bubble-text ol{margin:.25rem 0 .75rem;padding-left:1.35rem}.chat-bubble-text blockquote{border-left:3px solid var(--accent);color:var(--fg-muted);margin:.5rem 0;padding:.35rem .75rem}.chat-bubble-text code{background:color-mix(in srgb, var(--fg) 10%, transparent);border-radius:.3rem;padding:.1rem .3rem;font-size:.9em}.chat-bubble-text pre{border:1px solid var(--border);background:color-mix(in srgb, var(--surface) 75%, #000);border-radius:.5rem;margin:.6rem 0;padding:.75rem;overflow:auto}.chat-bubble-text pre code{background:0 0;padding:0}.chat-bubble-text a{color:var(--accent)}.chat-bubble-text table{border-collapse:collapse;width:100%;margin:.7rem 0;font-size:.92em}.chat-bubble-text th,.chat-bubble-text td{text-align:left;border:1px solid var(--border);padding:.45rem .6rem}.chat-bubble-text th{color:var(--fg);background:color-mix(in srgb, var(--surface) 70%, transparent);font-weight:700}.chat-compose{border-top:1px solid var(--border);padding:.85rem 1rem 1rem}.chat-composer-shell{background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:.9rem;padding:.7rem .8rem .55rem;position:relative}.chat-composer{resize:vertical;box-sizing:border-box;width:100%;min-height:3.3rem;color:var(--fg);font:inherit;background:0 0;border:0;padding:.25rem 0}.chat-composer:focus{outline:0}.chat-command-menu{z-index:3;background:var(--surface);border:1px solid var(--border-strong);border-radius:.7rem;gap:.15rem;max-height:18rem;padding:.35rem;display:grid;position:absolute;bottom:calc(100% - .25rem);left:.8rem;right:.8rem;overflow:auto;box-shadow:0 .7rem 2rem #0000004d}.chat-command-menu[hidden]{display:none}.chat-command-option{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.45rem;grid-template-columns:minmax(8rem,14rem) 1fr;align-items:center;gap:.65rem;padding:.5rem .6rem;display:grid}.chat-command-option:hover,.chat-command-option[aria-selected=true]{color:var(--fg);background:var(--surface-hover);border-color:var(--border)}.chat-command-option code{color:var(--fg)}.chat-compose-actions{margin-top:.55rem}.chat-hint,.chat-empty{color:var(--fg-muted);font-size:.78rem}.chat-command-help{color:var(--fg-muted);margin-right:auto;font-size:.78rem}.chat-command-help summary{cursor:pointer}.chat-command-list{min-width:min(34rem,70vw);max-width:40rem;padding-top:.4rem;line-height:1.45}.chat-command-item{grid-template-columns:minmax(10rem,16rem) 1fr;gap:.7rem;padding:.3rem 0;display:grid}.chat-command-item code{color:var(--fg)}@media (width<=760px){.chat-topbar,.chat-topbar-actions{flex-direction:column;align-items:flex-start}.chat-layout{grid-template-columns:1fr}.chat-sidebar{max-height:14rem;overflow:auto}}@media (width<=520px){.chat-update-panel{flex-direction:column;align-items:flex-start}} +:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}@media (width<=1220px) and (width>=901px){.topbar{flex-wrap:wrap}.nav{border-radius:var(--radius-lg);flex-wrap:wrap;order:3;justify-content:center;width:100%;margin:0}}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;flex-wrap:nowrap;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{background:0 0;border:0;padding:0;overflow:hidden}.topbar-search-icon{display:none}.mobile-search-toggle{display:grid}.topbar-search input{opacity:0;pointer-events:none;width:0;transition:width var(--transition), opacity var(--transition);padding:0}.topbar-search.is-open,.topbar-search:focus-within{padding-right:var(--sp-2);border:1px solid var(--hairline);background:var(--surface-glass-strong)}.topbar-search.is-open input,.topbar-search:focus-within input{opacity:1;pointer-events:auto;width:min(9rem,34vw)}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-complete-actions{align-items:center;gap:var(--sp-2);display:flex}.setup-dismiss{width:28px;height:28px;font-size:var(--text-lg);line-height:1}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row{cursor:pointer}.task-expand{width:1.5rem;height:1.5rem;margin-right:var(--sp-2);color:var(--fg-muted);border:1px solid var(--border);font:inherit;cursor:pointer;background:0 0;border-radius:50%;padding:0;line-height:1}.task-expand:hover,.task-expand:focus-visible{color:var(--fg);border-color:var(--accent)}.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-actions{gap:var(--sp-1);white-space:nowrap;flex-wrap:wrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:180px;color:var(--danger);font-size:var(--text-xs);white-space:normal}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-detail-actions{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);padding-bottom:var(--sp-3);border-bottom:1px solid var(--hairline);display:flex}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}.table-scroll:has(.task-row){overflow:visible}.table:has(.task-row){display:block}.table:has(.task-row) tbody{display:block}.table-scroll>.table:has(.task-row){width:100%;min-width:0}.table:has(.task-row) thead{display:none}.task-row{gap:var(--sp-2) var(--sp-4);margin-bottom:var(--sp-3);padding:var(--sp-3);border:1px solid var(--hairline);border-radius:var(--radius-lg);background:var(--surface-glass);grid-template-columns:1fr 1fr;display:grid}.task-row td{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-1) 0;text-align:right;border:0;display:flex}.task-row td:before{content:attr(data-label);color:var(--fg-subtle);font-size:var(--text-xs);text-align:left;font-weight:500}.task-row td:nth-child(3),.task-row td:last-child{grid-column:1/-1}.task-row td:last-child{align-items:flex-start}.task-timeline-row,.task-timeline-row td{width:100%;display:block}.task-timeline-row td{margin:calc(var(--sp-2) * -1) 0 var(--sp-4);border-radius:0 0 var(--radius-lg) var(--radius-lg)}.task-detail-actions{flex-direction:column;align-items:flex-start}}@media (width<=480px){.task-row{grid-template-columns:1fr}.task-row td:nth-child(3),.task-row td:last-child{grid-column:auto}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-4) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.cfg-rows{gap:var(--sp-2);flex-direction:column;display:flex}.cfg-row{justify-content:space-between;align-items:baseline;gap:var(--sp-4);padding:var(--sp-2) 0;border-bottom:1px solid var(--border);display:flex}.cfg-section .cfg-rows{gap:0}.cfg-section .cfg-row{padding:var(--sp-1) 0}.cfg-row:last-child{border-bottom:0}.cfg-label{font-size:var(--text-sm);color:var(--fg-muted)}.cfg-value{font-size:var(--text-sm);color:var(--fg);text-align:right}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.chat-page{flex-direction:column;height:calc(100vh - 5rem);display:flex;overflow:hidden}.chat-page-content{flex-direction:column;flex:auto;min-height:0;display:flex;overflow:hidden}.chat-topbar{flex:none;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;display:flex}.chat-kicker,.chat-workspace-label{color:var(--fg-muted);letter-spacing:.12em;font-size:.68rem;font-weight:700}.chat-topbar-actions{align-items:center;gap:.55rem;display:flex}.chat-topbar-actions .chat-select{min-width:0;max-width:14rem}.chat-update-panel{border:1px solid var(--border);color:var(--fg-muted);border-radius:.75rem;flex:none;justify-content:space-between;align-items:center;gap:1rem;margin:0 0 .75rem;padding:.7rem .9rem;font-size:.8rem;display:flex}.chat-update-panel>div:first-child{gap:.2rem;display:grid}.chat-update-panel strong{color:var(--fg)}.chat-update-actions{flex-shrink:0;gap:.45rem;display:flex}.chat-dangerous-panel{border:1px solid color-mix(in srgb, var(--danger) 45%, var(--border));border-radius:.75rem;flex:none;margin:0 0 .75rem;padding:.8rem .9rem}.chat-dangerous-head,.chat-dangerous-controls,.chat-dangerous-pending{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-dangerous-head{margin-bottom:.7rem}.chat-dangerous-controls{flex-wrap:wrap;align-items:stretch}.chat-dangerous-controls>div{flex:18rem;gap:.45rem;display:flex}.chat-dangerous-input{background:var(--surface-hover);min-width:0;color:var(--fg);border:1px solid var(--border-strong);font:inherit;border-radius:.5rem;flex:1;padding:.5rem .65rem}.chat-dangerous-pending-list{gap:.45rem;margin-top:.75rem;display:grid}.chat-dangerous-pending{border-top:1px solid var(--border);color:var(--fg-muted);padding-top:.55rem;font-size:.8rem}.chat-layout{flex:auto;grid-template-columns:242px minmax(0,1fr);gap:.75rem;min-height:0;display:grid;overflow:hidden}.chat-sidebar,.chat-workspace{background:var(--surface);border:1px solid var(--border);border-radius:1rem}.chat-sidebar{padding:.8rem;overflow-y:auto}.chat-sidebar-head,.chat-toolbar,.chat-compose-actions{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-session-list{gap:.35rem;margin-top:1rem;display:grid}.chat-session{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.65rem;gap:.25rem;padding:.7rem;display:grid}.chat-session:hover,.chat-session.active{background:var(--surface-hover);color:var(--fg);border-color:var(--border-strong)}.chat-session span{font-size:.72rem}.chat-workspace{grid-template-rows:auto minmax(0,1fr) auto;min-width:0;display:grid;overflow:hidden}.chat-workspace-head{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;padding:.85rem 1.1rem;display:flex}.chat-session-tools{color:var(--fg-muted);margin-left:.6rem;font-size:.78rem;position:relative}.chat-session-tools summary{cursor:pointer}.chat-session-tool-list{z-index:2;background:var(--surface);border:1px solid var(--border-strong);border-radius:.65rem;flex-wrap:wrap;gap:.35rem;width:min(22rem,72vw);padding:.55rem;display:flex;position:absolute;top:calc(100% + .45rem);right:0;box-shadow:0 .7rem 2rem #0000004d}.chat-select{background:var(--surface-hover);color:var(--fg);border:1px solid var(--border-strong);border-radius:.5rem;padding:.5rem .65rem}.chat-transcript{align-content:start;gap:1rem;padding:1.25rem;display:grid;overflow:auto}.chat-empty-state{text-align:center;place-self:center;width:min(100%,40rem);padding:3rem 1rem}.chat-empty-mark{border:1px solid var(--border-strong);width:2.6rem;height:2.6rem;color:var(--accent);border-radius:.8rem;place-items:center;margin:0 auto 1rem;font-weight:700;display:grid}.chat-empty-state h2{letter-spacing:-.04em;margin:0;font-size:clamp(1.5rem,3vw,2.25rem)}.chat-empty-state p{color:var(--fg-muted);margin:.6rem 0 1.4rem}.chat-prompt-grid{flex-wrap:wrap;justify-content:center;gap:.5rem;display:flex}.chat-prompt{border:1px solid var(--border);background:var(--surface-hover);color:var(--fg-muted);cursor:pointer;border-radius:999px;padding:.55rem .75rem}.chat-prompt:hover{color:var(--fg);border-color:var(--border-strong)}.chat-bubble-row{display:flex}.chat-bubble-row.user{justify-content:flex-end}.chat-bubble{background:var(--surface-hover);border-radius:.85rem;max-width:min(78ch,86%);padding:.8rem 1rem;line-height:1.5}.chat-bubble-row.user .chat-bubble{background:color-mix(in srgb, var(--accent) 18%, var(--surface))}.chat-bubble-meta{color:var(--fg-muted);margin-bottom:.3rem;font-size:.7rem}.chat-bubble-text{white-space:pre-wrap;overflow-wrap:anywhere}.chat-bubble-text p{margin:0 0 .7rem}.chat-bubble-text p:last-child{margin-bottom:0}.chat-bubble-text h1,.chat-bubble-text h2,.chat-bubble-text h3{letter-spacing:-.02em;margin:.2rem 0 .6rem;line-height:1.2}.chat-bubble-text h1{font-size:1.25rem}.chat-bubble-text h2{font-size:1.1rem}.chat-bubble-text h3{font-size:1rem}.chat-bubble-text ul,.chat-bubble-text ol{margin:.25rem 0 .75rem;padding-left:1.35rem}.chat-bubble-text blockquote{border-left:3px solid var(--accent);color:var(--fg-muted);margin:.5rem 0;padding:.35rem .75rem}.chat-bubble-text code{background:color-mix(in srgb, var(--fg) 10%, transparent);border-radius:.3rem;padding:.1rem .3rem;font-size:.9em}.chat-bubble-text pre{border:1px solid var(--border);background:color-mix(in srgb, var(--surface) 75%, #000);border-radius:.5rem;margin:.6rem 0;padding:.75rem;overflow:auto}.chat-bubble-text pre code{background:0 0;padding:0}.chat-bubble-text a{color:var(--accent)}.chat-bubble-text table{border-collapse:collapse;width:100%;margin:.7rem 0;font-size:.92em}.chat-bubble-text th,.chat-bubble-text td{text-align:left;border:1px solid var(--border);padding:.45rem .6rem}.chat-bubble-text th{color:var(--fg);background:color-mix(in srgb, var(--surface) 70%, transparent);font-weight:700}.chat-compose{border-top:1px solid var(--border);padding:.85rem 1rem 1rem}.chat-composer-shell{background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:.9rem;padding:.7rem .8rem .55rem;position:relative}.chat-composer{resize:vertical;box-sizing:border-box;width:100%;min-height:3.3rem;color:var(--fg);font:inherit;background:0 0;border:0;padding:.25rem 0}.chat-composer:focus{outline:0}.chat-command-menu{z-index:3;background:var(--surface);border:1px solid var(--border-strong);border-radius:.7rem;gap:.15rem;max-height:18rem;padding:.35rem;display:grid;position:absolute;bottom:calc(100% - .25rem);left:.8rem;right:.8rem;overflow:auto;box-shadow:0 .7rem 2rem #0000004d}.chat-command-menu[hidden]{display:none}.chat-command-option{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.45rem;grid-template-columns:minmax(8rem,14rem) 1fr;align-items:center;gap:.65rem;padding:.5rem .6rem;display:grid}.chat-command-option:hover,.chat-command-option[aria-selected=true]{color:var(--fg);background:var(--surface-hover);border-color:var(--border)}.chat-command-option code{color:var(--fg)}.chat-compose-actions{margin-top:.55rem}.chat-hint,.chat-empty{color:var(--fg-muted);font-size:.78rem}.chat-command-help{color:var(--fg-muted);margin-right:auto;font-size:.78rem}.chat-command-help summary{cursor:pointer}.chat-command-list{min-width:min(34rem,70vw);max-width:40rem;padding-top:.4rem;line-height:1.45}.chat-command-item{grid-template-columns:minmax(10rem,16rem) 1fr;gap:.7rem;padding:.3rem 0;display:grid}.chat-command-item code{color:var(--fg)}@media (width<=760px){.chat-topbar,.chat-topbar-actions{flex-direction:column;align-items:flex-start}.chat-layout{grid-template-columns:1fr}.chat-sidebar{max-height:14rem;overflow:auto}}@media (width<=520px){.chat-update-panel{flex-direction:column;align-items:flex-start}} diff --git a/ui/src/settings/settings.css b/ui/src/settings/settings.css index 0463a682e..9911fb617 100644 --- a/ui/src/settings/settings.css +++ b/ui/src/settings/settings.css @@ -15,6 +15,12 @@ margin-top: 0; } +/* The .cfg-rows / .cfg-row class pair is shared with the Workflows + "Start work" form (form.cfg-rows, no .cfg-row children). The form + needs the 8px gap and `var(--sp-2) 0` padding for breathing room + between inputs; the Configuration page reads as dense metadata where + the border alone carries the rhythm. Keep the general rules for the + form and override under .cfg-section. */ .cfg-rows { display: flex; flex-direction: column; @@ -30,6 +36,14 @@ border-bottom: 1px solid var(--border); } +.cfg-section .cfg-rows { + gap: 0; +} + +.cfg-section .cfg-row { + padding: var(--sp-1) 0; +} + .cfg-row:last-child { border-bottom: 0; } From b6f0aea93033a6326c3667f0e49b00cfdd5888b7 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 9 Aug 2026 23:29:52 +1000 Subject: [PATCH 02/13] refactor(daemon,webui): make Daemon.Cfg and webui.Server.Cfg reload-safe Daemon.Cfg, webui.Server.Cfg, and telegramSetup.Cfg were all held by value (or as a raw shared pointer in webui's case), so a future reload path could not swap the running configuration -- the consumers held frozen snapshots made at construction. This is the prerequisite for issue #348. Add config.Holder, a small RWMutex-backed snapshot holder: - Get returns a value copy under RLock; the copy shares its reference-type fields with the published snapshot, so a doc comment pins the immutability invariant (a published Config is immutable; reload constructs a fresh one). - Set replaces the snapshot under WLock. - Get is nil-safe; Set is not. Convert every consumer to read through the accessor. The convention 'cfg := h.Get() once per logical operation' is documented on the type so the next reader knows that inline d.Cfg.Get().Foo is a code smell (a Set could land between two consecutive Gets). Special cases: - webui.Server.Cfg: was *config.Config, a raw shared pointer read from handler goroutines. Convert to *config.Holder. The pre-existing 'cfg := s.Cfg' aliasing bug at api_config.go:295 (which was *trying* to copy but only copied the pointer) now becomes 'cfg := s.Cfg.Get()', which is the value copy the read-only view always wanted. - daemon_test.go: one test mutated d.Cfg.DiffCapLines in place, which the Holder forbids. Replace with the documented read-modify-write pattern (prev := d.Cfg.Get(); prev.X = Y; d.Cfg.Set(prev)). - telegramSetup.Cfg: matches the daemon's API for consistency even though setup runs before the daemon is alive. TaskContext.Cfg in internal/domain/workflow/workflow.go is deliberately NOT converted -- a task that starts under one config should finish under it, and a config changing between TDD and gate stages is a bug, not a feature. Snapshotted at dispatch, as before. Verified: go test ./... (61 packages), go vet, -race on internal/daemon and internal/config. --- cmd/archied/main.go | 10 ++-- cmd/archied/task_actions_test.go | 2 +- cmd/archied/telegram_setup.go | 36 +++++++----- internal/config/holder.go | 72 +++++++++++++++++++++++ internal/config/holder_test.go | 75 ++++++++++++++++++++++++ internal/daemon/daemon.go | 39 ++++++------ internal/daemon/daemon_test.go | 42 ++++++------- internal/webui/api_config.go | 8 ++- internal/webui/api_config_test.go | 10 ++-- internal/webui/api_logs.go | 2 +- internal/webui/api_setup.go | 12 ++-- internal/webui/api_skills.go | 5 +- internal/webui/api_tasks.go | 7 ++- internal/webui/api_tasks_actions_test.go | 8 +-- internal/webui/server.go | 6 +- 15 files changed, 251 insertions(+), 83 deletions(-) create mode 100644 internal/config/holder.go create mode 100644 internal/config/holder_test.go diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 8b1a78cb0..b4f10bb00 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -427,7 +427,7 @@ func run() int { Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature), }) } - web := &webui.Server{Store: st, Log: log, LogFeed: logFeed, TaskLogs: taskLogs, Cfg: &cfg, ConfigProvenance: configProvenance, Channels: channelManager, Events: bus} + web := &webui.Server{Store: st, Log: log, LogFeed: logFeed, TaskLogs: taskLogs, Cfg: config.NewHolder(cfg), ConfigProvenance: configProvenance, Channels: channelManager, Events: bus} web.ReloadChannel = func(ctx context.Context, id string) error { if id != "telegram" || restartTelegram == nil { return fmt.Errorf("channel reload unavailable") @@ -504,7 +504,7 @@ func run() int { requeue: st.Requeue, transition: st.Transition, }) - updateService := makeUpdateService(telegramSetup{Cfg: cfg}) + updateService := makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)}) web.WorkRequests = chatTasks // The dashboard is another gateway, not a second chat implementation. It @@ -528,7 +528,7 @@ func run() int { webRouter.InitSessions(chatSessionStore) configureTaskCommands(webRouter, chatTasks, chatController, defaultChatIdentity) webSetup := telegramSetup{ - Cfg: cfg, St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg, + Cfg: config.NewHolder(cfg), St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg, Personas: personas, ChatTasks: chatTasks, ChatController: chatController, ChatTaskLister: chatTaskListerAdapter{tasks: st.Tasks}, ChatTaskLogs: chatTaskLogReaderAdapter{ @@ -553,7 +553,7 @@ func run() int { // Multi-agent collaboration PRD phase C (docs/prds/multi-agent-collaboration.md). var startGateways []func() start, ok := setupTelegramGateway(ctx, telegramSetup{ - Cfg: cfg, CfgPath: *cfgPath, OverlayPath: *overlayPath, + Cfg: config.NewHolder(cfg), CfgPath: *cfgPath, OverlayPath: *overlayPath, St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg, Personas: personas, ChatTasks: chatTasks, ChatController: chatController, ChatTaskLister: chatTaskListerAdapter{tasks: st.Tasks}, @@ -950,7 +950,7 @@ func run() int { // via Yaegi is deferred to the container/agent runtime. d := &daemon.Daemon{ - Cfg: cfg, + Cfg: config.NewHolder(cfg), Store: st, Bus: bus, Forge: forgeClient, diff --git a/cmd/archied/task_actions_test.go b/cmd/archied/task_actions_test.go index bf503ea4a..e599c70ef 100644 --- a/cmd/archied/task_actions_test.go +++ b/cmd/archied/task_actions_test.go @@ -72,7 +72,7 @@ func TestDashboardAndChatAgreeOnTerminalStates(t *testing.T) { t.Fatalf("chat %s: %v", tc.action, actErr) } } else { - srv := &webui.Server{Store: st, Cfg: &config.Config{MaxRetries: 3}} + srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{MaxRetries: 3})} req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"`+tc.action+`"}`)) diff --git a/cmd/archied/telegram_setup.go b/cmd/archied/telegram_setup.go index 38dc86ab2..454d74512 100644 --- a/cmd/archied/telegram_setup.go +++ b/cmd/archied/telegram_setup.go @@ -28,7 +28,10 @@ import ( // chat gateway. Every field is intentionally explicit so the function // signature acts as a contract of what the gateway depends on. type telegramSetup struct { - Cfg config.Config + // Cfg is read once per setup function via Get(); the daemon is not + // running yet at this point, so the reload-safe Holder is mostly a + // formality, but matching the daemon's API keeps callers honest. + Cfg *config.Holder CfgPath string OverlayPath string St store.TaskStore @@ -57,19 +60,20 @@ type telegramSetup struct { // token is configured. It returns a start function (nil when no token // is configured) and ok=false to signal the caller must exit early. func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), ok bool) { - if s.Cfg.Chat.Telegram.TokenEnv == "" { + cfg := s.Cfg.Get() + if cfg.Chat.Telegram.TokenEnv == "" { return nil, true } - tgToken := os.Getenv(s.Cfg.Chat.Telegram.TokenEnv) + tgToken := os.Getenv(cfg.Chat.Telegram.TokenEnv) if tgToken == "" { - s.Log.Error("chat.telegram configured but token env var is empty", "env", s.Cfg.Chat.Telegram.TokenEnv) + s.Log.Error("chat.telegram configured but token env var is empty", "env", cfg.Chat.Telegram.TokenEnv) return nil, false } - if len(s.Cfg.Chat.Telegram.AllowedUserIDs) == 0 { + if len(cfg.Chat.Telegram.AllowedUserIDs) == 0 { s.Log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " + "Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.") } - tg := telegram.New(tgToken, "", "", s.Cfg.Chat.Telegram.AllowedUserIDs, s.Log) + tg := telegram.New(tgToken, "", "", cfg.Chat.Telegram.AllowedUserIDs, s.Log) if s.RegisterRestart != nil { s.RegisterRestart(tg.RequestRestart) } @@ -83,7 +87,7 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o } tg.Dangerous = s.Dangerous tg.ReleaseAnnouncements = &releaseannounce.Announcer{ - StatePath: releaseAnnouncementStatePath(s.Cfg.WorkDir, s.Cfg.BotUser), + StatePath: releaseAnnouncementStatePath(cfg.WorkDir, cfg.BotUser), Components: []releaseannounce.Component{ {ID: "gateway", Label: "THE GATEWAY", Version: gatewayVersion, ChangelogPath: packagedGatewayChangelogPath}, {ID: "runtime", Label: "THE RUNTIME", Version: runtimeVersion, ChangelogPath: packagedRuntimeChangelogPath}, @@ -120,15 +124,16 @@ func configureTelegramUpdates(tg *telegram.Gateway, s telegramSetup) { } func makeUpdateService(s telegramSetup) *releaseupdate.Service { - if len(s.Cfg.Chat.Telegram.UpdateCheckCommand) == 0 { + cfg := s.Cfg.Get() + if len(cfg.Chat.Telegram.UpdateCheckCommand) == 0 { return nil } updates := &releaseupdate.Service{ - Catalog: releaseupdate.CommandCatalog{Command: s.Cfg.Chat.Telegram.UpdateCheckCommand}, - StatePath: filepath.Join(s.Cfg.WorkDir, "telegram-update-deferrals.json"), + Catalog: releaseupdate.CommandCatalog{Command: cfg.Chat.Telegram.UpdateCheckCommand}, + StatePath: filepath.Join(cfg.WorkDir, "telegram-update-deferrals.json"), } - if len(s.Cfg.Chat.Telegram.UpdateInstallCommand) != 0 { - updates.Installer = releaseupdate.CommandInstaller{Command: s.Cfg.Chat.Telegram.UpdateInstallCommand} + if len(cfg.Chat.Telegram.UpdateInstallCommand) != 0 { + updates.Installer = releaseupdate.CommandInstaller{Command: cfg.Chat.Telegram.UpdateInstallCommand} } return updates } @@ -204,20 +209,21 @@ func newChatTurnRunner( sessionStore gateway.SessionStore, router *gateway.Router, ) *gateway.TurnRunner { + cfg := s.Cfg.Get() runner := gateway.NewTurnRunner(gateway.TurnRunnerConfig{ Router: router, Sessions: sessionStore, Models: s.ChatModels, Personas: s.Personas, - Model: newChatTurnModel(s.LLM, s.ToolReg, s.Cfg.Chat.MaxSteps, toolLimits(s.Cfg)), + Model: newChatTurnModel(s.LLM, s.ToolReg, cfg.Chat.MaxSteps, toolLimits(cfg)), TaskLister: s.ChatTaskLister, Tasks: s.ChatTasks, TaskLogs: s.ChatTaskLogs, TaskIdentity: s.DefaultChatIdentity, Bus: s.Bus, - BotUser: s.Cfg.BotUser, + BotUser: cfg.BotUser, Channel: channel, - Operator: s.Cfg.Chat.Operator, + Operator: cfg.Chat.Operator, Log: s.Log, }) if err := runner.Recover(context.Background()); err != nil && s.Log != nil { diff --git a/internal/config/holder.go b/internal/config/holder.go new file mode 100644 index 000000000..3c0535aed --- /dev/null +++ b/internal/config/holder.go @@ -0,0 +1,72 @@ +package config + +import "sync" + +// Holder publishes a Config snapshot to concurrent readers and lets a +// single writer swap the snapshot atomically. +// +// # Immutability invariant +// +// A published Config is immutable. The only way to update the published +// value is to call Set with a freshly constructed Config; in-place +// mutation of a published Config is a bug. The reason this matters: Get +// returns a value copy, but the copy shares its reference-type fields +// (Models, Providers, Repos, Identities, MCPServers, Extra, etc.) with +// the published snapshot. Mutating a map or slice through that copy +// mutates the published snapshot too, and any other reader sees the +// mutation outside the protection of the read lock. +// +// Reload paths (Loader.Reload, the file watcher, the UI PATCH handler) +// construct a fresh Config and call Set; they never mutate an existing +// one. Decode paths must finish constructing the new Config before Set +// is called; the existing decode.go:80 cfg.Extra[name] = value is fine +// because it runs pre-publish. +// +// # Convention +// +// Call Get once per logical operation and bind the result to a local: +// +// cfg := d.Cfg.Get() +// interval := cfg.PollInterval.Std() +// +// Inline accessors like d.Cfg.Get().Foo are a code smell: they may +// torn-read across a Set if a reload lands between two consecutive +// calls. With a single Get, every value in the local cfg came from +// the same published snapshot. +// +// # Why a pointer +// +// The zero value of Holder is not usable (the mutex is uninitialised); +// construct one with [NewHolder]. Holder is always passed by pointer +// because the embedded sync.RWMutex is itself a non-copyable type, and +// copying a Daemon that embeds a value Holder triggers go vet copylocks. +type Holder struct { + mu sync.RWMutex + cfg Config +} + +// NewHolder returns a Holder preloaded with c. +func NewHolder(c Config) *Holder { + return &Holder{cfg: c} +} + +// Get returns the currently published Config. The returned value is a +// shallow copy; the reference-type fields inside it are shared with the +// published snapshot and must not be mutated. See the type doc comment. +func (h *Holder) Get() Config { + if h == nil { + return Config{} + } + h.mu.RLock() + defer h.mu.RUnlock() + return h.cfg +} + +// Set replaces the published Config with c. The previous snapshot is +// dropped; c becomes the new published value and its reference-type +// fields become shared with all subsequent Get callers. +func (h *Holder) Set(c Config) { + h.mu.Lock() + defer h.mu.Unlock() + h.cfg = c +} diff --git a/internal/config/holder_test.go b/internal/config/holder_test.go new file mode 100644 index 000000000..943769c16 --- /dev/null +++ b/internal/config/holder_test.go @@ -0,0 +1,75 @@ +package config + +import ( + "sync" + "testing" +) + +func TestHolderGetReturnsConstructorValue(t *testing.T) { + c := Config{BotUser: "archie", PollInterval: Duration(1)} + h := NewHolder(c) + if got := h.Get(); got.BotUser != "archie" || got.PollInterval != Duration(1) { + t.Fatalf("Get() = %+v, want BotUser=archie PollInterval=1", got) + } +} + +func TestHolderSetReplaces(t *testing.T) { + h := NewHolder(Config{BotUser: "old"}) + h.Set(Config{BotUser: "new"}) + if got := h.Get(); got.BotUser != "new" { + t.Fatalf("after Set, Get().BotUser = %q, want \"new\"", got.BotUser) + } +} + +func TestHolderConcurrentGetSetIsRaceFree(t *testing.T) { + // The actual contract is that Get never tears: under -race, no data + // race, and every observed Config is a value some Set wrote. We do + // not assert "Get after my Set returns my value" because with N + // concurrent writers that property is not what Get guarantees -- a + // later Set can land between this writer's Set and this writer's + // Get. The race detector is the real check. + h := NewHolder(Config{BotUser: "v0"}) + + const writers = 8 + const iters = 1000 + + var wg sync.WaitGroup + for i := 0; i < writers; i++ { + wg.Add(2) + go func() { + defer wg.Done() + for j := 0; j < iters; j++ { + h.Set(Config{BotUser: "w"}) + } + }() + go func() { + defer wg.Done() + for j := 0; j < iters; j++ { + _ = h.Get() + } + }() + } + wg.Wait() +} + +func TestHolderGetIsNilSafe(t *testing.T) { + var h *Holder + if got := h.Get(); got.BotUser != "" { + t.Fatalf("nil Holder returned non-zero Config: %+v", got) + } +} + +func TestHolderSharedReferenceField(t *testing.T) { + // Documents the immutability invariant: maps inside the snapshot + // are shared with all Get callers. Mutating one is visible to all + // others -- the contract forbids this, but the test pins the + // current behaviour so any future change (e.g. copying maps) is + // a deliberate decision. + original := Config{Models: map[string]string{"builder": "anthropic/claude"}} + h := NewHolder(original) + snapshot := h.Get() + snapshot.Models["builder"] = "mutated" + if got := h.Get().Models["builder"]; got != "mutated" { + t.Fatalf("expected Get to see mutation through shared map, got %q", got) + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index b20cd4a9c..010e41948 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -47,7 +47,9 @@ type TaskBus interface { } type Daemon struct { - Cfg config.Config + // Cfg publishes the running configuration. Read through Cfg() so a + // reload swaps the published snapshot atomically. See config.Holder. + Cfg *config.Holder Store store.TaskStore Forge forge.Forge Trees *worktree.Manager @@ -197,7 +199,7 @@ func (d *Daemon) Startup(ctx context.Context) error { if err := d.Forge.AcceptInvitations(ctx); err != nil { d.Log.Warn("invitation sweep failed", "err", err) } - for _, r := range d.Cfg.Repos { + for _, r := range d.Cfg.Get().Repos { if err := d.Forge.VerifyPush(ctx, r.Owner, r.Name); err != nil { d.Log.Warn("repo not pushable -- tasks from it will fail", "repo", r.FullName(), "err", err) } @@ -213,7 +215,7 @@ func (d *Daemon) Run(ctx context.Context) error { if len(d.Identities) > 0 { return d.runIdentities(ctx) } - ticker := time.NewTicker(d.Cfg.PollInterval.Std()) + ticker := time.NewTicker(d.Cfg.Get().PollInterval.Std()) defer ticker.Stop() for { d.Cycle(ctx) @@ -248,7 +250,7 @@ func (d *Daemon) runIdentities(ctx context.Context) error { wg.Add(1) go func(id *IdentityRunner) { defer wg.Done() - interval := d.Cfg.PollInterval.Std() + interval := d.Cfg.Get().PollInterval.Std() if id.Cfg.PollInterval > 0 { interval = id.Cfg.PollInterval.Std() } @@ -267,7 +269,7 @@ func (d *Daemon) runIdentities(ctx context.Context) error { // One shared maintenance-and-drain loop. wg.Go(func() { - ticker := time.NewTicker(d.Cfg.PollInterval.Std()) + ticker := time.NewTicker(d.Cfg.Get().PollInterval.Std()) defer ticker.Stop() for { d.maintainAndDrain(ctx) @@ -288,7 +290,7 @@ func (d *Daemon) runIdentities(ctx context.Context) error { // drains or reconciles -- those are store-wide and run in the shared // maintainAndDrain loop. func (d *Daemon) pollForIdentity(ctx context.Context, id *IdentityRunner) { - cfg := configForIdentity(d.Cfg, id.Cfg) + cfg := configForIdentity(d.Cfg.Get(), id.Cfg) for _, repo := range id.Repos { issues := d.pollIssuesWithConfig(ctx, id.Forge, cfg, repo) for _, is := range issues { @@ -382,7 +384,7 @@ func (d *Daemon) Cycle(ctx context.Context) { } func (d *Daemon) cleanupExpiredStorage(ctx context.Context) { - ttl := d.Cfg.Containers.VolumeTTL.Std() + ttl := d.Cfg.Get().Containers.VolumeTTL.Std() if ttl <= 0 { return } @@ -399,7 +401,7 @@ func (d *Daemon) cleanupExpiredStorage(ctx context.Context) { // drainSQLite claims queued tasks from SQLite and dispatches them concurrently. func (d *Daemon) drainSQLite(ctx context.Context) { - dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency, d.allowConcurrentForTask) + dispatcher := newTaskDispatcher(d.Cfg.Get().Containers.MaxConcurrency, d.allowConcurrentForTask) for ctx.Err() == nil { task, err := d.Store.ClaimNext(ctx) if err != nil { @@ -418,7 +420,7 @@ func (d *Daemon) drainSQLite(ctx context.Context) { // requeued tasks (waiting_human approval, retry-parked) that didn't come // through a NATS publish. func (d *Daemon) drainNATS(ctx context.Context) { - dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency, d.allowConcurrentForTask) + dispatcher := newTaskDispatcher(d.Cfg.Get().Containers.MaxConcurrency, d.allowConcurrentForTask) for ctx.Err() == nil { msg, err := d.Tasks.Fetch(ctx) if err != nil && !errors.Is(err, eventbus.ErrNoMessage) { @@ -535,14 +537,14 @@ func (d *taskDispatcher) Wait() { } func (d *Daemon) poll(ctx context.Context) { - for _, repo := range d.Cfg.Repos { + for _, repo := range d.Cfg.Get().Repos { issues := d.pollIssues(ctx, repo) for _, is := range issues { labels := strings.Join(is.Labels, ",") if d.Tasks != nil { - d.pollNATS(ctx, d.Forge, d.Cfg, repo, is, labels, "") + d.pollNATS(ctx, d.Forge, d.Cfg.Get(), repo, is, labels, "") } else { - d.pollSQLite(ctx, d.Forge, d.Cfg, repo, is, labels, "") + d.pollSQLite(ctx, d.Forge, d.Cfg.Get(), repo, is, labels, "") } } } @@ -686,7 +688,7 @@ func (d *Daemon) processNATSTask(ctx context.Context, msg eventbus.Message) { // config, using the root forge client. Identity poll loops use // pollIssuesWithConfig with their own forge and config instead. func (d *Daemon) pollIssues(ctx context.Context, repo config.Repo) []forge.Issue { - return d.pollIssuesWithConfig(ctx, d.Forge, d.Cfg, repo) + return d.pollIssuesWithConfig(ctx, d.Forge, d.Cfg.Get(), repo) } // closeResolvedIssue closes the forge issue behind a finished task. @@ -1071,9 +1073,10 @@ func (d *Daemon) requestTaskRun(ctx context.Context, taskID int64, data []byte) } func (d *Daemon) containerEnv(task *store.Task) []string { + cfg := d.Cfg.Get() var env []string - env = append(env, "NATS_URL="+d.Cfg.NATS.URL) - if tokenEnv := d.Cfg.NATS.TokenEnv; tokenEnv != "" { + env = append(env, "NATS_URL="+cfg.NATS.URL) + if tokenEnv := cfg.NATS.TokenEnv; tokenEnv != "" { if token := os.Getenv(tokenEnv); token != "" { env = append(env, "NATS_TOKEN="+token) } @@ -1090,9 +1093,9 @@ func (d *Daemon) containerEnv(task *store.Task) []string { func (d *Daemon) executionFor(task *store.Task) (config.Config, agentexec.Runner) { if id := d.identityFor(task); id != nil { - return configForIdentity(d.Cfg, id.Cfg), id.Agent + return configForIdentity(d.Cfg.Get(), id.Cfg), id.Agent } - return d.Cfg, d.Agent + return d.Cfg.Get(), d.Agent } func (d *Daemon) configFor(task *store.Task) config.Config { @@ -1152,7 +1155,7 @@ func (d *Daemon) treesFor(task *store.Task) *worktree.Manager { // repoFor resolves task's repo config from the owning identity's repo // list when task.Identity is set, else the root Cfg.Repos. func (d *Daemon) repoFor(t *store.Task) (config.Repo, bool) { - repos := d.Cfg.Repos + repos := d.Cfg.Get().Repos if id := d.identityFor(t); id != nil { repos = id.Repos } diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index f220d6eb8..5948cb8bc 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -53,9 +53,9 @@ func (s *cleanupStorage) CleanupExpired(_ context.Context, ttl time.Duration) (i func TestCleanupExpiredStorageUsesConfiguredTTL(t *testing.T) { backend := &cleanupStorage{} d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Containers: config.ContainerConfig{VolumeTTL: config.Duration(6 * time.Hour)}, - }, + }), Storage: backend, Log: slog.New(slog.DiscardHandler), } @@ -252,12 +252,12 @@ func TestTaskDispatcherWaitsForRunningTasks(t *testing.T) { func TestDaemonAllowConcurrentForReadsRepoConfig(t *testing.T) { d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Repos: []config.Repo{ {Owner: "acme", Name: "widget", AllowConcurrent: true}, {Owner: "acme", Name: "todo"}, }, - }, + }), } if !d.allowConcurrentForTask(&store.Task{Owner: "acme", Repo: "widget"}) { @@ -279,10 +279,10 @@ func TestDaemonAllowConcurrentForReadsRepoConfig(t *testing.T) { func TestAllowConcurrentForTaskPrefersOwningIdentityRepo(t *testing.T) { shared := config.Repo{Owner: "acme", Name: "shared"} d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ // Root (legacy) list: shared is NOT opted in. Repos: []config.Repo{shared}, - }, + }), Identities: []*IdentityRunner{ { Name: "archie", @@ -305,12 +305,12 @@ func TestAllowConcurrentForTaskPrefersOwningIdentityRepo(t *testing.T) { func TestContainerEnvIncludesConfiguredNATSCredentials(t *testing.T) { t.Setenv("ARCHIE_NATS_SECRET", "test-nats-token") - d := &Daemon{Cfg: config.Config{ + d := &Daemon{Cfg: config.NewHolder(config.Config{ NATS: config.NATSConfig{ URL: "nats://nats.example:4222", TokenEnv: "ARCHIE_NATS_SECRET", }, - }} + })} got := d.containerEnv(nil) for _, want := range []string{ @@ -327,9 +327,9 @@ func TestContainerEnvUsesOnlyOwningIdentityProviderCredential(t *testing.T) { t.Setenv("ROOT_PROVIDER_KEY", "root-secret") t.Setenv("WORKER_PROVIDER_KEY", "worker-secret") d := &Daemon{ - Cfg: config.Config{Providers: map[string]config.Provider{ + Cfg: config.NewHolder(config.Config{Providers: map[string]config.Provider{ "openai": {Class: "openai", APIKeyEnv: "ROOT_PROVIDER_KEY"}, - }}, + }}), Identities: []*IdentityRunner{{ Name: "worker", Cfg: config.IdentityConfig{Name: "worker", Providers: map[string]config.Provider{ @@ -371,11 +371,11 @@ func daemonWithNATS(t *testing.T) (*Daemon, *store.Store, *arnats.Client) { s := store.OpenTest(t) d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Dispatch: config.Dispatch{Labels: map[string]string{ "parked": "archie:parked", "queued": "archie:queued", "dead": "archie:dead", }}, - }, + }), Store: s, Tasks: client, Log: slog.New(slog.DiscardHandler), @@ -532,7 +532,9 @@ func TestRunViaAgentParksOnRunError(t *testing.T) { func TestRunViaAgentSendsExpectedRequest(t *testing.T) { d, s, busClient := daemonWithNATS(t) - d.Cfg.DiffCapLines = 999 + prev := d.Cfg.Get() + prev.DiffCapLines = 999 + d.Cfg.Set(prev) ctx := context.Background() if _, err := s.EnqueueIssue(ctx, "acme", "widget", 3, "t", "b", "", ""); err != nil { @@ -677,7 +679,7 @@ func testDaemon(t *testing.T, maxRetries, _ int) (*Daemon, *store.Store, *testFo log := slog.New(slog.NewTextHandler(os.Stderr, nil)) return &Daemon{ - Cfg: cfg, + Cfg: config.NewHolder(cfg), Store: s, Forge: fg, // Reconcile paths call Trees.Cleanup, which dereferences the @@ -751,12 +753,12 @@ func TestExecutionForUsesIdentityConfigAgentAndProvider(t *testing.T) { rootAgent := &identityRunnerStub{} identityAgent := &identityRunnerStub{} d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Models: map[string]string{"builder": "root/model"}, Providers: map[string]config.Provider{ "root": {Class: "openai", APIKeyEnv: "ROOT_KEY"}, }, - }, + }), Agent: rootAgent, Identities: []*IdentityRunner{{ Name: "worker", Agent: identityAgent, @@ -814,7 +816,7 @@ func twoIdentityDaemon(t *testing.T) (d *Daemon, s *store.Store, rootFg, archieF repo := config.Repo{Owner: "acme", Name: "shared"} d = &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Dispatch: config.Dispatch{ Labels: map[string]string{ "queued": "archie:queued", @@ -822,7 +824,7 @@ func twoIdentityDaemon(t *testing.T) (d *Daemon, s *store.Store, rootFg, archieF }, }, Repos: []config.Repo{repo}, // root/legacy repo list -- must NOT be consulted for identity tasks - }, + }), Store: s, Forge: rootFg, // must NOT be called for identity-owned tasks Log: log, @@ -858,7 +860,7 @@ func TestAcknowledgeUsesOwningIdentityForgeNotRoot(t *testing.T) { is := forge.Issue{Number: 1, Title: "shared issue"} // archie's poll cycle acknowledges via its own forge client. - d.acknowledge(ctx, archieFg, d.Cfg, repo, is) + d.acknowledge(ctx, archieFg, d.Cfg.Get(), repo, is) if len(archieFg.stateLabels) != 0 { t.Fatalf("archie forge got %d state label calls, want 0", len(archieFg.stateLabels)) } @@ -945,7 +947,7 @@ func TestMaintainAndDrainReconcilesPRsInMultiIdentityMode(t *testing.T) { // issues assigned to the root bot user. func TestPollIssuesWithConfigUsesIdentityScopedDispatch(t *testing.T) { fg := &recordingForge{} - d := &Daemon{Cfg: config.Config{}, Log: slog.New(slog.DiscardHandler)} + d := &Daemon{Cfg: config.NewHolder(config.Config{}), Log: slog.New(slog.DiscardHandler)} // Root uses bot_user "root"; the identity uses "winter". Both default // to the assignee trigger. diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 2e795e1ed..88314cb4d 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -40,7 +40,7 @@ func (s *Server) handleChannels(w http.ResponseWriter, r *http.Request) { return } - chat := s.Cfg.Chat + chat := s.Cfg.Get().Chat views := []ChannelView{ telegramChannelView(chat.Telegram), webhookChannelView(chat.WebhookAddr), @@ -292,7 +292,11 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]any{}) return } - cfg := s.Cfg + // cfg := s.Cfg was a shared-pointer copy that aliased the live + // config. Under the Holder it becomes a value snapshot, which is + // what the read-only view always wanted -- every ConfigView field + // is read from this local. + cfg := s.Cfg.Get() view := ConfigView{ Identity: IdentityView{ diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index 7de93f8d5..3b54ca4dd 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -23,8 +23,8 @@ const ( fakeNATSToken = "nats-FAKESECRETTOKEN000" ) -func configWithFakeSecrets() *config.Config { - return &config.Config{ +func configWithFakeSecrets() *config.Holder { + return config.NewHolder(config.Config{ WorkDir: "/work/archie", SkillsDir: "/work/archie/.agents/skills", DBPath: "/work/archie/archie.db", @@ -58,7 +58,7 @@ func configWithFakeSecrets() *config.Config { Chat: config.ChatConfig{ Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}, }, - } + }) } // leakCandidates returns the set of fake secret strings a test should @@ -72,11 +72,11 @@ func leakCandidates() []string { func TestHandleConfigNeverLeaksSecrets(t *testing.T) { cases := []struct { name string - cfg *config.Config + cfg *config.Holder }{ {name: "populated config with secrets", cfg: configWithFakeSecrets()}, {name: "nil config", cfg: nil}, - {name: "zero-value config", cfg: &config.Config{}}, + {name: "zero-value config", cfg: config.NewHolder(config.Config{})}, } for _, tc := range cases { diff --git a/internal/webui/api_logs.go b/internal/webui/api_logs.go index 5bc2b4178..31ead1302 100644 --- a/internal/webui/api_logs.go +++ b/internal/webui/api_logs.go @@ -116,7 +116,7 @@ func (s *Server) logFile() string { if s.Cfg == nil { return "" } - return strings.TrimSpace(s.Cfg.Log.File) + return strings.TrimSpace(s.Cfg.Get().Log.File) } func splitCSV(v string) []string { diff --git a/internal/webui/api_setup.go b/internal/webui/api_setup.go index 7fb81e953..dd29cf311 100644 --- a/internal/webui/api_setup.go +++ b/internal/webui/api_setup.go @@ -35,18 +35,19 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) { // The operator's name is deployment data, configured once in [chat]. The // dashboard greets with it rather than hardcoding a name, which would be // wrong on every deployment but one. - operator := strings.TrimSpace(s.Cfg.Chat.Operator) + cfg := s.Cfg.Get() + operator := strings.TrimSpace(cfg.Chat.Operator) steps = append(steps, SetupStep{ Title: "Give Archie an identity", Detail: "The account it commits and comments as.", - Done: strings.TrimSpace(s.Cfg.BotUser) != "", + Done: strings.TrimSpace(cfg.BotUser) != "", }) steps = append(steps, SetupStep{ Title: "Connect a repository", Detail: "Archie polls these for issues assigned to it.", - Done: len(s.Cfg.Repos) > 0, + Done: len(cfg.Repos) > 0, }) steps = append(steps, SetupStep{ @@ -75,6 +76,7 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) { // Chat is disabled entirely when no channel token is set, so the presence of // one is the honest signal here. func (s *Server) hasChannel() bool { - return strings.TrimSpace(s.Cfg.Chat.Telegram.TokenEnv) != "" || - strings.TrimSpace(s.Cfg.Chat.WebhookAddr) != "" + cfg := s.Cfg.Get() + return strings.TrimSpace(cfg.Chat.Telegram.TokenEnv) != "" || + strings.TrimSpace(cfg.Chat.WebhookAddr) != "" } diff --git a/internal/webui/api_skills.go b/internal/webui/api_skills.go index 55c7ffdc1..4d8f8c5cc 100644 --- a/internal/webui/api_skills.go +++ b/internal/webui/api_skills.go @@ -28,7 +28,8 @@ func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) { return } - roots := skill.DefaultRoots(s.Cfg.WorkDir, s.Cfg.SkillsDir) + cfg := s.Cfg.Get() + roots := skill.DefaultRoots(cfg.WorkDir, cfg.SkillsDir) catalog, err := skill.CatalogRoots(roots...) if err != nil { http.Error(w, "failed to read skill catalogue: "+err.Error(), http.StatusInternalServerError) @@ -41,7 +42,7 @@ func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) { Name: entry.Name, Description: entry.Description, Workflow: entry.Workflow, - Source: skillSource(entry.Root, s.Cfg.WorkDir, s.Cfg.SkillsDir), + Source: skillSource(entry.Root, cfg.WorkDir, cfg.SkillsDir), }) } diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 549d2060f..ca5de4bc5 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -374,12 +374,13 @@ func (s *Server) maxRetriesFor(task *store.Task) int { if s.Cfg == nil { return 0 } - for _, repo := range s.Cfg.Repos { + cfg := s.Cfg.Get() + for _, repo := range cfg.Repos { if repo.Owner == task.Owner && repo.Name == task.Repo { - return repo.EffectiveMaxRetries(s.Cfg.MaxRetries) + return repo.EffectiveMaxRetries(cfg.MaxRetries) } } - return s.Cfg.MaxRetries + return cfg.MaxRetries } // closeRejectedIssue closes the forge issue behind a task the operator has diff --git a/internal/webui/api_tasks_actions_test.go b/internal/webui/api_tasks_actions_test.go index 36af47c1a..67aab008e 100644 --- a/internal/webui/api_tasks_actions_test.go +++ b/internal/webui/api_tasks_actions_test.go @@ -62,7 +62,7 @@ func actionServer(t *testing.T, status, parkReason string) (*Server, *store.Task srv.Issues = closer srv.Events = bus - srv.Cfg = &config.Config{MaxRetries: 3} + srv.Cfg = config.NewHolder(config.Config{MaxRetries: 3}) return srv, task, closer, bus, sub } @@ -128,7 +128,7 @@ func TestRetryEnforcesMaxRetries(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { srv, task, _, _, _ := actionServer(t, store.StatusParked, "it broke") - srv.Cfg = &config.Config{MaxRetries: tc.maxRetries} + srv.Cfg = config.NewHolder(config.Config{MaxRetries: tc.maxRetries}) ctx := t.Context() for range tc.priorCount { if err := srv.Store.IncrementRetryCount(ctx, task.ID); err != nil { @@ -203,7 +203,7 @@ func TestRejectDoesNotCloseAChatTaskIssue(t *testing.T) { ctx := t.Context() closer := &recordingCloser{} srv.Issues = closer - srv.Cfg = &config.Config{MaxRetries: 3} + srv.Cfg = config.NewHolder(config.Config{MaxRetries: 3}) task, err := srv.Store.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "") if err != nil { @@ -380,7 +380,7 @@ func TestTaskActionStoreFailureIs500(t *testing.T) { srv := &Server{ Store: &stubStore{TaskStore: base.Store, requeueErr: errors.New("db locked")}, Log: base.Log, - Cfg: &config.Config{MaxRetries: 3}, + Cfg: config.NewHolder(config.Config{MaxRetries: 3}), } w := postAction(t, srv, task.ID, "approve") if w.Code != http.StatusInternalServerError { diff --git a/internal/webui/server.go b/internal/webui/server.go index ef2b40f7b..be67998fa 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -32,8 +32,10 @@ type Server struct { Log *slog.Logger // Cfg backs the setup checklist and configuration views. Optional: the - // dashboard degrades to task data alone when it is nil. - Cfg *config.Config + // dashboard degrades to task data alone when it is nil. Held through a + // Holder so a reload swaps the snapshot atomically across handler + // goroutines that would otherwise race on the raw shared pointer. + Cfg *config.Holder // Workflows is the executable registry snapshot supplied by composition. Workflows []workflow.Definition From f544dd0978617eb7d657d6e04b49646a2c71538b Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 00:19:46 +1000 Subject: [PATCH 03/13] feat(config): SIGHUP-triggered reload with requires-restart warnings The daemon can now re-read its configuration on SIGHUP (or on a future in-process trigger) and republish it through the Holder, closing the first half of issue #348: 'config can change at runtime, safely, and can't brick the daemon.' Reload path: - cmd/archied/reload.go: ReloadController re-runs loader.Resolve on the same paths main.go passed at startup (Resolve is pure -- no reload state added to the loader). apply is called only with a Document that passed validation; a failed reload records the error and its timestamp and leaves the running config untouched. That Set-not-called-on-error property is the safety core and is pinned by TestReloadValidationFailureDoesNotApply. - SIGHUP listener in main.go runs reloadLoop(ctx, ch, controller, log); the loop is extracted as a testable seam (syscall.SIGHUP is Unix-only, fine given the Linux target). PollInterval is genuinely reloadable now, not just re-read: the three ticker sites (Run, per-identity goroutine, shared maintenance loop) re-read the interval each tick and Reset the ticker on change. A reloaded poll_interval takes effect on the next cycle. Diff-and-warn so an operator never has to read the source to know whether an edit took effect: changedNonReloadableFields compares the old and new snapshots against an allowlist of re-read fields (PollInterval, Repos, DiffCapLines, Budgets, Dispatch, and the Containers sub-fields VolumeTTL + MaxConcurrency). Anything else that changed logs Warn 'requires a restart'; a fully-applied reload logs Info. The allowlist is deliberate: a field added to Config later defaults to requires-restart, the safe direction. NATS split-brain closed: containerEnv now hands containers the endpoint the daemon's own client connected with at startup (Daemon.ConnectedNATS, captured at construction) instead of the live config, so a reloaded nats.url cannot point new containers at a server the daemon is not publishing on. A nats change is therefore classified requires-restart, and CLAUDE.md's 'hands its own nats.url verbatim' note is updated to the meaning it now has (same today, deliberately different after a reload). Validation guard: poll_interval <= 0 is rejected in validate.go beside the VolumeTTL guard. applyDefaults fills zero with 60s, so this fires on an explicit negative -- which would panic time.NewTicker/Reset at boot and, after the per-iteration reset, on a SIGHUP mid-run. Observability: config.ReloadStatus (last_error, last_error_at, last_reload_at) is recorded by the controller and surfaced in /api/config via Server.LastReload, so a stale running config is visible in the dashboard, not just the logs. Rendering waits for the UI step. Recovery hatch: --no-config-overlay flag plus ARCHIE_SKIP_CONFIG_OVERLAY=1 (configuration.SkipOverlay), logged at startup. No overlay source exists yet; the flag is the documented escape hatch the DB overlay (step 3 of #348) will consult. webui.Server.ConfigProvenance becomes atomic.Pointer so a reload can swap it via SetProvenance independently of Cfg; the accepted skew (new config alongside old provenance) is documented on the field. Verified: task check clean; -race on daemon, webui, cmd/archied, config, infrastructure/configuration. --- CHANGELOG.archied.md | 4 + CLAUDE.md | 12 +- cmd/archied/main.go | 40 +++- cmd/archied/reload.go | 145 +++++++++++++ cmd/archied/reload_test.go | 195 ++++++++++++++++++ internal/config/holder.go | 36 ++-- internal/config/holder_test.go | 17 +- internal/config/reload.go | 17 ++ internal/daemon/daemon.go | 59 ++++-- internal/daemon/daemon_test.go | 66 +++++- .../infrastructure/configuration/flags.go | 18 ++ .../configuration/flags_test.go | 17 ++ .../infrastructure/configuration/validate.go | 16 ++ .../configuration/validate_test.go | 16 +- internal/webui/api_config.go | 14 +- internal/webui/api_config_test.go | 77 +++++++ internal/webui/server.go | 22 +- 17 files changed, 723 insertions(+), 48 deletions(-) create mode 100644 cmd/archied/reload.go create mode 100644 cmd/archied/reload_test.go create mode 100644 internal/config/reload.go create mode 100644 internal/infrastructure/configuration/flags.go create mode 100644 internal/infrastructure/configuration/flags_test.go diff --git a/CHANGELOG.archied.md b/CHANGELOG.archied.md index c43ca2cba..6389878e4 100644 --- a/CHANGELOG.archied.md +++ b/CHANGELOG.archied.md @@ -1,5 +1,9 @@ # archied changelog +## [Unreleased] + +- feat(config): SIGHUP-triggered config reload with `--no-config-overlay` recovery flag + ## [1.6.0] - 2026-08-09 - feat(gateway): tool-approval gate, session tools for chat, and /delete command diff --git a/CLAUDE.md b/CLAUDE.md index 3cee303c4..d56ec54bc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,14 +58,22 @@ whether the jail is lifted together determine which filesystem those tools can reach; neither is something the code should assume. NATS and the per-task archie-agent containers are Docker regardless. -**The daemon hands agent containers its own `nats.url` verbatim** — see +**The daemon hands agent containers the NATS endpoint its own client connected with at startup** — see `containerEnv` in `internal/daemon/daemon.go`, which appends `NATS_URL=` from -`d.Cfg.NATS.URL`. That URL must therefore be reachable from wherever the daemon +`d.ConnectedNATS.URL`, captured at construction. That endpoint must therefore be reachable from wherever the daemon runs *and* from inside the containers. When the daemon is on the host, that means the compose network's gateway address, not the service name and not localhost. `docker-compose.yml` pins the subnet to `172.19.0.0/16` so the gateway address cannot drift when the network is recreated. +The two URLs are the same today and deliberately *not* the same after a +SIGHUP reload of `nats.url`: the daemon's own client is startup-built, so a +reload that pointed new containers at the new URL would launch them on a +server the daemon is not publishing on, and every task would park with +`ErrNoResponders`. Freezing the connected endpoint makes that divergence +impossible regardless of what the config says or who reloads it; a reloaded +`nats.url` is logged as a change that requires a restart. + **`containers.pull_policy` can only be `"missing"`** (the default) or `"always"`. `"always"` against a private registry answers 401, because the daemon sends no credentials to the Docker API. Refresh the agent image diff --git a/cmd/archied/main.go b/cmd/archied/main.go index b4f10bb00..a8e1ad231 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -313,6 +313,7 @@ func run() int { defaultCfg := filepath.Join(configHome(), "archie", "config.toml") cfgPath := flag.String("config", defaultCfg, "path to a TOML/YAML config file or configuration directory") overlayPath := flag.String("config-overlay", "", "path to a TOML/YAML overlay file or configuration directory applied on top of -config") + noConfigOverlay := flag.Bool("no-config-overlay", false, "ignore the runtime config overlay (recovery hatch: boots on file config alone)") once := flag.Bool("once", false, "run a single poll+process cycle and exit (systemd timer / testing)") requeue := flag.Int64("requeue", 0, "requeue a parked/waiting task by id (keeps its workflow), then exit unless -once is also set") flag.Parse() @@ -321,7 +322,11 @@ func run() int { log := slog.New(slog.NewJSONHandler(os.Stderr, nil)) - doc, err := configuration.New(log).Resolve(*cfgPath, *overlayPath) + loader := configuration.New(log) + if *noConfigOverlay || configuration.SkipOverlay() { + log.Info("runtime config overlay disabled (recovery hatch); booting on file config alone") + } + doc, err := loader.Resolve(*cfgPath, *overlayPath) if err != nil { fmt.Fprintln(os.Stderr, err) return 1 @@ -427,7 +432,8 @@ func run() int { Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature), }) } - web := &webui.Server{Store: st, Log: log, LogFeed: logFeed, TaskLogs: taskLogs, Cfg: config.NewHolder(cfg), ConfigProvenance: configProvenance, Channels: channelManager, Events: bus} + web := &webui.Server{Store: st, Log: log, LogFeed: logFeed, TaskLogs: taskLogs, Cfg: config.NewHolder(cfg), Channels: channelManager, Events: bus} + web.SetProvenance(configProvenance) web.ReloadChannel = func(ctx context.Context, id string) error { if id != "telegram" || restartTelegram == nil { return fmt.Errorf("channel reload unavailable") @@ -951,6 +957,7 @@ func run() int { d := &daemon.Daemon{ Cfg: config.NewHolder(cfg), + ConnectedNATS: cfg.NATS, Store: st, Bus: bus, Forge: forgeClient, @@ -973,6 +980,35 @@ func run() int { } web.TaskStopper = d + // SIGHUP re-loads the config from disk and republishes it. The apply + // closure swaps the daemon's Holder and the dashboard's provenance; + // the reload log warns about changed fields that require a restart, so + // an operator never has to read the source to find out whether their + // edit took effect. web.LastReload exposes the outcome to /api/config. + reloadController := newReloadController(loader, *cfgPath, *overlayPath, func(doc *configuration.Document) { + old := d.Cfg.Get() + d.Cfg.Set(doc.Config) + provenance := make([]webui.ConfigOrigin, 0, len(doc.Provenance.Origins)) + for _, origin := range doc.Provenance.Origins { + provenance = append(provenance, webui.ConfigOrigin{ + Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature), + }) + } + web.SetProvenance(provenance) + if fields := changedNonReloadableFields(old, doc.Config); len(fields) > 0 { + log.Warn("config reloaded; some changes require a restart", + "fields", fields, "paths", doc.Provenance.Paths()) + } else { + log.Info("config reloaded", "paths", doc.Provenance.Paths()) + } + }) + web.LastReload = reloadController.Status + + reloadCh := make(chan os.Signal, 1) + signal.Notify(reloadCh, syscall.SIGHUP) + defer signal.Stop(reloadCh) + go reloadLoop(ctx, reloadCh, reloadController, log) + // Give /cancel and /stop a handle on work already in flight. The // controller is built before the daemon exists, so the runtime is // attached here; gateways start further down, after d.Startup, so no diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go new file mode 100644 index 000000000..df6453f28 --- /dev/null +++ b/cmd/archied/reload.go @@ -0,0 +1,145 @@ +package main + +import ( + "context" + "log/slog" + "os" + "reflect" + "sync/atomic" + "time" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" +) + +// ReloadController re-runs the configuration load on demand and +// publishes the result through apply. A failed reload never publishes: +// apply is called only with a Document that passed validation, and the +// running config is left untouched on error. That "Set is not called on +// the error path" property is the safety core of the reload feature -- +// a bad file must leave the daemon running on the previous config. +type ReloadController struct { + loader *configuration.Loader + base string + overlay string + + // apply receives a freshly loaded, validated Document. It is the + // composition root's job to wire this to whatever owns the running + // config (the daemon's Holder, the dashboard's provenance). + apply func(*configuration.Document) + + status atomic.Pointer[config.ReloadStatus] +} + +func newReloadController(loader *configuration.Loader, base, overlay string, apply func(*configuration.Document)) *ReloadController { + c := &ReloadController{loader: loader, base: base, overlay: overlay, apply: apply} + c.status.Store(&config.ReloadStatus{}) + return c +} + +// Reload re-runs the configuration load. On validation failure it +// records the error in Status and returns it; apply is not called and +// the running configuration is unchanged. On success it calls apply +// with the fresh Document and records the reload time. +func (c *ReloadController) Reload() error { + doc, err := c.loader.Resolve(c.base, c.overlay) + if err != nil { + c.status.Store(&config.ReloadStatus{ + LastError: err.Error(), + LastErrorAt: time.Now().UTC().Format(time.RFC3339), + }) + return err + } + c.apply(doc) + c.status.Store(&config.ReloadStatus{ + LastReloadAt: time.Now().UTC().Format(time.RFC3339), + }) + return nil +} + +// Status returns the most recent reload outcome. +func (c *ReloadController) Status() config.ReloadStatus { + if p := c.status.Load(); p != nil { + return *p + } + return config.ReloadStatus{} +} + +// reloadLoop waits for a reload signal on ch and re-loads the config +// each time, until ctx is cancelled. A failed reload is logged and the +// running config is left untouched (see ReloadController.Reload). +func reloadLoop(ctx context.Context, ch <-chan os.Signal, c *ReloadController, log *slog.Logger) { + for { + select { + case <-ctx.Done(): + return + case <-ch: + if err := c.Reload(); err != nil { + log.Error("config reload failed; keeping running config", "err", err) + } + } + } +} + +// reloadableFields are the Config fields the daemon re-reads per cycle +// or per dispatched task, so a reload takes effect without a restart. +// This is deliberately an allowlist: a field added to Config later +// defaults to requires-restart, which is the safe direction and forces +// whoever adds it to decide deliberately. +var reloadableFields = map[string]bool{ + // Tickers reset on change (daemon.go Run / runIdentities). + "PollInterval": true, + // Poll loops re-read per cycle (daemon.go poll / pollForIdentity). + "Repos": true, + // Per-task snapshot: configFor -> executionFor -> d.Cfg.Get() at + // dispatch, carried by TaskConfig (config.go ForTask). + "DiffCapLines": true, + "Budgets": true, + // Dispatch is read per poll (daemon.go pollIssuesWithConfig switch) + // and carried per task like DiffCapLines. + "Dispatch": true, +} + +// reloadableSubFields are sub-fields of structs that are otherwise +// startup-built. VolumeTTL and MaxConcurrency are re-read per cycle +// (cleanupExpiredStorage, drainSQLite/drainNATS); everything else in +// Containers (Image, Enabled, MaxUptime, PullPolicy, Network) is frozen +// in the startup-built container pool. +var reloadableSubFields = map[string]map[string]bool{ + "Containers": {"VolumeTTL": true, "MaxConcurrency": true}, +} + +// changedNonReloadableFields compares old and new and returns the +// dotted names of top-level Config fields whose values differ and are +// not re-read per cycle. The reload log warns about these so the +// operator knows their edit did not take effect until a restart -- +// the alternative is an operator who believes a reloaded poll interval +// changed the forge token, and burns an hour discovering it did not. +func changedNonReloadableFields(old, new config.Config) []string { + var changed []string + ov, nv := reflect.ValueOf(old), reflect.ValueOf(new) + ot := reflect.TypeFor[config.Config]() + for i := 0; i < ot.NumField(); i++ { + f := ot.Field(i) + name := f.Name + if reloadableFields[name] { + continue + } + if subs, ok := reloadableSubFields[name]; ok && f.Type.Kind() == reflect.Struct { + for j := 0; j < f.Type.NumField(); j++ { + sub := f.Type.Field(j).Name + if subs[sub] { + continue + } + if !reflect.DeepEqual(ov.Field(i).Field(j).Interface(), nv.Field(i).Field(j).Interface()) { + changed = append(changed, name+"."+sub) + } + } + continue + } + if !reflect.DeepEqual(ov.Field(i).Interface(), nv.Field(i).Interface()) { + changed = append(changed, name) + } + } + return changed +} diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go new file mode 100644 index 000000000..b864e69d1 --- /dev/null +++ b/cmd/archied/reload_test.go @@ -0,0 +1,195 @@ +package main + +import ( + "context" + "log/slog" + "os" + "path/filepath" + "sync" + "syscall" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" +) + +// writeConfig writes a TOML config file. The minimal shape (bot_user + +// one repo) is the same fixture loader_test.go uses to satisfy +// validation. +func writeConfig(t *testing.T, path, body string) { + t.Helper() + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } +} + +func minimalConfigTOML(botUser string) string { + return "bot_user = \"" + botUser + "\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n" +} + +func invalidConfigTOML() string { + return "bot_user = \"widget\"\nagent = { mode = \"bogus-mode\" }\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n" +} + +func TestReloadAppliesAndPublishes(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + writeConfig(t, path, minimalConfigTOML("first")) + + loader := configuration.New(slog.New(slog.DiscardHandler)) + var published config.Config + controller := newReloadController(loader, path, "", func(doc *configuration.Document) { + published = doc.Config + }) + + if err := controller.Reload(); err != nil { + t.Fatalf("first reload: %v", err) + } + if published.BotUser != "first" { + t.Fatalf("published BotUser = %q, want first", published.BotUser) + } + + writeConfig(t, path, minimalConfigTOML("second")) + if err := controller.Reload(); err != nil { + t.Fatalf("second reload: %v", err) + } + if published.BotUser != "second" { + t.Fatalf("published BotUser = %q, want second", published.BotUser) + } + if st := controller.Status(); st.LastReloadAt == "" || st.LastError != "" { + t.Fatalf("Status after success = %+v, want LastReloadAt set and no error", st) + } +} + +// TestReloadValidationFailureDoesNotApply pins the safety property of +// the whole reload feature: a reload that fails validation must not +// publish. If apply were called on the error path, a bad file would +// half-apply or corrupt the running config. +func TestReloadValidationFailureDoesNotApply(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + writeConfig(t, path, minimalConfigTOML("widget")) + + loader := configuration.New(slog.New(slog.DiscardHandler)) + applied := 0 + controller := newReloadController(loader, path, "", func(*configuration.Document) { applied++ }) + + if err := controller.Reload(); err != nil { + t.Fatalf("first reload: %v", err) + } + if applied != 1 { + t.Fatalf("apply called %d times after successful reload, want 1", applied) + } + + writeConfig(t, path, invalidConfigTOML()) + err := controller.Reload() + if err == nil { + t.Fatal("reload with invalid config: expected an error") + } + if applied != 1 { + t.Fatalf("apply called %d times after failed reload, want still 1", applied) + } + if st := controller.Status(); st.LastError == "" || st.LastErrorAt == "" { + t.Fatalf("Status after failed reload = %+v, want LastError and LastErrorAt set", st) + } + + // A subsequent valid reload clears the error. + writeConfig(t, path, minimalConfigTOML("widget")) + if err := controller.Reload(); err != nil { + t.Fatalf("recovery reload: %v", err) + } + if st := controller.Status(); st.LastError != "" || st.LastReloadAt == "" { + t.Fatalf("Status after recovery = %+v, want no error and a reload time", st) + } +} + +func TestReloadLoopAppliesOnSignalAndStopsOnCancel(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + writeConfig(t, path, minimalConfigTOML("widget")) + + loader := configuration.New(slog.New(slog.DiscardHandler)) + applied := make(chan struct{}, 1) + controller := newReloadController(loader, path, "", func(*configuration.Document) { + applied <- struct{}{} + }) + + ctx, cancel := context.WithCancel(context.Background()) + ch := make(chan os.Signal, 1) + var wg sync.WaitGroup + wg.Go(func() { + reloadLoop(ctx, ch, controller, slog.New(slog.DiscardHandler)) + }) + + ch <- syscall.SIGHUP + select { + case <-applied: + case <-time.After(5 * time.Second): + t.Fatal("reload not applied after signal") + } + + cancel() + wg.Wait() +} + +func TestChangedNonReloadableFields(t *testing.T) { + base := config.Config{ + BotUser: "a", + MaxRetries: 3, + PollInterval: config.Duration(30 * time.Second), + Repos: []config.Repo{{Owner: "x", Name: "y"}}, + } + + // Unchanged -> empty. + if got := changedNonReloadableFields(base, base); len(got) != 0 { + t.Fatalf("unchanged: got %v, want []", got) + } + + // Reloadable-only changes (PollInterval, Repos, Budgets, Dispatch, + // DiffCapLines) -> empty. + reloadableOnly := base + reloadableOnly.PollInterval = config.Duration(60 * time.Second) + reloadableOnly.Repos = []config.Repo{{Owner: "x", Name: "z"}} + reloadableOnly.Budgets = config.Budgets{MaxSteps: 99} + reloadableOnly.Dispatch = config.Dispatch{Trigger: "label"} + reloadableOnly.DiffCapLines = 1234 + if got := changedNonReloadableFields(base, reloadableOnly); len(got) != 0 { + t.Fatalf("reloadable-only: got %v, want []", got) + } + + // A non-reloadable change is named. + nonReloadable := base + nonReloadable.BotUser = "b" + if got := changedNonReloadableFields(base, nonReloadable); len(got) != 1 || got[0] != "BotUser" { + t.Fatalf("BotUser change: got %v, want [BotUser]", got) + } + + // Containers sub-field granularity: Image change warns, MaxConcurrency + // and VolumeTTL changes do not. + c1 := base + c1.Containers = config.ContainerConfig{Image: "img1", MaxConcurrency: 2, VolumeTTL: config.Duration(24 * time.Hour)} + c2 := c1 + c2.Containers.Image = "img2" + if got := changedNonReloadableFields(c1, c2); len(got) != 1 || got[0] != "Containers.Image" { + t.Fatalf("Image change: got %v, want [Containers.Image]", got) + } + c3 := c1 + c3.Containers.MaxConcurrency = 4 + if got := changedNonReloadableFields(c1, c3); len(got) != 0 { + t.Fatalf("MaxConcurrency change: got %v, want []", got) + } + c4 := c1 + c4.Containers.VolumeTTL = config.Duration(48 * time.Hour) + if got := changedNonReloadableFields(c1, c4); len(got) != 0 { + t.Fatalf("VolumeTTL change: got %v, want []", got) + } + + // NATS is not reloadable: a URL change warns (the daemon's client is + // startup-built; containers get the frozen ConnectedNATS). + natsChanged := base + natsChanged.NATS = config.NATSConfig{URL: "nats://new:4222"} + if got := changedNonReloadableFields(base, natsChanged); len(got) != 1 || got[0] != "NATS" { + t.Fatalf("NATS change: got %v, want [NATS]", got) + } +} diff --git a/internal/config/holder.go b/internal/config/holder.go index 3c0535aed..1e2210d7e 100644 --- a/internal/config/holder.go +++ b/internal/config/holder.go @@ -22,17 +22,29 @@ import "sync" // is called; the existing decode.go:80 cfg.Extra[name] = value is fine // because it runs pre-publish. // -// # Convention +// # Torn reads across a field group // -// Call Get once per logical operation and bind the result to a local: +// A single field read inline (d.Cfg.Get().PollInterval) is fine: the +// value is a primitive, and any other reader sees a whole Config +// snapshot too. The risk is reading two or more fields of the same +// snapshot when a Set could land in between, so each field would +// derive from a different published version. When a logical operation +// needs multiple fields, bind the snapshot to a local first: // // cfg := d.Cfg.Get() -// interval := cfg.PollInterval.Std() +// if cfg.PollInterval > 0 { ... } +// for _, r := range cfg.Repos { ... } // -// Inline accessors like d.Cfg.Get().Foo are a code smell: they may -// torn-read across a Set if a reload lands between two consecutive -// calls. With a single Get, every value in the local cfg came from -// the same published snapshot. +// A single Get per logical operation is the contract; inline single- +// field access is not a smell. +// +// # Loud failures, not silent degradation +// +// Get panics on a nil receiver. A forgotten NewHolder that publishes +// the zero Holder is a programming error and should crash at the first +// consumer, not boot a daemon that runs forever with PollInterval 0 +// and empty Repos. Set has always panicked on nil for the same reason; +// the asymmetry was wrong. // // # Why a pointer // @@ -52,11 +64,10 @@ func NewHolder(c Config) *Holder { // Get returns the currently published Config. The returned value is a // shallow copy; the reference-type fields inside it are shared with the -// published snapshot and must not be mutated. See the type doc comment. +// published snapshot and must not be mutated. Get panics on a nil +// receiver; a forgotten NewHolder is a programming error. See the type +// doc comment. func (h *Holder) Get() Config { - if h == nil { - return Config{} - } h.mu.RLock() defer h.mu.RUnlock() return h.cfg @@ -64,7 +75,8 @@ func (h *Holder) Get() Config { // Set replaces the published Config with c. The previous snapshot is // dropped; c becomes the new published value and its reference-type -// fields become shared with all subsequent Get callers. +// fields become shared with all subsequent Get callers. Set panics on +// a nil receiver. func (h *Holder) Set(c Config) { h.mu.Lock() defer h.mu.Unlock() diff --git a/internal/config/holder_test.go b/internal/config/holder_test.go index 943769c16..4977df12e 100644 --- a/internal/config/holder_test.go +++ b/internal/config/holder_test.go @@ -34,17 +34,17 @@ func TestHolderConcurrentGetSetIsRaceFree(t *testing.T) { const iters = 1000 var wg sync.WaitGroup - for i := 0; i < writers; i++ { + for range writers { wg.Add(2) go func() { defer wg.Done() - for j := 0; j < iters; j++ { + for range iters { h.Set(Config{BotUser: "w"}) } }() go func() { defer wg.Done() - for j := 0; j < iters; j++ { + for range iters { _ = h.Get() } }() @@ -52,11 +52,14 @@ func TestHolderConcurrentGetSetIsRaceFree(t *testing.T) { wg.Wait() } -func TestHolderGetIsNilSafe(t *testing.T) { +func TestHolderGetPanicsOnNil(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Fatalf("Get on nil Holder did not panic") + } + }() var h *Holder - if got := h.Get(); got.BotUser != "" { - t.Fatalf("nil Holder returned non-zero Config: %+v", got) - } + _ = h.Get() } func TestHolderSharedReferenceField(t *testing.T) { diff --git a/internal/config/reload.go b/internal/config/reload.go new file mode 100644 index 000000000..6e2c770c3 --- /dev/null +++ b/internal/config/reload.go @@ -0,0 +1,17 @@ +package config + +// ReloadStatus is the outcome of the most recent config reload attempt, +// surfaced so the dashboard can tell the operator when the running +// config is stale: a reload that failed validation leaves the daemon +// running on the previous config, and that failure must be visible in +// the UI, not buried in logs. +type ReloadStatus struct { + // LastError is the validation error from the most recent failed + // reload attempt. Empty when the most recent attempt succeeded. + LastError string `json:"last_error,omitempty"` + // LastErrorAt is the RFC3339 UTC timestamp of the failed attempt. + LastErrorAt string `json:"last_error_at,omitempty"` + // LastReloadAt is the RFC3339 UTC timestamp of the most recent + // successful reload. Empty until the first reload. + LastReloadAt string `json:"last_reload_at,omitempty"` +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 010e41948..e4001e3a1 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -49,14 +49,21 @@ type TaskBus interface { type Daemon struct { // Cfg publishes the running configuration. Read through Cfg() so a // reload swaps the published snapshot atomically. See config.Holder. - Cfg *config.Holder - Store store.TaskStore - Forge forge.Forge - Trees *worktree.Manager - Agent agentexec.Runner - Bus *events.Bus - Workflows workflow.Registry - Log *slog.Logger + Cfg *config.Holder + // ConnectedNATS is the [nats] configuration the daemon's own client + // connected with at startup (the endpoint it publishes on). Container + // env is built from this, not from the live config, so a reload of + // nats.url/token_env cannot point new containers at a server the + // daemon is not publishing on. Zero value means NATS is not + // configured. + ConnectedNATS config.NATSConfig + Store store.TaskStore + Forge forge.Forge + Trees *worktree.Manager + Agent agentexec.Runner + Bus *events.Bus + Workflows workflow.Registry + Log *slog.Logger // Tasks is the optional message bus for task distribution. Nil means no // bus is configured; the existing SQLite ClaimNext flow is used. Tasks TaskBus @@ -215,7 +222,8 @@ func (d *Daemon) Run(ctx context.Context) error { if len(d.Identities) > 0 { return d.runIdentities(ctx) } - ticker := time.NewTicker(d.Cfg.Get().PollInterval.Std()) + interval := d.Cfg.Get().PollInterval.Std() + ticker := time.NewTicker(interval) defer ticker.Stop() for { d.Cycle(ctx) @@ -223,6 +231,12 @@ func (d *Daemon) Run(ctx context.Context) error { case <-ctx.Done(): return ctx.Err() case <-ticker.C: + // PollInterval may have been reloaded; reset the ticker so a + // change takes effect on the next cycle. + if iv := d.Cfg.Get().PollInterval.Std(); iv != interval { + interval = iv + ticker.Reset(iv) + } } } } @@ -262,6 +276,16 @@ func (d *Daemon) runIdentities(ctx context.Context) error { case <-ctx.Done(): return case <-ticker.C: + // The identity's own override is frozen (identity config is + // startup-built); the root fallback may have been reloaded. + iv := d.Cfg.Get().PollInterval.Std() + if id.Cfg.PollInterval > 0 { + iv = id.Cfg.PollInterval.Std() + } + if iv != interval { + interval = iv + ticker.Reset(iv) + } } } }(id) @@ -269,7 +293,8 @@ func (d *Daemon) runIdentities(ctx context.Context) error { // One shared maintenance-and-drain loop. wg.Go(func() { - ticker := time.NewTicker(d.Cfg.Get().PollInterval.Std()) + interval := d.Cfg.Get().PollInterval.Std() + ticker := time.NewTicker(interval) defer ticker.Stop() for { d.maintainAndDrain(ctx) @@ -277,6 +302,12 @@ func (d *Daemon) runIdentities(ctx context.Context) error { case <-ctx.Done(): return case <-ticker.C: + // PollInterval may have been reloaded; reset the ticker so a + // change takes effect on the next cycle. + if iv := d.Cfg.Get().PollInterval.Std(); iv != interval { + interval = iv + ticker.Reset(iv) + } } } }) @@ -1073,10 +1104,12 @@ func (d *Daemon) requestTaskRun(ctx context.Context, taskID int64, data []byte) } func (d *Daemon) containerEnv(task *store.Task) []string { - cfg := d.Cfg.Get() var env []string - env = append(env, "NATS_URL="+cfg.NATS.URL) - if tokenEnv := cfg.NATS.TokenEnv; tokenEnv != "" { + // The endpoint the daemon's own client connected with at startup, not + // the live config: a reloaded [nats] section must not point new + // containers at a server the daemon is not publishing on. + env = append(env, "NATS_URL="+d.ConnectedNATS.URL) + if tokenEnv := d.ConnectedNATS.TokenEnv; tokenEnv != "" { if token := os.Getenv(tokenEnv); token != "" { env = append(env, "NATS_TOKEN="+token) } diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index 5948cb8bc..9cf7f5dfb 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -305,12 +305,18 @@ func TestAllowConcurrentForTaskPrefersOwningIdentityRepo(t *testing.T) { func TestContainerEnvIncludesConfiguredNATSCredentials(t *testing.T) { t.Setenv("ARCHIE_NATS_SECRET", "test-nats-token") - d := &Daemon{Cfg: config.NewHolder(config.Config{ - NATS: config.NATSConfig{ - URL: "nats://nats.example:4222", - TokenEnv: "ARCHIE_NATS_SECRET", - }, - })} + // ConnectedNATS is the endpoint the daemon's own client connected with + // at startup; containerEnv deliberately reads this, not the live Cfg, + // so a reload of nats.url cannot point new containers at a server the + // daemon is not publishing on. + natsCfg := config.NATSConfig{ + URL: "nats://nats.example:4222", + TokenEnv: "ARCHIE_NATS_SECRET", + } + d := &Daemon{ + Cfg: config.NewHolder(config.Config{}), + ConnectedNATS: natsCfg, + } got := d.containerEnv(nil) for _, want := range []string{ @@ -595,6 +601,54 @@ type testForge struct { prStates map[int]string } +// pollingForge records every repo the daemon asks about, so a test can +// observe which repos are being polled -- including that a repo removed +// by a reload stops new intake. +type pollingForge struct { + testForge + asked []string +} + +func (f *pollingForge) AssignedIssues(_ context.Context, owner, repo, _ string) ([]forge.Issue, error) { + f.asked = append(f.asked, owner+"/"+repo) + return nil, nil +} + +// TestRemovingRepoStopsNewIntake pins the reload behaviour: when a repo +// vanishes from the config, the next poll cycle no longer asks the forge +// about it. In-flight tasks are unaffected because their TaskContext.Cfg +// is a value snapshot taken at dispatch -- the type system guarantees +// that half; this test covers the intake half. +func TestRemovingRepoStopsNewIntake(t *testing.T) { + fg := &pollingForge{} + d := &Daemon{ + Cfg: config.NewHolder(config.Config{ + BotUser: "archie", + Repos: []config.Repo{{Owner: "acme", Name: "widget"}}, + Dispatch: config.Dispatch{Trigger: "assignee"}, + }), + Forge: fg, + Log: slog.New(slog.DiscardHandler), + } + + ctx := context.Background() + d.poll(ctx) + if len(fg.asked) != 1 || fg.asked[0] != "acme/widget" { + t.Fatalf("after first poll, asked = %v, want [acme/widget]", fg.asked) + } + + // Simulate a reload that drops the repo: the polling loop re-reads + // d.Cfg.Get().Repos fresh, so the next poll asks about nothing. + d.Cfg.Set(config.Config{ + BotUser: "archie", + Dispatch: config.Dispatch{Trigger: "assignee"}, + }) + d.poll(ctx) + if len(fg.asked) != 1 { + t.Fatalf("after reload, asked = %v, want unchanged [acme/widget] (no new intake)", fg.asked) + } +} + type closeIssueCall struct { owner, repo string number int diff --git a/internal/infrastructure/configuration/flags.go b/internal/infrastructure/configuration/flags.go new file mode 100644 index 000000000..e91149e93 --- /dev/null +++ b/internal/infrastructure/configuration/flags.go @@ -0,0 +1,18 @@ +package configuration + +import "os" + +// envSkipOverlay names the environment variable that disables runtime +// config overlays. It is the recovery hatch for an overlay write that +// leaves the daemon unable to boot: set ARCHIE_SKIP_CONFIG_OVERLAY=1 +// and the daemon boots from file config alone. The same switch exists +// as the --no-config-overlay flag on archied. +const envSkipOverlay = "ARCHIE_SKIP_CONFIG_OVERLAY" + +// SkipOverlay reports whether runtime config overlays are disabled via +// ARCHIE_SKIP_CONFIG_OVERLAY=1. The overlay source (a later step of the +// config-editing work) consults this before loading; cmd/archied +// OR-s its --no-config-overlay flag with this at startup. +func SkipOverlay() bool { + return os.Getenv(envSkipOverlay) == "1" +} diff --git a/internal/infrastructure/configuration/flags_test.go b/internal/infrastructure/configuration/flags_test.go new file mode 100644 index 000000000..06aa4dc28 --- /dev/null +++ b/internal/infrastructure/configuration/flags_test.go @@ -0,0 +1,17 @@ +package configuration + +import "testing" + +func TestSkipOverlayEnvSet(t *testing.T) { + t.Setenv(envSkipOverlay, "1") + if !SkipOverlay() { + t.Fatal("SkipOverlay() = false with env set to 1") + } +} + +func TestSkipOverlayEnvUnset(t *testing.T) { + t.Setenv(envSkipOverlay, "") + if SkipOverlay() { + t.Fatal("SkipOverlay() = true with env empty") + } +} diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index 75e63bb98..86d99d6de 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -72,9 +72,25 @@ func validate(cfg *config.Config) error { } else if err := validateSingleIdentity(cfg); err != nil { return err } + if err := validatePollInterval(cfg); err != nil { + return err + } return validateContainers(cfg) } +// validatePollInterval rejects a non-positive poll interval. +// applyDefaults fills PollInterval == 0 with the default, so this only +// fires on an explicit negative value -- which would panic +// time.NewTicker/Reset in the daemon's poll loops, at boot and (worse) +// on a SIGHUP reload mid-run, when the edit that broke it is no longer +// fresh in the operator's mind. +func validatePollInterval(cfg *config.Config) error { + if cfg.PollInterval <= 0 { + return fmt.Errorf("%w: poll_interval must be positive", ErrInvalidInput) + } + return nil +} + func validateAgent(cfg *config.Config) error { if !oneOf(cfg.Agent.Mode, agentModes) { return fmt.Errorf("%w: agent.mode %q (want %s)", ErrInvalidInput, cfg.Agent.Mode, list(agentModes)) diff --git a/internal/infrastructure/configuration/validate_test.go b/internal/infrastructure/configuration/validate_test.go index 5bc26bd5e..ac3013158 100644 --- a/internal/infrastructure/configuration/validate_test.go +++ b/internal/infrastructure/configuration/validate_test.go @@ -4,6 +4,7 @@ import ( "errors" "os" "testing" + "time" "github.com/samcharles93/archie-core/internal/config" ) @@ -14,8 +15,9 @@ import ( // have supplied. func minimalValidConfig() config.Config { return config.Config{ - BotUser: "archie-bot", - Agent: config.Agent{Mode: "inprocess"}, + BotUser: "archie-bot", + PollInterval: config.Duration(60 * time.Second), + Agent: config.Agent{Mode: "inprocess"}, Dispatch: config.Dispatch{ Trigger: "assignee", }, @@ -61,6 +63,16 @@ func TestValidate_RejectsTheSameProblemsAsLoaderLoad(t *testing.T) { mutate: func(cfg *config.Config) { cfg.Forge.Type = "not-a-real-forge" }, wantErr: true, }, + { + name: "negative poll_interval", + mutate: func(cfg *config.Config) { cfg.PollInterval = config.Duration(-5 * time.Second) }, + wantErr: true, + }, + { + name: "zero poll_interval", + mutate: func(cfg *config.Config) { cfg.PollInterval = 0 }, + wantErr: true, + }, { name: "provider base_url carries userinfo", mutate: func(cfg *config.Config) { diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 88314cb4d..6fb16cb23 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -195,6 +195,9 @@ type ConfigView struct { Containers ContainersView `json:"containers"` Web WebView `json:"web"` Provenance []ConfigOrigin `json:"provenance"` + // Reload reports the most recent config reload outcome. Omitted when + // the reload status is unavailable. + Reload *config.ReloadStatus `json:"reload,omitempty"` } // IdentityView is who Archie is on the forge -- never the token that @@ -298,6 +301,11 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { // is read from this local. cfg := s.Cfg.Get() + var provenance []ConfigOrigin + if p := s.ConfigProvenance.Load(); p != nil { + provenance = append([]ConfigOrigin(nil), (*p)...) + } + view := ConfigView{ Identity: IdentityView{ BotUser: cfg.BotUser, @@ -338,7 +346,11 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { Network: cfg.Containers.Network, }, Web: WebView{Listen: cfg.Web.Listen}, - Provenance: append([]ConfigOrigin(nil), s.ConfigProvenance...), + Provenance: provenance, + } + if s.LastReload != nil { + rs := s.LastReload() + view.Reload = &rs } writeJSON(w, view) diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index 3b54ca4dd..918f043aa 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -146,6 +146,83 @@ func TestHandleConfigSafeFieldsPresent(t *testing.T) { } } +// TestHandleConfigIncludesReloadStatus proves a failed reload is surfaced +// in /api/config so the operator can see the running config is stale +// without reading logs. +func TestHandleConfigIncludesReloadStatus(t *testing.T) { + srv := newTestServer(t) + srv.Cfg = configWithFakeSecrets() + srv.LastReload = func() config.ReloadStatus { + return config.ReloadStatus{ + LastError: "poll_interval must be positive", + LastErrorAt: "2026-08-09T12:00:00Z", + } + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + var got ConfigView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if got.Reload == nil { + t.Fatal("Reload = nil, want the failed-reload status") + } + if got.Reload.LastError != "poll_interval must be positive" { + t.Errorf("Reload.LastError = %q", got.Reload.LastError) + } + if got.Reload.LastErrorAt != "2026-08-09T12:00:00Z" { + t.Errorf("Reload.LastErrorAt = %q", got.Reload.LastErrorAt) + } +} + +// TestHandleConfigOmitsReloadStatusWhenUnavailable pins that the reload +// field is absent (not empty) when the server has no reload seam wired. +func TestHandleConfigOmitsReloadStatusWhenUnavailable(t *testing.T) { + srv := newTestServer(t) + srv.Cfg = configWithFakeSecrets() + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + var got ConfigView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if got.Reload != nil { + t.Errorf("Reload = %+v, want nil (no reload seam)", got.Reload) + } +} + +// TestSetProvenancePublishesForConfigView proves a reloaded provenance +// list reaches /api/config. +func TestSetProvenancePublishesForConfigView(t *testing.T) { + srv := newTestServer(t) + srv.Cfg = configWithFakeSecrets() + srv.SetProvenance([]ConfigOrigin{ + {Path: "/etc/archie/config.toml", Role: "main", Layer: "base"}, + {Path: "/etc/archie/conf.d/docker.yaml", Role: "extra", Layer: "overlay", Feature: "docker"}, + }) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + var got ConfigView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got.Provenance) != 2 { + t.Fatalf("Provenance = %+v, want 2 origins", got.Provenance) + } + if got.Provenance[0].Path != "/etc/archie/config.toml" { + t.Errorf("Provenance[0].Path = %q", got.Provenance[0].Path) + } +} + func TestHandleChannelsReportsConfiguredState(t *testing.T) { srv := newTestServer(t) srv.Cfg = configWithFakeSecrets() diff --git a/internal/webui/server.go b/internal/webui/server.go index be67998fa..fad7033b0 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -14,6 +14,7 @@ import ( "log/slog" "net/http" "sync" + "sync/atomic" "time" "github.com/samcharles93/archie-core/internal/channels" @@ -50,9 +51,19 @@ type Server struct { // logging not configured) makes that a no-op. TaskLogs *logging.TaskRegistry - // ConfigProvenance is supplied by composition from the production loader. - // It is safe to expose: it contains paths and precedence only, never values. - ConfigProvenance []ConfigOrigin + // ConfigProvenance lists the files that produced the running config, + // in precedence order. Held through atomic.Pointer so a reload can + // swap it independently of Cfg. A reader may therefore observe the + // new config alongside the old provenance (or vice versa); this is + // display-only, and the skew is accepted rather than serialised. + ConfigProvenance atomic.Pointer[[]ConfigOrigin] + + // LastReload reports the most recent config reload outcome, so the + // dashboard can tell the operator when the running config is stale + // (a reload failed validation and the daemon kept the previous + // config). Optional: when nil, the /api/config response omits the + // reload status. + LastReload func() config.ReloadStatus // Channels reports actual adapter lifecycle, independently of configuration // presence. Nil preserves the configuration-only fallback for tests and @@ -105,6 +116,11 @@ type ConfigOrigin struct { Feature string `json:"feature,omitempty"` } +// SetProvenance publishes a fresh provenance list after a config reload. +func (s *Server) SetProvenance(origins []ConfigOrigin) { + s.ConfigProvenance.Store(&origins) +} + // IssueCloser closes the forge issue behind a task. type IssueCloser interface { CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error From d8d4c93239463a13a9439e585bb5419c8c215dcf Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 00:30:26 +1000 Subject: [PATCH 04/13] fix(config): share one config Holder between daemon and dashboard; re-apply model catalog on reload Adversarial review findings (fresh reviewer, no memory of the code): 1. (major) web.Cfg was a second Holder the reload never swapped, so /api/config showed boot-time values forever after the first reload while the daemon ran the new config -- the exact 'code means something different from what it says' failure. web and d now share one Holder (web.Cfg = d.Cfg after construction), so a reload swaps both views atomically. 2. (minor) the model catalog merge ran once at boot; publishing the raw reloaded document dropped catalog-discovered providers from the running config even though the file was unchanged. The apply closure re-runs applyModelCatalog on the reloaded document before publishing (idempotent; a catalog that failed to load merges to identity). 3. (minor) changedNonReloadableFields parameter 'new' shadowed the predeclared identifier (predeclared lint finding). Renamed to 'next'; the finding is gone from the branch diff. Also: tightened --no-config-overlay help text to state the file -config-overlay still applies (it gates the future DB overlay only), and documented that the controller's apply callback must be non-nil. task check clean; -race clean on cmd/archied and internal/daemon. --- cmd/archied/main.go | 14 +++++++++++++- cmd/archied/reload.go | 7 ++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/cmd/archied/main.go b/cmd/archied/main.go index a8e1ad231..ce6548747 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -313,7 +313,7 @@ func run() int { defaultCfg := filepath.Join(configHome(), "archie", "config.toml") cfgPath := flag.String("config", defaultCfg, "path to a TOML/YAML config file or configuration directory") overlayPath := flag.String("config-overlay", "", "path to a TOML/YAML overlay file or configuration directory applied on top of -config") - noConfigOverlay := flag.Bool("no-config-overlay", false, "ignore the runtime config overlay (recovery hatch: boots on file config alone)") + noConfigOverlay := flag.Bool("no-config-overlay", false, "skip the runtime config overlay (recovery hatch for the DB overlay; the -config-overlay file overlay still applies)") once := flag.Bool("once", false, "run a single poll+process cycle and exit (systemd timer / testing)") requeue := flag.Int64("requeue", 0, "requeue a parked/waiting task by id (keeps its workflow), then exit unless -once is also set") flag.Parse() @@ -979,6 +979,12 @@ func run() int { TaskLogs: taskLogs, } web.TaskStopper = d + // web and the daemon must share ONE Holder: a reload swaps d.Cfg and + // the dashboard reads the running config from the same snapshot. The + // webui Holder seeded in the literal above is replaced here; after + // this point /api/config and the daemon can never disagree about the + // published config. + web.Cfg = d.Cfg // SIGHUP re-loads the config from disk and republishes it. The apply // closure swaps the daemon's Holder and the dashboard's provenance; @@ -986,6 +992,12 @@ func run() int { // an operator never has to read the source to find out whether their // edit took effect. web.LastReload exposes the outcome to /api/config. reloadController := newReloadController(loader, *cfgPath, *overlayPath, func(doc *configuration.Document) { + // Boot merges catalog-discovered providers into cfg before the + // Holders are seeded; publishing the raw reloaded document would + // drop them from the running config even though the file is + // unchanged. Re-apply the same merge (idempotent: a catalog that + // failed to load merges to identity). + applyModelCatalog(&doc.Config, catalog) old := d.Cfg.Get() d.Cfg.Set(doc.Config) provenance := make([]webui.ConfigOrigin, 0, len(doc.Provenance.Origins)) diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go index df6453f28..7b891db28 100644 --- a/cmd/archied/reload.go +++ b/cmd/archied/reload.go @@ -25,7 +25,8 @@ type ReloadController struct { // apply receives a freshly loaded, validated Document. It is the // composition root's job to wire this to whatever owns the running - // config (the daemon's Holder, the dashboard's provenance). + // config (the daemon's Holder, the dashboard's provenance). Must be + // non-nil; newReloadController requires it. apply func(*configuration.Document) status atomic.Pointer[config.ReloadStatus] @@ -115,9 +116,9 @@ var reloadableSubFields = map[string]map[string]bool{ // operator knows their edit did not take effect until a restart -- // the alternative is an operator who believes a reloaded poll interval // changed the forge token, and burns an hour discovering it did not. -func changedNonReloadableFields(old, new config.Config) []string { +func changedNonReloadableFields(old, next config.Config) []string { var changed []string - ov, nv := reflect.ValueOf(old), reflect.ValueOf(new) + ov, nv := reflect.ValueOf(old), reflect.ValueOf(next) ot := reflect.TypeFor[config.Config]() for i := 0; i < ot.NumField(); i++ { f := ot.Field(i) From 31fdbddd6180d85dbe8ca661e2a192ce2f228a5e Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 00:47:30 +1000 Subject: [PATCH 05/13] fix(config): complete the reloadable allowlist and pin it against ForTask The allowlist drifted before the chunk shipped. ForTask (config.go:457-465) is the authoritative per-dispatch snapshot and carries Models, Budgets, Dispatch, DiffCapLines, Notify and Forge.Host -- I allowlisted only three. And the poll path reads cfg.Label and cfg.BotUser live per cycle (daemon.go:359,390 and :368,381) off the same per-poll config as Dispatch.Trigger. Five fields would have reported 'requires a restart' while actually taking effect immediately: the safe direction, but exactly the warning-fatigue failure that kills the feature (an operator who is told to restart for a label change that already applied learns the warning is noise). The fix is enforcement, not a bigger list: TestReloadableFieldsCoverForTaskSnapshot reflects over TaskConfig and fails if any field ForTask carries is not in the allowlist (Forge maps to the Forge.Host sub-field entry). A field added to ForTask later now fails the test instead of silently producing a wrong warning. Label and BotUser are not carried by ForTask -- they come off the poll path -- so they are allowlisted by hand with a comment, and the same test pins them explicitly. Also documents on webui.Server.Cfg that in production it is the daemon's OWN Holder (web.Cfg = d.Cfg), so Set publishes to the running daemon: a config-mutating handler must apply to a copy, validate the materialised config, persist, then Set -- never Set directly. task check clean. --- cmd/archied/reload.go | 23 +++++++++++---- cmd/archied/reload_test.go | 57 ++++++++++++++++++++++++++++++++++---- internal/webui/server.go | 6 ++++ 3 files changed, 74 insertions(+), 12 deletions(-) diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go index 7b891db28..976f0d519 100644 --- a/cmd/archied/reload.go +++ b/cmd/archied/reload.go @@ -92,22 +92,33 @@ var reloadableFields = map[string]bool{ "PollInterval": true, // Poll loops re-read per cycle (daemon.go poll / pollForIdentity). "Repos": true, - // Per-task snapshot: configFor -> executionFor -> d.Cfg.Get() at - // dispatch, carried by TaskConfig (config.go ForTask). + // Per-task snapshot: ForTask carries these into every dispatched + // TaskContext (config.go ForTask), built fresh from d.Cfg.Get() at + // dispatch. Pinned by TestReloadableFieldsCoverForTaskSnapshot so a + // field added to ForTask cannot silently drift out of this list. "DiffCapLines": true, "Budgets": true, - // Dispatch is read per poll (daemon.go pollIssuesWithConfig switch) - // and carried per task like DiffCapLines. - "Dispatch": true, + "Dispatch": true, + "Models": true, + "Notify": true, + // Per-poll reads off the live config in pollIssuesWithConfig: + // cfg.Label feeds IssuesWithLabel (daemon.go:359,390), cfg.BotUser + // feeds AssignedIssues (:368,381). Not carried by ForTask, so + // pinned by hand in TestReloadableFieldsCoverForTaskSnapshot. + "Label": true, + "BotUser": true, } // reloadableSubFields are sub-fields of structs that are otherwise // startup-built. VolumeTTL and MaxConcurrency are re-read per cycle // (cleanupExpiredStorage, drainSQLite/drainNATS); everything else in // Containers (Image, Enabled, MaxUptime, PullPolicy, Network) is frozen -// in the startup-built container pool. +// in the startup-built container pool. Forge.Host is carried into +// TaskContext by ForTask (display/link building only); the forge client +// itself is startup-built, so Type/Token/TokenEnv stay requires-restart. var reloadableSubFields = map[string]map[string]bool{ "Containers": {"VolumeTTL": true, "MaxConcurrency": true}, + "Forge": {"Host": true}, } // changedNonReloadableFields compares old and new and returns the diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go index b864e69d1..86bb41fca 100644 --- a/cmd/archied/reload_test.go +++ b/cmd/archied/reload_test.go @@ -5,6 +5,7 @@ import ( "log/slog" "os" "path/filepath" + "reflect" "sync" "syscall" "testing" @@ -146,23 +147,27 @@ func TestChangedNonReloadableFields(t *testing.T) { t.Fatalf("unchanged: got %v, want []", got) } - // Reloadable-only changes (PollInterval, Repos, Budgets, Dispatch, - // DiffCapLines) -> empty. + // Reloadable-only changes -> empty. reloadableOnly := base reloadableOnly.PollInterval = config.Duration(60 * time.Second) reloadableOnly.Repos = []config.Repo{{Owner: "x", Name: "z"}} reloadableOnly.Budgets = config.Budgets{MaxSteps: 99} reloadableOnly.Dispatch = config.Dispatch{Trigger: "label"} reloadableOnly.DiffCapLines = 1234 + reloadableOnly.Models = map[string]string{"builder": "provider/model"} + reloadableOnly.Notify = config.Notify{Webhook: "https://notify.example/hook"} + reloadableOnly.Label = "archie" + reloadableOnly.BotUser = "new-bot" + reloadableOnly.Forge = config.Forge{Host: "https://new-forge.example"} if got := changedNonReloadableFields(base, reloadableOnly); len(got) != 0 { t.Fatalf("reloadable-only: got %v, want []", got) } - // A non-reloadable change is named. + // A non-reloadable change is named (Agent builds the startup runner). nonReloadable := base - nonReloadable.BotUser = "b" - if got := changedNonReloadableFields(base, nonReloadable); len(got) != 1 || got[0] != "BotUser" { - t.Fatalf("BotUser change: got %v, want [BotUser]", got) + nonReloadable.Agent = config.Agent{Mode: "subprocess"} + if got := changedNonReloadableFields(base, nonReloadable); len(got) != 1 || got[0] != "Agent" { + t.Fatalf("Agent change: got %v, want [Agent]", got) } // Containers sub-field granularity: Image change warns, MaxConcurrency @@ -192,4 +197,44 @@ func TestChangedNonReloadableFields(t *testing.T) { if got := changedNonReloadableFields(base, natsChanged); len(got) != 1 || got[0] != "NATS" { t.Fatalf("NATS change: got %v, want [NATS]", got) } + + // Forge.Host is reloadable but Forge.Type is not: only the host is + // carried into TaskContext by ForTask. + forgeTypeChanged := base + forgeTypeChanged.Forge = config.Forge{Type: "gitea"} + if got := changedNonReloadableFields(base, forgeTypeChanged); len(got) != 1 || got[0] != "Forge.Type" { + t.Fatalf("Forge.Type change: got %v, want [Forge.Type]", got) + } +} + +// TestReloadableFieldsCoverForTaskSnapshot pins the allowlist against +// the per-dispatch snapshot: every field ForTask carries into a +// TaskContext is re-read at dispatch, so a reload applies to new tasks. +// If a field is added to ForTask later, this test fails until the +// allowlist is updated -- a hand-maintained list that mirrors ForTask +// otherwise drifts silently into a wrong 'requires a restart' warning. +func TestReloadableFieldsCoverForTaskSnapshot(t *testing.T) { + tt := reflect.TypeFor[config.TaskConfig]() + for field := range tt.Fields() { + name := field.Name + if name == "Forge" { + // TaskConfig.Forge is TaskForge{Host}; it maps to the + // Config.Forge.Host sub-field allowlist entry. + if !reloadableSubFields["Forge"]["Host"] { + t.Errorf("ForTask field Forge (Host) is not allowlisted as reloadable") + } + continue + } + if !reloadableFields[name] { + t.Errorf("ForTask field %s is not allowlisted as reloadable", name) + } + } + // The poll-path fields (Label, BotUser) are not carried by ForTask; + // pin them explicitly so a refactor that moves their read site does + // not silently drop the allowlist entry. + for _, name := range []string{"Label", "BotUser"} { + if !reloadableFields[name] { + t.Errorf("poll-path field %s is not allowlisted as reloadable", name) + } + } } diff --git a/internal/webui/server.go b/internal/webui/server.go index fad7033b0..ddce8bd9b 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -36,6 +36,12 @@ type Server struct { // dashboard degrades to task data alone when it is nil. Held through a // Holder so a reload swaps the snapshot atomically across handler // goroutines that would otherwise race on the raw shared pointer. + // + // In production this is the daemon's OWN Holder (main.go wires + // web.Cfg = d.Cfg), so Set here publishes to the running daemon. A + // config-mutating handler must never call Set directly: it goes + // through the same path as reload -- apply to a copy, validate the + // materialised config, persist, then Set. Cfg *config.Holder // Workflows is the executable registry snapshot supplied by composition. From da2d93a8301848b069fabbe432d8678c2018dff9 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 00:54:23 +1000 Subject: [PATCH 06/13] feat(config): runtime config overlay store and PATCH /api/config The second half of #348's storage layer: dashboard-edited overrides live in their own SQLite file, separate from the task and conversation stores so each file owns its user_version and migrator with no contention (configDBPath -> cfg.DBPath + "-config.sqlite", matching the taskDBPath / conversationDBPath convention). Store (internal/infrastructure/configuration/overlay): - config_overlay(key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at, updated_by), own migration, WAL. - Set refuses DeniedKeys (db_path, work_dir) at write time as well as at the API layer; the map is exported so the dashboard can show the reason instead of silently omitting the edit affordance. - Snapshot JSON-decodes each value and nests dotted keys ("budgets.max_steps" -> map[b][m]) ready to decode into Config. Loader (ApplyOverlay / ApplyOverlayValues): - Decodes a nested overlay map with the same field-level precedence as a file overlay, records the runtime-overlay origin, then applies defaults and validates. Used at boot, on SIGHUP reload (ReloadController gained an optional WithOverlay source) and by the PATCH path. Boot and reload: - A broken overlay (unopenable store, unreadable snapshot, values that fail validation) degrades to file config alone -- it must never brick the daemon. --no-config-overlay / ARCHIE_SKIP_CONFIG_OVERLAY=1 skips the store entirely; the flag is now a real gate, not a log-only stub. PATCH /api/config (webui): - handleConfigUpdate decodes {"updates": {dotted.key: value}}, calls the composition-wired UpdateConfig seam, and classifies errors via webui sentinels: ErrConfigUpdateInvalid -> 400 (denylisted key, failed validation, unparseable value), ErrConfigUpdateUnavailable -> 503 (overlay skipped by recovery flag), anything else -> 500. - The seam (main.go) applies updates to a COPY of the published config, validates the materialised result, persists to the overlay, then publishes through the same path as reload -- it never calls Set directly from the handler, since web.Cfg is the daemon's own Holder. - ConfigView gains Locked (dotted key -> reason) so the UI disables denylisted rows explicitly. Verified: task check clean; new tests cover the store round-trip, denied keys, loader overlay layering/validation/provenance, reload with and without overlay, and the PATCH handler's 200/400/503 paths. --- cmd/archied/main.go | 116 ++++++++++-- cmd/archied/reload.go | 33 ++++ cmd/archied/reload_test.go | 48 +++++ .../infrastructure/configuration/apply.go | 33 ++++ .../configuration/apply_test.go | 88 +++++++++ .../infrastructure/configuration/loader.go | 19 ++ .../configuration/overlay/overlay.go | 178 ++++++++++++++++++ .../configuration/overlay/overlay_test.go | 122 ++++++++++++ internal/webui/api_config.go | 68 +++++++ internal/webui/api_config_test.go | 97 ++++++++++ internal/webui/server.go | 8 + 11 files changed, 796 insertions(+), 14 deletions(-) create mode 100644 internal/infrastructure/configuration/apply.go create mode 100644 internal/infrastructure/configuration/apply_test.go create mode 100644 internal/infrastructure/configuration/overlay/overlay.go create mode 100644 internal/infrastructure/configuration/overlay/overlay_test.go diff --git a/cmd/archied/main.go b/cmd/archied/main.go index ce6548747..26fedb1b7 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -43,6 +43,7 @@ import ( "github.com/samcharles93/archie-core/internal/forgerpc" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay" "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" "github.com/samcharles93/archie-core/internal/logging" @@ -293,6 +294,15 @@ func taskDBPath(configuredPath string) string { return configuredPath + "-tasks.sqlite" } +// configDBPath resolves the runtime config overlay file. It is a sibling +// of the task and conversation stores (same configured path, own suffix) +// so each file owns its user_version and its migrator with no +// contention; recovery from a broken overlay is rm this file plus the +// --no-config-overlay boot flag. +func configDBPath(configuredPath string) string { + return configuredPath + "-config.sqlite" +} + func manualRequeueTask(ctx context.Context, st store.TaskStore, taskID int64) error { task, err := st.TaskByID(ctx, taskID) if err != nil { @@ -323,7 +333,8 @@ func run() int { log := slog.New(slog.NewJSONHandler(os.Stderr, nil)) loader := configuration.New(log) - if *noConfigOverlay || configuration.SkipOverlay() { + skipOverlay := *noConfigOverlay || configuration.SkipOverlay() + if skipOverlay { log.Info("runtime config overlay disabled (recovery hatch); booting on file config alone") } doc, err := loader.Resolve(*cfgPath, *overlayPath) @@ -331,6 +342,32 @@ func run() int { fmt.Fprintln(os.Stderr, err) return 1 } + // Runtime config overlay: dashboard-edited overrides layered over the + // file config from their own SQLite file (own user_version and + // migrator, no contention with the task store). Skipped under + // --no-config-overlay / ARCHIE_SKIP_CONFIG_OVERLAY=1, or when the + // store cannot be opened or its values fail validation -- a broken + // overlay must not brick the daemon. + var overlayStore *overlay.Store + if !skipOverlay { + overlayStore, err = overlay.Open(ctx, configDBPath(doc.Config.DBPath)) + if err != nil { + log.Error("config overlay unavailable; booting on file config alone", "path", configDBPath(doc.Config.DBPath), "err", err) + } else { + defer overlayStore.Close() + if overrides, err := overlayStore.Snapshot(ctx); err != nil { + log.Error("config overlay unreadable; booting on file config alone", "err", err) + } else if len(overrides) > 0 { + next := *doc + applied, err := loader.ApplyOverlay(&next, overrides) + if err != nil { + log.Error("config overlay rejected by validation; booting on file config alone", "err", err) + } else { + doc = applied + } + } + } + } cfg := doc.Config // Re-create the logger now the config is known. Everything above this @@ -986,11 +1023,28 @@ func run() int { // published config. web.Cfg = d.Cfg - // SIGHUP re-loads the config from disk and republishes it. The apply - // closure swaps the daemon's Holder and the dashboard's provenance; - // the reload log warns about changed fields that require a restart, so - // an operator never has to read the source to find out whether their - // edit took effect. web.LastReload exposes the outcome to /api/config. + // publishConfig publishes a config snapshot and its provenance to + // both the daemon and the dashboard (they share one Holder). Reload + // and the PATCH path both go through it, so the two can never + // diverge. currentProvenance is the last published provenance chain; + // the PATCH path appends the runtime-overlay origin to it. + currentProvenance := doc.Provenance + publishConfig := func(cfg config.Config, provenance configuration.Provenance) { + d.Cfg.Set(cfg) + origins := make([]webui.ConfigOrigin, 0, len(provenance.Origins)) + for _, origin := range provenance.Origins { + origins = append(origins, webui.ConfigOrigin{ + Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature), + }) + } + web.SetProvenance(origins) + } + + // SIGHUP re-loads the config from disk, layers the runtime overlay, + // and republishes it. The reload log warns about changed fields that + // require a restart, so an operator never has to read the source to + // find out whether their edit took effect. web.LastReload exposes + // the outcome to /api/config. reloadController := newReloadController(loader, *cfgPath, *overlayPath, func(doc *configuration.Document) { // Boot merges catalog-discovered providers into cfg before the // Holders are seeded; publishing the raw reloaded document would @@ -999,14 +1053,8 @@ func run() int { // failed to load merges to identity). applyModelCatalog(&doc.Config, catalog) old := d.Cfg.Get() - d.Cfg.Set(doc.Config) - provenance := make([]webui.ConfigOrigin, 0, len(doc.Provenance.Origins)) - for _, origin := range doc.Provenance.Origins { - provenance = append(provenance, webui.ConfigOrigin{ - Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature), - }) - } - web.SetProvenance(provenance) + currentProvenance = doc.Provenance + publishConfig(doc.Config, doc.Provenance) if fields := changedNonReloadableFields(old, doc.Config); len(fields) > 0 { log.Warn("config reloaded; some changes require a restart", "fields", fields, "paths", doc.Provenance.Paths()) @@ -1014,8 +1062,48 @@ func run() int { log.Info("config reloaded", "paths", doc.Provenance.Paths()) } }) + if overlayStore != nil { + reloadController.WithOverlay(func() (map[string]any, error) { return overlayStore.Snapshot(ctx) }) + } web.LastReload = reloadController.Status + // PATCH /api/config goes through the same publish path as reload: + // apply to a copy of the published config, validate the materialised + // result, persist to the overlay, then publish. It must never call + // Set directly from the handler -- web.Cfg is the daemon's own Holder. + web.UpdateConfig = func(ctx context.Context, updates map[string]any) error { + if overlayStore == nil { + return fmt.Errorf("%w: config overlay is disabled (--no-config-overlay or ARCHIE_SKIP_CONFIG_OVERLAY=1)", webui.ErrConfigUpdateUnavailable) + } + for key := range updates { + if reason, denied := overlay.DeniedKeys[key]; denied { + return fmt.Errorf("%w: config key %s is not runtime-tunable: %s", webui.ErrConfigUpdateInvalid, key, reason) + } + } + next := d.Cfg.Get() + if err := configuration.ApplyOverlayValues(&next, updates); err != nil { + return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + } + if err := configuration.Validate(&next); err != nil { + return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + } + for key, value := range updates { + data, err := json.Marshal(value) + if err != nil { + return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + } + if err := overlayStore.Set(ctx, key, string(data), "dashboard"); err != nil { + return err + } + } + prov := configuration.Provenance{Origins: append(append([]configuration.Origin{}, currentProvenance.Origins...), + configuration.Origin{Path: "config_overlay (runtime)", Role: configuration.RoleMain, Layer: configuration.LayerOverlay})} + currentProvenance = prov + publishConfig(next, prov) + log.Info("config updated from dashboard", "keys", len(updates)) + return nil + } + reloadCh := make(chan os.Signal, 1) signal.Notify(reloadCh, syscall.SIGHUP) defer signal.Stop(reloadCh) diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go index 976f0d519..66468af0e 100644 --- a/cmd/archied/reload.go +++ b/cmd/archied/reload.go @@ -29,6 +29,12 @@ type ReloadController struct { // non-nil; newReloadController requires it. apply func(*configuration.Document) + // overlayValues, when non-nil, returns the runtime config overlay + // (dotted keys -> typed values) to layer over the file config before + // publishing. A failed overlay read or validation aborts the reload + // exactly like a bad file. + overlayValues func() (map[string]any, error) + status atomic.Pointer[config.ReloadStatus] } @@ -51,6 +57,26 @@ func (c *ReloadController) Reload() error { }) return err } + if c.overlayValues != nil { + values, err := c.overlayValues() + if err != nil { + c.status.Store(&config.ReloadStatus{ + LastError: err.Error(), + LastErrorAt: time.Now().UTC().Format(time.RFC3339), + }) + return err + } + if len(values) > 0 { + next := *doc + if doc, err = c.loader.ApplyOverlay(&next, values); err != nil { + c.status.Store(&config.ReloadStatus{ + LastError: err.Error(), + LastErrorAt: time.Now().UTC().Format(time.RFC3339), + }) + return err + } + } + } c.apply(doc) c.status.Store(&config.ReloadStatus{ LastReloadAt: time.Now().UTC().Format(time.RFC3339), @@ -58,6 +84,13 @@ func (c *ReloadController) Reload() error { return nil } +// WithOverlay attaches the runtime config overlay source. Optional: a +// controller without it publishes the file config alone. +func (c *ReloadController) WithOverlay(fn func() (map[string]any, error)) *ReloadController { + c.overlayValues = fn + return c +} + // Status returns the most recent reload outcome. func (c *ReloadController) Status() config.ReloadStatus { if p := c.status.Load(); p != nil { diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go index 86bb41fca..5dbe070ba 100644 --- a/cmd/archied/reload_test.go +++ b/cmd/archied/reload_test.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "log/slog" "os" "path/filepath" @@ -105,6 +106,53 @@ func TestReloadValidationFailureDoesNotApply(t *testing.T) { } } +func TestReloadAppliesOverlayBeforePublish(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + writeConfig(t, path, minimalConfigTOML("widget")) + + loader := configuration.New(slog.New(slog.DiscardHandler)) + var published config.Config + controller := newReloadController(loader, path, "", func(doc *configuration.Document) { + published = doc.Config + }).WithOverlay(func() (map[string]any, error) { + return map[string]any{"poll_interval": "90s"}, nil + }) + + if err := controller.Reload(); err != nil { + t.Fatal(err) + } + if published.PollInterval != config.Duration(90*time.Second) { + t.Errorf("PollInterval = %v, want 90s (overlay applied before publish)", published.PollInterval) + } +} + +// TestReloadOverlayFailureAborts pins that a failed overlay read or +// validation aborts the reload exactly like a bad file: apply is not +// called and the error is recorded. +func TestReloadOverlayFailureAborts(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + writeConfig(t, path, minimalConfigTOML("widget")) + + loader := configuration.New(slog.New(slog.DiscardHandler)) + applied := 0 + controller := newReloadController(loader, path, "", func(*configuration.Document) { applied++ }). + WithOverlay(func() (map[string]any, error) { + return nil, errors.New("overlay unreadable") + }) + + if err := controller.Reload(); err == nil { + t.Fatal("expected an error from the failed overlay") + } + if applied != 0 { + t.Fatalf("apply called %d times after overlay failure, want 0", applied) + } + if st := controller.Status(); st.LastError == "" { + t.Fatal("expected LastError recorded") + } +} + func TestReloadLoopAppliesOnSignalAndStopsOnCancel(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "config.toml") diff --git a/internal/infrastructure/configuration/apply.go b/internal/infrastructure/configuration/apply.go new file mode 100644 index 000000000..c6f4cd250 --- /dev/null +++ b/internal/infrastructure/configuration/apply.go @@ -0,0 +1,33 @@ +package configuration + +import ( + "fmt" + + "gopkg.in/yaml.v3" + + "github.com/samcharles93/archie-core/internal/config" +) + +// ApplyOverlayValues decodes overrides (a nested map of dotted-path +// values, as produced by the overlay store) into cfg using the same +// field-level precedence as a file overlay: only the keys present are +// replaced, every field the overlay omits keeps its existing value. +// +// This is the decode half of the runtime config overlay. The loader's +// ApplyOverlay wraps it with defaulting, validation and provenance; the +// dashboard PATCH path calls it on a copy of the published config and +// validates the materialised result before persisting. Either way the +// caller owns the cfg value -- pass a copy when the base must survive. +func ApplyOverlayValues(cfg *config.Config, overrides map[string]any) error { + if len(overrides) == 0 { + return nil + } + data, err := yaml.Marshal(overrides) + if err != nil { + return fmt.Errorf("%w: encoding config overlay: %v", ErrUnreadable, err) + } + if err := yaml.Unmarshal(data, cfg); err != nil { + return fmt.Errorf("%w: parsing config overlay: %v", ErrUnreadable, err) + } + return nil +} diff --git a/internal/infrastructure/configuration/apply_test.go b/internal/infrastructure/configuration/apply_test.go new file mode 100644 index 000000000..31dcf90c3 --- /dev/null +++ b/internal/infrastructure/configuration/apply_test.go @@ -0,0 +1,88 @@ +package configuration + +import ( + "log/slog" + "os" + "path/filepath" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/config" +) + +func TestApplyOverlayValuesFieldLevelMerge(t *testing.T) { + cfg := config.Config{ + BotUser: "a", + Budgets: config.Budgets{MaxSteps: 10}, + } + overrides := map[string]any{ + "budgets": map[string]any{"max_steps": float64(20)}, + } + if err := ApplyOverlayValues(&cfg, overrides); err != nil { + t.Fatal(err) + } + if cfg.Budgets.MaxSteps != 20 { + t.Errorf("MaxSteps = %d, want 20", cfg.Budgets.MaxSteps) + } + // Fields the overlay omits keep their value. + if cfg.BotUser != "a" { + t.Errorf("BotUser = %q, want a (unchanged)", cfg.BotUser) + } + // Unrelated nested fields keep their value too. + if cfg.Budgets.MaxTokens != 0 { + t.Errorf("MaxTokens = %d, want 0 (untouched)", cfg.Budgets.MaxTokens) + } +} + +func TestLoaderApplyOverlayLayersDefaultsValidatesAndRecordsProvenance(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte("bot_user = \"widget\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"), 0o600); err != nil { + t.Fatal(err) + } + + l := New(slog.New(slog.DiscardHandler)) + doc, err := l.Resolve(path, "") + if err != nil { + t.Fatal(err) + } + + applied, err := l.ApplyOverlay(doc, map[string]any{"poll_interval": "90s"}) + if err != nil { + t.Fatal(err) + } + if applied.Config.PollInterval != config.Duration(90*time.Second) { + t.Errorf("PollInterval = %v, want 90s", applied.Config.PollInterval) + } + if len(applied.Provenance.Origins) != 2 { + t.Errorf("Origins = %+v, want 2 (file + runtime overlay)", applied.Provenance.Origins) + } + + // An overlay that fails validation aborts; the base document is + // untouched when a copy is passed. + next := *doc + if _, err := l.ApplyOverlay(&next, map[string]any{"agent": map[string]any{"mode": "bogus"}}); err == nil { + t.Fatal("invalid overlay accepted") + } + if doc.Config.Agent.Mode != "inprocess" { + t.Errorf("base Agent.Mode = %q, want inprocess (defaulted, untouched)", doc.Config.Agent.Mode) + } +} + +func TestLoaderApplyOverlayEmptyIsNoOp(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte("bot_user = \"widget\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"), 0o600); err != nil { + t.Fatal(err) + } + l := New(slog.New(slog.DiscardHandler)) + doc, err := l.Resolve(path, "") + if err != nil { + t.Fatal(err) + } + applied, err := l.ApplyOverlay(doc, nil) + if err != nil { + t.Fatal(err) + } + if len(applied.Provenance.Origins) != 1 { + t.Errorf("Origins = %+v, want 1 (no overlay origin for an empty overlay)", applied.Provenance.Origins) + } +} diff --git a/internal/infrastructure/configuration/loader.go b/internal/infrastructure/configuration/loader.go index 4189ee8ec..73cb71a01 100644 --- a/internal/infrastructure/configuration/loader.go +++ b/internal/infrastructure/configuration/loader.go @@ -113,6 +113,25 @@ func (l *Loader) Overlay(basePath, overlayPath string) (*Document, error) { return l.overlayFile(basePath, overlayPath) } +// ApplyOverlay decodes the runtime config overlay (a nested map of +// dotted-path values from the overlay store) into doc with the same +// field-level precedence as a file overlay, records the overlay origin, +// then applies defaults and validates. It is used at boot and on reload +// to layer dashboard-edited overrides over the file config. +// +// doc is decoded in place; pass a copy when the base document must +// survive a decode or validation failure (the boot path does). +func (l *Loader) ApplyOverlay(doc *Document, overrides map[string]any) (*Document, error) { + if len(overrides) == 0 { + return l.finalize(doc) + } + if err := ApplyOverlayValues(&doc.Config, overrides); err != nil { + return nil, err + } + doc.Provenance.record(Origin{Path: "config_overlay (runtime)", Role: RoleMain, Layer: LayerOverlay}) + return l.finalize(doc) +} + func (l *Loader) overlayFile(basePath, overlayPath string) (*Document, error) { doc := &Document{} diff --git a/internal/infrastructure/configuration/overlay/overlay.go b/internal/infrastructure/configuration/overlay/overlay.go new file mode 100644 index 000000000..2ad794e43 --- /dev/null +++ b/internal/infrastructure/configuration/overlay/overlay.go @@ -0,0 +1,178 @@ +// Package overlay persists runtime-tunable configuration overrides in +// their own SQLite file (cfg.DBPath + "-config.sqlite"), separate from +// the task, conversation and search stores so each file owns its +// user_version and its migrator with no contention. +// +// It backs the dashboard's config editing: a PATCH writes here, the +// daemon layers these values over the file config at boot and on every +// reload, and removing the file (or passing --no-config-overlay / +// ARCHIE_SKIP_CONFIG_OVERLAY=1) is the documented recovery from a write +// that would otherwise break boot. +package overlay + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + _ "modernc.org/sqlite" +) + +// DeniedKeys are the config keys the overlay may never set, mapped to +// the reason shown to the operator. db_path is the daemon's own +// bootstrap path -- the daemon must read it before it can open this +// store -- and work_dir pins the whole working layout. Enforced at +// write time (the API returns 4xx) and again in Set, not silently +// dropped at read time. +var DeniedKeys = map[string]string{ + "db_path": "required for bootstrap; cannot be changed at runtime", + "work_dir": "pins the daemon's working layout; cannot be changed at runtime", +} + +// Store is the config overlay database. +type Store struct{ db *sql.DB } + +const schemaVersion = 1 + +const schema = ` +CREATE TABLE IF NOT EXISTS config_overlay ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL, + updated_by TEXT NOT NULL +); +` + +// Open opens (creating if needed) the overlay database and migrates it. +func Open(ctx context.Context, path string) (*Store, error) { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return nil, err + } + db, err := sql.Open("sqlite", sqliteDSN(path)) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(1) + if _, err := db.ExecContext(ctx, schema); err != nil { + return nil, errors.Join(fmt.Errorf("overlay: init schema: %w", err), db.Close()) + } + if err := migrate(ctx, db); err != nil { + return nil, errors.Join(fmt.Errorf("overlay: migrate: %w", err), db.Close()) + } + return &Store{db: db}, nil +} + +// Close closes the database. +func (s *Store) Close() error { return s.db.Close() } + +// sqliteDSN enables WAL and a busy timeout. Kept local to match the +// task and gateway stores; deduplicating the three copies is a +// follow-up, not part of this change. +func sqliteDSN(path string) string { + separator := "?" + if strings.HasSuffix(path, "?") || strings.HasSuffix(path, "&") { + separator = "" + } else if strings.Contains(path, "?") { + separator = "&" + } + return path + separator + "_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)" +} + +func migrate(ctx context.Context, db *sql.DB) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + + var version int + if err := tx.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&version); err != nil { + return err + } + if version > schemaVersion { + return fmt.Errorf("config overlay schema version %d is newer than supported version %d", version, schemaVersion) + } + if version == schemaVersion { + return tx.Commit() + } + if _, err := tx.ExecContext(ctx, `PRAGMA user_version = 1`); err != nil { + return err + } + return tx.Commit() +} + +// Set persists one override. key is a dotted config path +// ("budgets.max_steps"); value is the JSON encoding of the field value +// ("12", "\"60s\"", "true"). updatedBy names the writer for audit. +// Keys in DeniedKeys are refused here as well as at the API layer. +func (s *Store) Set(ctx context.Context, key, value, updatedBy string) error { + if reason, denied := DeniedKeys[key]; denied { + return fmt.Errorf("config key %s is not runtime-tunable: %s", key, reason) + } + _, err := s.db.ExecContext(ctx, + `INSERT INTO config_overlay (key, value, updated_at, updated_by) VALUES (?, ?, ?, ?) + ON CONFLICT(key) DO UPDATE SET + value = excluded.value, updated_at = excluded.updated_at, updated_by = excluded.updated_by`, + key, value, time.Now().UTC().Format(time.RFC3339), updatedBy) + return err +} + +// Delete removes one override, restoring the file's value for that key. +func (s *Store) Delete(ctx context.Context, key string) error { + _, err := s.db.ExecContext(ctx, `DELETE FROM config_overlay WHERE key = ?`, key) + return err +} + +// Snapshot returns every stored override as a nested map of typed +// values ready to decode into config.Config. Dotted keys are nested: +// "budgets.max_steps" becomes map["budgets"]["max_steps"]. Values are +// JSON-decoded so the caller never has to know the field's type. +func (s *Store) Snapshot(ctx context.Context) (map[string]any, error) { + rows, err := s.db.QueryContext(ctx, `SELECT key, value FROM config_overlay`) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + + out := make(map[string]any) + for rows.Next() { + var key, raw string + if err := rows.Scan(&key, &raw); err != nil { + return nil, err + } + var value any + if err := json.Unmarshal([]byte(raw), &value); err != nil { + return nil, fmt.Errorf("overlay: key %s holds invalid JSON %q: %w", key, raw, err) + } + if err := Nest(out, key, value); err != nil { + return nil, err + } + } + return out, rows.Err() +} + +// Nest inserts value into root at the dotted key path ("a.b.c" -> +// root["a"]["b"]["c"]), creating intermediate maps as needed. +func Nest(root map[string]any, key string, value any) error { + parts := strings.Split(key, ".") + if len(parts) == 0 || parts[0] == "" { + return fmt.Errorf("overlay: empty key %q", key) + } + cur := root + for _, part := range parts[:len(parts)-1] { + next, ok := cur[part].(map[string]any) + if !ok { + next = make(map[string]any) + cur[part] = next + } + cur = next + } + cur[parts[len(parts)-1]] = value + return nil +} diff --git a/internal/infrastructure/configuration/overlay/overlay_test.go b/internal/infrastructure/configuration/overlay/overlay_test.go new file mode 100644 index 000000000..e155f2689 --- /dev/null +++ b/internal/infrastructure/configuration/overlay/overlay_test.go @@ -0,0 +1,122 @@ +package overlay + +import ( + "context" + "path/filepath" + "reflect" + "testing" +) + +func openTest(t *testing.T) (*Store, context.Context) { + t.Helper() + s, err := Open(context.Background(), filepath.Join(t.TempDir(), "config.sqlite")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + return s, context.Background() +} + +func TestSetGetSnapshotRoundTrip(t *testing.T) { + s, ctx := openTest(t) + + for _, tc := range []struct { + key, value string + }{ + {"budgets.max_steps", "12"}, + {"label", `"archie"`}, + {"containers.enabled", "true"}, + {"web.listen", `":8643"`}, + } { + if err := s.Set(ctx, tc.key, tc.value, "test"); err != nil { + t.Fatalf("Set(%s): %v", tc.key, err) + } + } + + snap, err := s.Snapshot(ctx) + if err != nil { + t.Fatal(err) + } + + if got := snap["budgets"].(map[string]any)["max_steps"]; !reflect.DeepEqual(got, float64(12)) { + t.Errorf("budgets.max_steps = %#v, want float64(12)", got) + } + if got := snap["label"]; got != "archie" { + t.Errorf("label = %#v, want archie", got) + } + if got := snap["containers"].(map[string]any)["enabled"]; got != true { + t.Errorf("containers.enabled = %#v, want true", got) + } + if got := snap["web"].(map[string]any)["listen"]; got != ":8643" { + t.Errorf("web.listen = %#v, want :8643", got) + } +} + +func TestSetUpsertsAndDeleteRestores(t *testing.T) { + s, ctx := openTest(t) + + if err := s.Set(ctx, "label", `"first"`, "test"); err != nil { + t.Fatal(err) + } + if err := s.Set(ctx, "label", `"second"`, "test"); err != nil { + t.Fatal(err) + } + snap, err := s.Snapshot(ctx) + if err != nil { + t.Fatal(err) + } + if snap["label"] != "second" { + t.Fatalf("after upsert, label = %#v, want second", snap["label"]) + } + + if err := s.Delete(ctx, "label"); err != nil { + t.Fatal(err) + } + snap, err = s.Snapshot(ctx) + if err != nil { + t.Fatal(err) + } + if len(snap) != 0 { + t.Fatalf("after delete, snapshot = %#v, want empty", snap) + } +} + +func TestSetRefusesDeniedKeys(t *testing.T) { + s, ctx := openTest(t) + for key := range DeniedKeys { + if err := s.Set(ctx, key, `"x"`, "test"); err == nil { + t.Errorf("Set(%s) succeeded, want denial", key) + } + } +} + +func TestNestBuildsNestedMaps(t *testing.T) { + root := map[string]any{} + if err := Nest(root, "a.b.c", 1); err != nil { + t.Fatal(err) + } + if err := Nest(root, "a.b.d", "x"); err != nil { + t.Fatal(err) + } + ab := root["a"].(map[string]any)["b"].(map[string]any) + if ab["c"] != 1 || ab["d"] != "x" { + t.Fatalf("nested map = %#v", root) + } + if err := Nest(root, "", 1); err == nil { + t.Fatal("empty key accepted") + } +} + +func TestOpenIdempotentAndVersioned(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.sqlite") + s1, err := Open(context.Background(), path) + if err != nil { + t.Fatal(err) + } + _ = s1.Close() + s2, err := Open(context.Background(), path) + if err != nil { + t.Fatalf("reopen: %v", err) + } + _ = s2.Close() +} diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 6fb16cb23..b0b0c3f31 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -1,12 +1,31 @@ package webui import ( + "encoding/json" + "errors" + "maps" "net/http" "strconv" "strings" "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay" +) + +// Sentinel errors for handleConfigUpdate status classification. The +// composition root wraps its UpdateConfig errors with these so the +// handler can answer 400 (invalid input) or 503 (unavailable) without +// reaching into infrastructure internals. +var ( + // ErrConfigUpdateUnavailable reports that config editing is not + // wired (no UpdateConfig seam, or the overlay is skipped by the + // recovery flag). + ErrConfigUpdateUnavailable = errors.New("config editing unavailable") + // ErrConfigUpdateInvalid reports a rejected update: a denylisted + // key, a failed validation of the materialised config, or an + // unparseable value. + ErrConfigUpdateInvalid = errors.New("config update invalid") ) // ChannelView is one conversational front-end as shown on the dashboard's @@ -198,6 +217,10 @@ type ConfigView struct { // Reload reports the most recent config reload outcome. Omitted when // the reload status is unavailable. Reload *config.ReloadStatus `json:"reload,omitempty"` + // Locked maps dotted config keys that cannot be changed from the + // dashboard to the reason. The UI renders these rows disabled rather + // than silently omitting the edit affordance. + Locked map[string]string `json:"locked,omitempty"` } // IdentityView is who Archie is on the forge -- never the token that @@ -347,6 +370,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { }, Web: WebView{Listen: cfg.Web.Listen}, Provenance: provenance, + Locked: lockedConfigKeys(), } if s.LastReload != nil { rs := s.LastReload() @@ -356,6 +380,50 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { writeJSON(w, view) } +// lockedConfigKeys returns the dotted config keys the overlay refuses +// to set, with the reason shown in the UI. These are the daemon's own +// bootstrap inputs; changing them from the dashboard could break the +// next boot. +func lockedConfigKeys() map[string]string { + out := make(map[string]string, len(overlay.DeniedKeys)) + maps.Copy(out, overlay.DeniedKeys) + return out +} + +// handleConfigUpdate applies a set of dotted-path config updates via +// UpdateConfig, which the composition root wires to the same +// validate-persist-publish path as reload. The dashboard can then +// change runtime-tunable settings without hand-editing TOML. +func (s *Server) handleConfigUpdate(w http.ResponseWriter, r *http.Request) { + if s.UpdateConfig == nil { + http.Error(w, ErrConfigUpdateUnavailable.Error(), http.StatusServiceUnavailable) + return + } + var body struct { + Updates map[string]any `json:"updates"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest) + return + } + if len(body.Updates) == 0 { + http.Error(w, "no updates provided", http.StatusBadRequest) + return + } + if err := s.UpdateConfig(r.Context(), body.Updates); err != nil { + switch { + case errors.Is(err, ErrConfigUpdateUnavailable): + http.Error(w, err.Error(), http.StatusServiceUnavailable) + case errors.Is(err, ErrConfigUpdateInvalid): + http.Error(w, err.Error(), http.StatusBadRequest) + default: + http.Error(w, "config update failed: "+err.Error(), http.StatusInternalServerError) + } + return + } + writeJSON(w, map[string]any{"ok": true}) +} + func reposView(repos []config.Repo) []RepoView { out := make([]RepoView, 0, len(repos)) for _, r := range repos { diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index 918f043aa..c0f1e1dd9 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -1,7 +1,9 @@ package webui import ( + "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "strings" @@ -223,6 +225,101 @@ func TestSetProvenancePublishesForConfigView(t *testing.T) { } } +// TestHandleConfigReportsLockedKeys proves the dashboard is told which +// config keys it cannot edit and why, so it can disable those rows +// instead of silently omitting the edit affordance. +func TestHandleConfigReportsLockedKeys(t *testing.T) { + srv := newTestServer(t) + srv.Cfg = configWithFakeSecrets() + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + var got ConfigView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + for _, key := range []string{"db_path", "work_dir"} { + if got.Locked[key] == "" { + t.Errorf("Locked[%q] is empty, want a reason", key) + } + } +} + +// TestHandleConfigUpdateAppliesViaSeam proves the PATCH handler passes +// the decoded updates to the wired UpdateConfig seam and answers ok. +func TestHandleConfigUpdateAppliesViaSeam(t *testing.T) { + srv := newTestServer(t) + var got map[string]any + srv.UpdateConfig = func(_ context.Context, updates map[string]any) error { + got = updates + return nil + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config", + strings.NewReader(`{"updates": {"budgets.max_steps": 12}}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", w.Code, w.Body) + } + if got["budgets.max_steps"] != float64(12) { + t.Errorf("updates = %#v, want budgets.max_steps=12", got) + } +} + +// TestHandleConfigUpdateInvalidMapsTo400 proves a rejected update (the +// seam wraps its error with ErrConfigUpdateInvalid) answers 400. +func TestHandleConfigUpdateInvalidMapsTo400(t *testing.T) { + srv := newTestServer(t) + srv.UpdateConfig = func(context.Context, map[string]any) error { + return fmt.Errorf("%w: label is not runtime-tunable", ErrConfigUpdateInvalid) + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config", + strings.NewReader(`{"updates": {"label": "x"}}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400, body = %s", w.Code, w.Body) + } +} + +// TestHandleConfigUpdateUnavailableMapsTo503 proves a disabled overlay +// (ErrConfigUpdateUnavailable) answers 503, as does a server with no +// UpdateConfig seam at all. +func TestHandleConfigUpdateUnavailableMapsTo503(t *testing.T) { + srv := newTestServer(t) + srv.UpdateConfig = func(context.Context, map[string]any) error { + return fmt.Errorf("%w: overlay disabled by recovery flag", ErrConfigUpdateUnavailable) + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config", + strings.NewReader(`{"updates": {"label": "x"}}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503, body = %s", w.Code, w.Body) + } +} + +func TestHandleConfigUpdateWithoutSeamMapsTo503(t *testing.T) { + srv := newTestServer(t) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config", + strings.NewReader(`{"updates": {"label": "x"}}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503, body = %s", w.Code, w.Body) + } +} + func TestHandleChannelsReportsConfiguredState(t *testing.T) { srv := newTestServer(t) srv.Cfg = configWithFakeSecrets() diff --git a/internal/webui/server.go b/internal/webui/server.go index ddce8bd9b..2fa1d4a9c 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -71,6 +71,13 @@ type Server struct { // reload status. LastReload func() config.ReloadStatus + // UpdateConfig applies a set of dotted-path config updates through + // the same validate-persist-publish path as reload (wired by the + // composition root). Optional: when nil, PATCH /api/config answers + // 503. The handler never touches the Cfg Holder directly -- see the + // Cfg field doc. + UpdateConfig func(context.Context, map[string]any) error + // Channels reports actual adapter lifecycle, independently of configuration // presence. Nil preserves the configuration-only fallback for tests and // minimal embedding. @@ -169,6 +176,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /api/channels", s.handleChannels) mux.HandleFunc("POST /api/channels/{id}/reload", s.handleChannelReload) mux.HandleFunc("GET /api/config", s.handleConfig) + mux.HandleFunc("PATCH /api/config", s.handleConfigUpdate) mux.HandleFunc("GET /api/logs", s.handleLogs) mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs) mux.HandleFunc("GET /api/logs/stream", s.handleLogStream) From fa8a0d6d02a19024a981f8071533007c3cdff415 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 00:57:05 +1000 Subject: [PATCH 07/13] feat(webui): inline config editing on the Configuration page The dashboard's Configuration page can now change runtime-tunable settings without hand-editing TOML (issue #348). Scalar rows get an Edit affordance; Save PATCHes the dotted key to /api/config, which validates the materialised config before persisting to the runtime overlay and republishing. Per the design constraints: - Structured values (repositories, models, providers -- arrays and maps) render read-only with no edit affordance; they are not faked as editable. - Denylisted keys (db_path, work_dir) render explicitly disabled with the server's reason from the ConfigView.locked map, instead of a row that silently lacks an Edit button. - Bool fields edit via a select, ints parse client-side so a typo fails before a round trip, durations and strings pass through to the server which validates them. The server's error text is shown inline on a rejected save (validation failure, denylist, disabled overlay). - Enter saves, Escape cancels, Cancel restores the row. api.configUpdate PATCHes /api/config with {updates: {dotted.key: v}}. Verified: task check clean; 23 node tests pass; dist rebuilt and committed in the same change. --- ui/dist/assets/index.css | 2 +- ui/dist/assets/index.js | 12 +-- ui/src/base/api.js | 10 ++ ui/src/settings/settings.css | 93 ++++++++++++++++++ ui/src/settings/settings.js | 180 ++++++++++++++++++++++++++--------- 5 files changed, 246 insertions(+), 51 deletions(-) diff --git a/ui/dist/assets/index.css b/ui/dist/assets/index.css index cab20eb9d..5c5d84baf 100644 --- a/ui/dist/assets/index.css +++ b/ui/dist/assets/index.css @@ -1 +1 @@ -:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}@media (width<=1220px) and (width>=901px){.topbar{flex-wrap:wrap}.nav{border-radius:var(--radius-lg);flex-wrap:wrap;order:3;justify-content:center;width:100%;margin:0}}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;flex-wrap:nowrap;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{background:0 0;border:0;padding:0;overflow:hidden}.topbar-search-icon{display:none}.mobile-search-toggle{display:grid}.topbar-search input{opacity:0;pointer-events:none;width:0;transition:width var(--transition), opacity var(--transition);padding:0}.topbar-search.is-open,.topbar-search:focus-within{padding-right:var(--sp-2);border:1px solid var(--hairline);background:var(--surface-glass-strong)}.topbar-search.is-open input,.topbar-search:focus-within input{opacity:1;pointer-events:auto;width:min(9rem,34vw)}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-complete-actions{align-items:center;gap:var(--sp-2);display:flex}.setup-dismiss{width:28px;height:28px;font-size:var(--text-lg);line-height:1}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row{cursor:pointer}.task-expand{width:1.5rem;height:1.5rem;margin-right:var(--sp-2);color:var(--fg-muted);border:1px solid var(--border);font:inherit;cursor:pointer;background:0 0;border-radius:50%;padding:0;line-height:1}.task-expand:hover,.task-expand:focus-visible{color:var(--fg);border-color:var(--accent)}.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-actions{gap:var(--sp-1);white-space:nowrap;flex-wrap:wrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:180px;color:var(--danger);font-size:var(--text-xs);white-space:normal}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-detail-actions{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);padding-bottom:var(--sp-3);border-bottom:1px solid var(--hairline);display:flex}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}.table-scroll:has(.task-row){overflow:visible}.table:has(.task-row){display:block}.table:has(.task-row) tbody{display:block}.table-scroll>.table:has(.task-row){width:100%;min-width:0}.table:has(.task-row) thead{display:none}.task-row{gap:var(--sp-2) var(--sp-4);margin-bottom:var(--sp-3);padding:var(--sp-3);border:1px solid var(--hairline);border-radius:var(--radius-lg);background:var(--surface-glass);grid-template-columns:1fr 1fr;display:grid}.task-row td{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-1) 0;text-align:right;border:0;display:flex}.task-row td:before{content:attr(data-label);color:var(--fg-subtle);font-size:var(--text-xs);text-align:left;font-weight:500}.task-row td:nth-child(3),.task-row td:last-child{grid-column:1/-1}.task-row td:last-child{align-items:flex-start}.task-timeline-row,.task-timeline-row td{width:100%;display:block}.task-timeline-row td{margin:calc(var(--sp-2) * -1) 0 var(--sp-4);border-radius:0 0 var(--radius-lg) var(--radius-lg)}.task-detail-actions{flex-direction:column;align-items:flex-start}}@media (width<=480px){.task-row{grid-template-columns:1fr}.task-row td:nth-child(3),.task-row td:last-child{grid-column:auto}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-4) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.cfg-rows{gap:var(--sp-2);flex-direction:column;display:flex}.cfg-row{justify-content:space-between;align-items:baseline;gap:var(--sp-4);padding:var(--sp-2) 0;border-bottom:1px solid var(--border);display:flex}.cfg-section .cfg-rows{gap:0}.cfg-section .cfg-row{padding:var(--sp-1) 0}.cfg-row:last-child{border-bottom:0}.cfg-label{font-size:var(--text-sm);color:var(--fg-muted)}.cfg-value{font-size:var(--text-sm);color:var(--fg);text-align:right}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.chat-page{flex-direction:column;height:calc(100vh - 5rem);display:flex;overflow:hidden}.chat-page-content{flex-direction:column;flex:auto;min-height:0;display:flex;overflow:hidden}.chat-topbar{flex:none;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;display:flex}.chat-kicker,.chat-workspace-label{color:var(--fg-muted);letter-spacing:.12em;font-size:.68rem;font-weight:700}.chat-topbar-actions{align-items:center;gap:.55rem;display:flex}.chat-topbar-actions .chat-select{min-width:0;max-width:14rem}.chat-update-panel{border:1px solid var(--border);color:var(--fg-muted);border-radius:.75rem;flex:none;justify-content:space-between;align-items:center;gap:1rem;margin:0 0 .75rem;padding:.7rem .9rem;font-size:.8rem;display:flex}.chat-update-panel>div:first-child{gap:.2rem;display:grid}.chat-update-panel strong{color:var(--fg)}.chat-update-actions{flex-shrink:0;gap:.45rem;display:flex}.chat-dangerous-panel{border:1px solid color-mix(in srgb, var(--danger) 45%, var(--border));border-radius:.75rem;flex:none;margin:0 0 .75rem;padding:.8rem .9rem}.chat-dangerous-head,.chat-dangerous-controls,.chat-dangerous-pending{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-dangerous-head{margin-bottom:.7rem}.chat-dangerous-controls{flex-wrap:wrap;align-items:stretch}.chat-dangerous-controls>div{flex:18rem;gap:.45rem;display:flex}.chat-dangerous-input{background:var(--surface-hover);min-width:0;color:var(--fg);border:1px solid var(--border-strong);font:inherit;border-radius:.5rem;flex:1;padding:.5rem .65rem}.chat-dangerous-pending-list{gap:.45rem;margin-top:.75rem;display:grid}.chat-dangerous-pending{border-top:1px solid var(--border);color:var(--fg-muted);padding-top:.55rem;font-size:.8rem}.chat-layout{flex:auto;grid-template-columns:242px minmax(0,1fr);gap:.75rem;min-height:0;display:grid;overflow:hidden}.chat-sidebar,.chat-workspace{background:var(--surface);border:1px solid var(--border);border-radius:1rem}.chat-sidebar{padding:.8rem;overflow-y:auto}.chat-sidebar-head,.chat-toolbar,.chat-compose-actions{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-session-list{gap:.35rem;margin-top:1rem;display:grid}.chat-session{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.65rem;gap:.25rem;padding:.7rem;display:grid}.chat-session:hover,.chat-session.active{background:var(--surface-hover);color:var(--fg);border-color:var(--border-strong)}.chat-session span{font-size:.72rem}.chat-workspace{grid-template-rows:auto minmax(0,1fr) auto;min-width:0;display:grid;overflow:hidden}.chat-workspace-head{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;padding:.85rem 1.1rem;display:flex}.chat-session-tools{color:var(--fg-muted);margin-left:.6rem;font-size:.78rem;position:relative}.chat-session-tools summary{cursor:pointer}.chat-session-tool-list{z-index:2;background:var(--surface);border:1px solid var(--border-strong);border-radius:.65rem;flex-wrap:wrap;gap:.35rem;width:min(22rem,72vw);padding:.55rem;display:flex;position:absolute;top:calc(100% + .45rem);right:0;box-shadow:0 .7rem 2rem #0000004d}.chat-select{background:var(--surface-hover);color:var(--fg);border:1px solid var(--border-strong);border-radius:.5rem;padding:.5rem .65rem}.chat-transcript{align-content:start;gap:1rem;padding:1.25rem;display:grid;overflow:auto}.chat-empty-state{text-align:center;place-self:center;width:min(100%,40rem);padding:3rem 1rem}.chat-empty-mark{border:1px solid var(--border-strong);width:2.6rem;height:2.6rem;color:var(--accent);border-radius:.8rem;place-items:center;margin:0 auto 1rem;font-weight:700;display:grid}.chat-empty-state h2{letter-spacing:-.04em;margin:0;font-size:clamp(1.5rem,3vw,2.25rem)}.chat-empty-state p{color:var(--fg-muted);margin:.6rem 0 1.4rem}.chat-prompt-grid{flex-wrap:wrap;justify-content:center;gap:.5rem;display:flex}.chat-prompt{border:1px solid var(--border);background:var(--surface-hover);color:var(--fg-muted);cursor:pointer;border-radius:999px;padding:.55rem .75rem}.chat-prompt:hover{color:var(--fg);border-color:var(--border-strong)}.chat-bubble-row{display:flex}.chat-bubble-row.user{justify-content:flex-end}.chat-bubble{background:var(--surface-hover);border-radius:.85rem;max-width:min(78ch,86%);padding:.8rem 1rem;line-height:1.5}.chat-bubble-row.user .chat-bubble{background:color-mix(in srgb, var(--accent) 18%, var(--surface))}.chat-bubble-meta{color:var(--fg-muted);margin-bottom:.3rem;font-size:.7rem}.chat-bubble-text{white-space:pre-wrap;overflow-wrap:anywhere}.chat-bubble-text p{margin:0 0 .7rem}.chat-bubble-text p:last-child{margin-bottom:0}.chat-bubble-text h1,.chat-bubble-text h2,.chat-bubble-text h3{letter-spacing:-.02em;margin:.2rem 0 .6rem;line-height:1.2}.chat-bubble-text h1{font-size:1.25rem}.chat-bubble-text h2{font-size:1.1rem}.chat-bubble-text h3{font-size:1rem}.chat-bubble-text ul,.chat-bubble-text ol{margin:.25rem 0 .75rem;padding-left:1.35rem}.chat-bubble-text blockquote{border-left:3px solid var(--accent);color:var(--fg-muted);margin:.5rem 0;padding:.35rem .75rem}.chat-bubble-text code{background:color-mix(in srgb, var(--fg) 10%, transparent);border-radius:.3rem;padding:.1rem .3rem;font-size:.9em}.chat-bubble-text pre{border:1px solid var(--border);background:color-mix(in srgb, var(--surface) 75%, #000);border-radius:.5rem;margin:.6rem 0;padding:.75rem;overflow:auto}.chat-bubble-text pre code{background:0 0;padding:0}.chat-bubble-text a{color:var(--accent)}.chat-bubble-text table{border-collapse:collapse;width:100%;margin:.7rem 0;font-size:.92em}.chat-bubble-text th,.chat-bubble-text td{text-align:left;border:1px solid var(--border);padding:.45rem .6rem}.chat-bubble-text th{color:var(--fg);background:color-mix(in srgb, var(--surface) 70%, transparent);font-weight:700}.chat-compose{border-top:1px solid var(--border);padding:.85rem 1rem 1rem}.chat-composer-shell{background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:.9rem;padding:.7rem .8rem .55rem;position:relative}.chat-composer{resize:vertical;box-sizing:border-box;width:100%;min-height:3.3rem;color:var(--fg);font:inherit;background:0 0;border:0;padding:.25rem 0}.chat-composer:focus{outline:0}.chat-command-menu{z-index:3;background:var(--surface);border:1px solid var(--border-strong);border-radius:.7rem;gap:.15rem;max-height:18rem;padding:.35rem;display:grid;position:absolute;bottom:calc(100% - .25rem);left:.8rem;right:.8rem;overflow:auto;box-shadow:0 .7rem 2rem #0000004d}.chat-command-menu[hidden]{display:none}.chat-command-option{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.45rem;grid-template-columns:minmax(8rem,14rem) 1fr;align-items:center;gap:.65rem;padding:.5rem .6rem;display:grid}.chat-command-option:hover,.chat-command-option[aria-selected=true]{color:var(--fg);background:var(--surface-hover);border-color:var(--border)}.chat-command-option code{color:var(--fg)}.chat-compose-actions{margin-top:.55rem}.chat-hint,.chat-empty{color:var(--fg-muted);font-size:.78rem}.chat-command-help{color:var(--fg-muted);margin-right:auto;font-size:.78rem}.chat-command-help summary{cursor:pointer}.chat-command-list{min-width:min(34rem,70vw);max-width:40rem;padding-top:.4rem;line-height:1.45}.chat-command-item{grid-template-columns:minmax(10rem,16rem) 1fr;gap:.7rem;padding:.3rem 0;display:grid}.chat-command-item code{color:var(--fg)}@media (width<=760px){.chat-topbar,.chat-topbar-actions{flex-direction:column;align-items:flex-start}.chat-layout{grid-template-columns:1fr}.chat-sidebar{max-height:14rem;overflow:auto}}@media (width<=520px){.chat-update-panel{flex-direction:column;align-items:flex-start}} +:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}@media (width<=1220px) and (width>=901px){.topbar{flex-wrap:wrap}.nav{border-radius:var(--radius-lg);flex-wrap:wrap;order:3;justify-content:center;width:100%;margin:0}}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;flex-wrap:nowrap;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{background:0 0;border:0;padding:0;overflow:hidden}.topbar-search-icon{display:none}.mobile-search-toggle{display:grid}.topbar-search input{opacity:0;pointer-events:none;width:0;transition:width var(--transition), opacity var(--transition);padding:0}.topbar-search.is-open,.topbar-search:focus-within{padding-right:var(--sp-2);border:1px solid var(--hairline);background:var(--surface-glass-strong)}.topbar-search.is-open input,.topbar-search:focus-within input{opacity:1;pointer-events:auto;width:min(9rem,34vw)}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-complete-actions{align-items:center;gap:var(--sp-2);display:flex}.setup-dismiss{width:28px;height:28px;font-size:var(--text-lg);line-height:1}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row{cursor:pointer}.task-expand{width:1.5rem;height:1.5rem;margin-right:var(--sp-2);color:var(--fg-muted);border:1px solid var(--border);font:inherit;cursor:pointer;background:0 0;border-radius:50%;padding:0;line-height:1}.task-expand:hover,.task-expand:focus-visible{color:var(--fg);border-color:var(--accent)}.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-actions{gap:var(--sp-1);white-space:nowrap;flex-wrap:wrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:180px;color:var(--danger);font-size:var(--text-xs);white-space:normal}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-detail-actions{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);padding-bottom:var(--sp-3);border-bottom:1px solid var(--hairline);display:flex}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}.table-scroll:has(.task-row){overflow:visible}.table:has(.task-row){display:block}.table:has(.task-row) tbody{display:block}.table-scroll>.table:has(.task-row){width:100%;min-width:0}.table:has(.task-row) thead{display:none}.task-row{gap:var(--sp-2) var(--sp-4);margin-bottom:var(--sp-3);padding:var(--sp-3);border:1px solid var(--hairline);border-radius:var(--radius-lg);background:var(--surface-glass);grid-template-columns:1fr 1fr;display:grid}.task-row td{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-1) 0;text-align:right;border:0;display:flex}.task-row td:before{content:attr(data-label);color:var(--fg-subtle);font-size:var(--text-xs);text-align:left;font-weight:500}.task-row td:nth-child(3),.task-row td:last-child{grid-column:1/-1}.task-row td:last-child{align-items:flex-start}.task-timeline-row,.task-timeline-row td{width:100%;display:block}.task-timeline-row td{margin:calc(var(--sp-2) * -1) 0 var(--sp-4);border-radius:0 0 var(--radius-lg) var(--radius-lg)}.task-detail-actions{flex-direction:column;align-items:flex-start}}@media (width<=480px){.task-row{grid-template-columns:1fr}.task-row td:nth-child(3),.task-row td:last-child{grid-column:auto}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-4) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.cfg-rows{gap:var(--sp-2);flex-direction:column;display:flex}.cfg-row{justify-content:space-between;align-items:baseline;gap:var(--sp-4);padding:var(--sp-2) 0;border-bottom:1px solid var(--border);display:flex}.cfg-section .cfg-rows{gap:0}.cfg-section .cfg-row{padding:var(--sp-1) 0}.cfg-row:last-child{border-bottom:0}.cfg-label{font-size:var(--text-sm);color:var(--fg-muted)}.cfg-value{font-size:var(--text-sm);color:var(--fg);text-align:right}.cfg-value-cell{justify-content:flex-end;align-items:center;gap:var(--sp-2);min-width:0;display:flex}.cfg-edit{font:inherit;font-size:var(--text-xs);color:var(--fg-muted);background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:2px var(--sp-2);cursor:pointer;flex:none}.cfg-edit:hover{color:var(--fg);border-color:var(--accent)}.cfg-editing{flex-wrap:wrap}.cfg-input{font:inherit;font-size:var(--text-xs);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);flex:10rem;min-width:0}.cfg-input:focus{outline:2px solid var(--accent);outline-offset:-1px}.cfg-save,.cfg-cancel{font:inherit;font-size:var(--text-xs);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);cursor:pointer;flex:none}.cfg-save{background:var(--accent);border:1px solid var(--accent);color:var(--accent-fg);font-weight:500}.cfg-save:disabled{opacity:.6;cursor:default}.cfg-cancel{border:1px solid var(--border-strong);color:var(--fg-muted);background:0 0}.cfg-cancel:hover{color:var(--fg)}.cfg-locked{font-size:var(--text-xs);color:var(--fg-subtle);font-style:italic}.cfg-error{font-size:var(--text-xs);color:var(--danger);text-align:right;flex-basis:100%}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.chat-page{flex-direction:column;height:calc(100vh - 5rem);display:flex;overflow:hidden}.chat-page-content{flex-direction:column;flex:auto;min-height:0;display:flex;overflow:hidden}.chat-topbar{flex:none;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;display:flex}.chat-kicker,.chat-workspace-label{color:var(--fg-muted);letter-spacing:.12em;font-size:.68rem;font-weight:700}.chat-topbar-actions{align-items:center;gap:.55rem;display:flex}.chat-topbar-actions .chat-select{min-width:0;max-width:14rem}.chat-update-panel{border:1px solid var(--border);color:var(--fg-muted);border-radius:.75rem;flex:none;justify-content:space-between;align-items:center;gap:1rem;margin:0 0 .75rem;padding:.7rem .9rem;font-size:.8rem;display:flex}.chat-update-panel>div:first-child{gap:.2rem;display:grid}.chat-update-panel strong{color:var(--fg)}.chat-update-actions{flex-shrink:0;gap:.45rem;display:flex}.chat-dangerous-panel{border:1px solid color-mix(in srgb, var(--danger) 45%, var(--border));border-radius:.75rem;flex:none;margin:0 0 .75rem;padding:.8rem .9rem}.chat-dangerous-head,.chat-dangerous-controls,.chat-dangerous-pending{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-dangerous-head{margin-bottom:.7rem}.chat-dangerous-controls{flex-wrap:wrap;align-items:stretch}.chat-dangerous-controls>div{flex:18rem;gap:.45rem;display:flex}.chat-dangerous-input{background:var(--surface-hover);min-width:0;color:var(--fg);border:1px solid var(--border-strong);font:inherit;border-radius:.5rem;flex:1;padding:.5rem .65rem}.chat-dangerous-pending-list{gap:.45rem;margin-top:.75rem;display:grid}.chat-dangerous-pending{border-top:1px solid var(--border);color:var(--fg-muted);padding-top:.55rem;font-size:.8rem}.chat-layout{flex:auto;grid-template-columns:242px minmax(0,1fr);gap:.75rem;min-height:0;display:grid;overflow:hidden}.chat-sidebar,.chat-workspace{background:var(--surface);border:1px solid var(--border);border-radius:1rem}.chat-sidebar{padding:.8rem;overflow-y:auto}.chat-sidebar-head,.chat-toolbar,.chat-compose-actions{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-session-list{gap:.35rem;margin-top:1rem;display:grid}.chat-session{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.65rem;gap:.25rem;padding:.7rem;display:grid}.chat-session:hover,.chat-session.active{background:var(--surface-hover);color:var(--fg);border-color:var(--border-strong)}.chat-session span{font-size:.72rem}.chat-workspace{grid-template-rows:auto minmax(0,1fr) auto;min-width:0;display:grid;overflow:hidden}.chat-workspace-head{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;padding:.85rem 1.1rem;display:flex}.chat-session-tools{color:var(--fg-muted);margin-left:.6rem;font-size:.78rem;position:relative}.chat-session-tools summary{cursor:pointer}.chat-session-tool-list{z-index:2;background:var(--surface);border:1px solid var(--border-strong);border-radius:.65rem;flex-wrap:wrap;gap:.35rem;width:min(22rem,72vw);padding:.55rem;display:flex;position:absolute;top:calc(100% + .45rem);right:0;box-shadow:0 .7rem 2rem #0000004d}.chat-select{background:var(--surface-hover);color:var(--fg);border:1px solid var(--border-strong);border-radius:.5rem;padding:.5rem .65rem}.chat-transcript{align-content:start;gap:1rem;padding:1.25rem;display:grid;overflow:auto}.chat-empty-state{text-align:center;place-self:center;width:min(100%,40rem);padding:3rem 1rem}.chat-empty-mark{border:1px solid var(--border-strong);width:2.6rem;height:2.6rem;color:var(--accent);border-radius:.8rem;place-items:center;margin:0 auto 1rem;font-weight:700;display:grid}.chat-empty-state h2{letter-spacing:-.04em;margin:0;font-size:clamp(1.5rem,3vw,2.25rem)}.chat-empty-state p{color:var(--fg-muted);margin:.6rem 0 1.4rem}.chat-prompt-grid{flex-wrap:wrap;justify-content:center;gap:.5rem;display:flex}.chat-prompt{border:1px solid var(--border);background:var(--surface-hover);color:var(--fg-muted);cursor:pointer;border-radius:999px;padding:.55rem .75rem}.chat-prompt:hover{color:var(--fg);border-color:var(--border-strong)}.chat-bubble-row{display:flex}.chat-bubble-row.user{justify-content:flex-end}.chat-bubble{background:var(--surface-hover);border-radius:.85rem;max-width:min(78ch,86%);padding:.8rem 1rem;line-height:1.5}.chat-bubble-row.user .chat-bubble{background:color-mix(in srgb, var(--accent) 18%, var(--surface))}.chat-bubble-meta{color:var(--fg-muted);margin-bottom:.3rem;font-size:.7rem}.chat-bubble-text{white-space:pre-wrap;overflow-wrap:anywhere}.chat-bubble-text p{margin:0 0 .7rem}.chat-bubble-text p:last-child{margin-bottom:0}.chat-bubble-text h1,.chat-bubble-text h2,.chat-bubble-text h3{letter-spacing:-.02em;margin:.2rem 0 .6rem;line-height:1.2}.chat-bubble-text h1{font-size:1.25rem}.chat-bubble-text h2{font-size:1.1rem}.chat-bubble-text h3{font-size:1rem}.chat-bubble-text ul,.chat-bubble-text ol{margin:.25rem 0 .75rem;padding-left:1.35rem}.chat-bubble-text blockquote{border-left:3px solid var(--accent);color:var(--fg-muted);margin:.5rem 0;padding:.35rem .75rem}.chat-bubble-text code{background:color-mix(in srgb, var(--fg) 10%, transparent);border-radius:.3rem;padding:.1rem .3rem;font-size:.9em}.chat-bubble-text pre{border:1px solid var(--border);background:color-mix(in srgb, var(--surface) 75%, #000);border-radius:.5rem;margin:.6rem 0;padding:.75rem;overflow:auto}.chat-bubble-text pre code{background:0 0;padding:0}.chat-bubble-text a{color:var(--accent)}.chat-bubble-text table{border-collapse:collapse;width:100%;margin:.7rem 0;font-size:.92em}.chat-bubble-text th,.chat-bubble-text td{text-align:left;border:1px solid var(--border);padding:.45rem .6rem}.chat-bubble-text th{color:var(--fg);background:color-mix(in srgb, var(--surface) 70%, transparent);font-weight:700}.chat-compose{border-top:1px solid var(--border);padding:.85rem 1rem 1rem}.chat-composer-shell{background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:.9rem;padding:.7rem .8rem .55rem;position:relative}.chat-composer{resize:vertical;box-sizing:border-box;width:100%;min-height:3.3rem;color:var(--fg);font:inherit;background:0 0;border:0;padding:.25rem 0}.chat-composer:focus{outline:0}.chat-command-menu{z-index:3;background:var(--surface);border:1px solid var(--border-strong);border-radius:.7rem;gap:.15rem;max-height:18rem;padding:.35rem;display:grid;position:absolute;bottom:calc(100% - .25rem);left:.8rem;right:.8rem;overflow:auto;box-shadow:0 .7rem 2rem #0000004d}.chat-command-menu[hidden]{display:none}.chat-command-option{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.45rem;grid-template-columns:minmax(8rem,14rem) 1fr;align-items:center;gap:.65rem;padding:.5rem .6rem;display:grid}.chat-command-option:hover,.chat-command-option[aria-selected=true]{color:var(--fg);background:var(--surface-hover);border-color:var(--border)}.chat-command-option code{color:var(--fg)}.chat-compose-actions{margin-top:.55rem}.chat-hint,.chat-empty{color:var(--fg-muted);font-size:.78rem}.chat-command-help{color:var(--fg-muted);margin-right:auto;font-size:.78rem}.chat-command-help summary{cursor:pointer}.chat-command-list{min-width:min(34rem,70vw);max-width:40rem;padding-top:.4rem;line-height:1.45}.chat-command-item{grid-template-columns:minmax(10rem,16rem) 1fr;gap:.7rem;padding:.3rem 0;display:grid}.chat-command-item code{color:var(--fg)}@media (width<=760px){.chat-topbar,.chat-topbar-actions{flex-direction:column;align-items:flex-start}.chat-layout{grid-template-columns:1fr}.chat-sidebar{max-height:14rem;overflow:auto}}@media (width<=520px){.chat-update-panel{flex-direction:column;align-items:flex-start}} diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index b9c5e9618..ca5909e07 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -1,12 +1,12 @@ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n!==void 0&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,help:``};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=c[e]||c.dashboard,r}async function u(e){let t=await fetch(e,{headers:{Accept:`application/json`},signal:AbortSignal.timeout(15e3)});if(t.status===401)throw new p(`unauthorised`,401);if(!t.ok)throw new p(`${t.status} ${t.statusText}`,t.status);return t.json()}function d(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function f(e){try{let t=(await e.text()).trim();if(t)return t.split(` -`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),logs:e=>u(`/api/logs`+d(e)),memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function _({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&v(o,u===!1?`var(--danger)`:`var(--ok)`))}function v(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=``,u}function y({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`var(--danger)`,o=r/2,s=r/2,c=2*Math.PI*62*(240/360),l=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${o+62*Math.cos(n)} ${s+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${o+62*Math.cos(r)} ${s+62*Math.sin(r)}`].join(` `)},u=e(`svg.gauge`,{viewBox:`0 0 ${r} ${r*.78}`,role:`img`,"aria-label":`${n}: ${i}%`});return u.innerHTML=` +`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},logs:e=>u(`/api/logs`+d(e)),memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function _({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&v(o,u===!1?`var(--danger)`:`var(--ok)`))}function v(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=``,u}function y({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`var(--danger)`,o=r/2,s=r/2,c=2*Math.PI*62*(240/360),l=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${o+62*Math.cos(n)} ${s+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${o+62*Math.cos(r)} ${s+62*Math.sin(r)}`].join(` `)},u=e(`svg.gauge`,{viewBox:`0 0 ${r} ${r*.78}`,role:`img`,"aria-label":`${n}: ${i}%`});return u.innerHTML=` `,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function I(e,t){A(u,e,t)}function L(e){j(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function D(t,n){let r=O(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function O(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function k(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function A(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),y({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function j(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),b([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function M(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function N(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var P=new Set([`waiting_human`,`parked`]),F=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function I(e){let t=e?.get?.(`status`)||``;return F.has(t)?t:``}function L(e,t){return t?t===`needs_you`?P.has(e.status):e.status===t:!0}var R={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function z(e){return R[e]||e||`Unknown`}function B(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=I(t),f=``,p=Number(t.get(`task`)),h=Number.isFinite(p)&&p>0?p:null,g=h!==null,v=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(R).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,v]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),h&&u.some(e=>String(e.id)===String(h))&&W(h),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,_({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),_({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>L(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),h===e.id&&l.append(H(e));k()}function k(){!g||!h||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${h}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=h===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),h=h===t.id?null:t.id,O(),h===t.id&&W(t.id)};return e(`tr.task-row`,{...N(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),B(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(z(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await m.taskAction(e,t),x.delete(e),t===`archive`&&(h=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function P(e){return!v||!e.owner||!e.repo?null:`${v.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=P(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function B(t){let n=P(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=P(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await m.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function V(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var H={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function U(e){return H[e]?H[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function W(e,t){return t?Math.round(e/t*100):0}function G(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await m.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},U(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.cfg-rows`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await m.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=W(t.merged,t.runs);return e(`tr`,e(`td.strong`,U(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),G(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),G(W(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),G(W(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await m.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},`Refresh`))),r)}async function a(){try{o(await m.config())}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}function o(t){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}n(r,oe(t.identity),se(t.repositories),le(t.models,t.providers),de(t.budgets),fe(t.agent),me(t.storage,t.containers),ge(t.web),ae(t.provenance))}return t}function ae(t){return t?.length?K(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.cfg-rows`,...t.map(e=>q(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):K(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function K(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function q(t,n){return e(`div.cfg-row`,e(`span.cfg-label`,t),e(`span.cfg-value.mono`,n??`—`))}function oe(t){return t?K(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.cfg-rows`,q(`Bot account`,t.bot_user),q(`Commit author email`,t.bot_email),q(`Pickup label`,t.label),q(`Forge type`,t.forge_type),q(`Forge host`,t.forge_host),q(`Max diff size (lines)`,t.diff_cap_lines))):K(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function se(t){return t?.length?K(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,ce(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):K(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function ce(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function le(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.cfg-rows`,...i.map(([e,t])=>q(ue(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return K(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ue(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function de(t){return t?K(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.cfg-rows`,q(`Max steps`,t.max_steps||`Unlimited`),q(`Max tokens`,t.max_tokens||`Unlimited`),q(`Wall clock`,t.wall_clock),q(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`))):K(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function fe(t){return t?K(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.cfg-rows`,q(`Execution mode`,pe(t.mode)),q(`Worker command`,t.command),q(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):K(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function pe(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function me(t,n){let r=[];return t&&r.push(e(`h3.cfg-subhead`,`Paths`),e(`div.cfg-rows`,q(`Work directory`,t.work_dir),q(`State path prefix`,t.db_path),q(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`),q(`Daemon plugin directory`,t.plugin_dir||`None`),q(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`))),n&&r.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.cfg-rows`,q(`Sandboxing enabled`,n.enabled?`Yes`:`No`),q(`Agent image`,n.image||`Not set`),q(`Max concurrent tasks`,n.max_concurrency||`Unlimited`),q(`Container max lifetime`,n.max_uptime),q(`Persistent volume retention`,n.volume_ttl),q(`How images are refreshed`,he(n.pull_policy)),q(`Docker network`,n.network||`Auto-detected`))),r.length||r.push(s(`Not available`)),K(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...r)}function he(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function ge(t){return t?K(`Dashboard`,`This dashboard's own listen address.`,e(`div.cfg-rows`,q(`Listen address`,t.listen===`off`?`Disabled`:t.listen))):K(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var _e=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function ve(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function ye(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},..._e.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Te(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(we(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(be(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(be(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(xe)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function be(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function xe(t){let n=t.fields||{};return e(`div.log-row.log-${ve(t.level)}`,e(`span.log-time.mono`,Ce(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(Se(n))))))}function Se(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Ce(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function we(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Te(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Ee(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(De)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function De(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Oe(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Oe(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var ke=`
+ class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function I(e,t){A(u,e,t)}function L(e){j(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function D(t,n){let r=O(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function O(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function k(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function A(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),y({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function j(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),b([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function M(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function N(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var P=new Set([`waiting_human`,`parked`]),F=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function I(e){let t=e?.get?.(`status`)||``;return F.has(t)?t:``}function L(e,t){return t?t===`needs_you`?P.has(e.status):e.status===t:!0}var R={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function z(e){return R[e]||e||`Unknown`}function B(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=I(t),f=``,p=Number(t.get(`task`)),h=Number.isFinite(p)&&p>0?p:null,g=h!==null,v=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(R).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,v]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),h&&u.some(e=>String(e.id)===String(h))&&W(h),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,_({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),_({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>L(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),h===e.id&&l.append(H(e));k()}function k(){!g||!h||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${h}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=h===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),h=h===t.id?null:t.id,O(),h===t.id&&W(t.id)};return e(`tr.task-row`,{...N(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),B(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(z(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await m.taskAction(e,t),x.delete(e),t===`archive`&&(h=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function P(e){return!v||!e.owner||!e.repo?null:`${v.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=P(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function B(t){let n=P(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=P(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await m.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function V(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var H={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function U(e){return H[e]?H[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function W(e,t){return t?Math.round(e/t*100):0}function G(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await m.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},U(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.cfg-rows`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await m.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=W(t.merged,t.runs);return e(`tr`,e(`td.strong`,U(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),G(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),G(W(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),G(W(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await m.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},`Refresh`))),r)}async function a(){try{o(await m.config(),a)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}function o(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},onSaved:i};n(r,ce(t.identity,a),le(t.repositories),de(t.models,t.providers),pe(t.budgets,a),me(t.agent,a),ge(t.storage,t.containers,a),ve(t.web,a),ae(t.provenance))}return t}function ae(t){return t?.length?K(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.cfg-rows`,...t.map(e=>q(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):K(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function K(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function q(t,n,r){let i=e(`span.cfg-label`,t);if(!r?.key)return e(`div.cfg-row`,i,e(`span.cfg-value.mono`,n??`—`));if(r.locked?.[r.key])return e(`div.cfg-row`,i,e(`div.cfg-value-cell`,e(`span.cfg-value.mono`,n??`—`),e(`span.cfg-locked`,r.locked[r.key])));let a=e(`span.cfg-value.mono`,n??`—`),o=e(`button.cfg-edit`,{title:`Edit ${t}`},`Edit`),s=e(`div.cfg-value-cell`,a,o),c=e(`div.cfg-row`,i,s);return o.addEventListener(`click`,()=>oe(c,s,t,r)),c}function oe(t,n,r,i){let{key:a,type:o,raw:s,onSaved:c}=i,l=o===`bool`?e(`select.cfg-input`,e(`option`,{value:`true`,selected:s===!0},`true`),e(`option`,{value:`false`,selected:s===!1},`false`)):e(`input.cfg-input`,{type:`text`,value:String(s??``)}),u=e(`button.cfg-save`,{type:`button`},`Save`),d=e(`button.cfg-cancel`,{type:`button`},`Cancel`),f=e(`span.cfg-error`),p=e(`div.cfg-value-cell.cfg-editing`,l,u,d,f);t.replaceChild(p,n),l.focus();let h=()=>t.replaceChild(n,p);d.addEventListener(`click`,h),l.addEventListener(`keydown`,e=>{e.key===`Enter`&&u.click(),e.key===`Escape`&&h()}),u.addEventListener(`click`,async()=>{let e=se(o,l.value);if(e.error){f.textContent=e.error;return}u.disabled=!0;try{await m.configUpdate({[a]:e.value}),c?.()}catch(e){f.textContent=String(e.message||e),u.disabled=!1}})}function se(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}function ce(t,n){return t?K(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.cfg-rows`,q(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),q(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),q(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),q(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),q(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),q(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):K(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function le(t){return t?.length?K(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,ue(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):K(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function ue(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function de(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.cfg-rows`,...i.map(([e,t])=>q(fe(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return K(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function fe(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function pe(t,n){return t?K(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.cfg-rows`,q(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),q(`Max tokens`,t.max_tokens||`Unlimited`,{key:`budgets.max_tokens`,type:`int`,raw:t.max_tokens,...n}),q(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),q(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):K(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function me(t,n){return t?K(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.cfg-rows`,q(`Execution mode`,he(t.mode),{key:`agent.mode`,type:`string`,raw:t.mode,...n}),q(`Worker command`,t.command,{key:`agent.command`,type:`string`,raw:t.command,...n}),q(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):K(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function he(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function ge(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.cfg-rows`,q(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),q(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),q(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),q(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),q(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.cfg-rows`,q(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),q(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),q(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),q(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),q(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),q(`How images are refreshed`,_e(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),q(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),K(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function _e(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function ve(t,n){return t?K(`Dashboard`,`This dashboard's own listen address.`,e(`div.cfg-rows`,q(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):K(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var ye=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function be(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function xe(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...ye.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:De(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(Ee(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(Se(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(Se(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Ce)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function Se(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Ce(t){let n=t.fields||{};return e(`div.log-row.log-${be(t.level)}`,e(`span.log-time.mono`,Te(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(we(n))))))}function we(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Te(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function Ee(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function De(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Oe(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(ke)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function ke(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ae(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ae(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var je=`
ARCHIE WORKSPACE

Chat

@@ -71,10 +71,10 @@
-`;function Ae(){let e=document.createElement(`template`);e.innerHTML=ke.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function J(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return ii&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i{i.length&&(n.append(e(`p`,J(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;te(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` -`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Me(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Ne(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Pe(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?je(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=je(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}var Fe=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(Fe);return e||(e=crypto.randomUUID(),localStorage.setItem(Fe,e)),e}function Ie(e){return{text:e,sourceID:crypto.randomUUID()}}function Le(e){return{...e}}function Re(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?Le(e.turn):Ie(r),isRetry:n}}function ze({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Ne(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function Be(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,Ve(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function Ve(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function He(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function Ue(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function We(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function Ge(e){return e?.status===501?null:`Could not check for updates.`}function Ke(){let{root:t,refs:n}=Ae(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(Pe(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await m.chatUpdate();E=e?.snapshot||null,Ue(h,e,{onDefer:async()=>{await m.chatUpdateDefer(E),Ue(h,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(E),c.textContent=`Update started`,I()}})}catch(t){let n=Ge(t);h.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{We(g,await m.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await m.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await m.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await m.chatSessions();C=e.sessions||[],D=e,Be({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=He(y,e.commands),ze({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await m.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,ze({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await m.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let t=await m.chatMessages(e);for(let e of t)j(e);i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=Re(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-bubble-text`)));l||i.append(u),u.querySelector(`.chat-retry`)?.remove();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` +`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=Y(l),d=t+1e(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` +`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Pe(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Fe(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Ie(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?Ne(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=Ne(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}var Le=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(Le);return e||(e=crypto.randomUUID(),localStorage.setItem(Le,e)),e}function Re(e){return{text:e,sourceID:crypto.randomUUID()}}function ze(e){return{...e}}function Be(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?ze(e.turn):Re(r),isRetry:n}}function Ve({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Fe(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function He(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,Ue(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function Ue(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function We(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function Ge(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function Ke(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function qe(e){return e?.status===501?null:`Could not check for updates.`}function Je(){let{root:t,refs:n}=Me(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(Ie(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await m.chatUpdate();E=e?.snapshot||null,Ge(h,e,{onDefer:async()=>{await m.chatUpdateDefer(E),Ge(h,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(E),c.textContent=`Update started`,I()}})}catch(t){let n=qe(t);h.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{Ke(g,await m.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await m.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await m.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await m.chatSessions();C=e.sessions||[],D=e,He({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=We(y,e.commands),Ve({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await m.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,Ve({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await m.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let t=await m.chatMessages(e);for(let e of t)j(e);i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=Be(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-bubble-text`)));l||i.append(u),u.querySelector(`.chat-retry`)?.remove();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` `);i=a.pop()||``;for(let e of a){let t=e.split(` -`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=Le(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{Ve({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:Ke},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:ye},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:Ee},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:ie}],qe=`archie.theme`;function Je(e){document.documentElement.dataset.theme=e,localStorage.setItem(qe,e)}function $(){return localStorage.getItem(qe)||`dark`}function Ye(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Je($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function Xe(){Je($());let t=e(`main.main`),r=Ye(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):Ze(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function Ze(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}Xe(); \ No newline at end of file +`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=ze(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{Ue({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:Je},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:xe},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:Oe},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:ie}],Ye=`archie.theme`;function Xe(e){document.documentElement.dataset.theme=e,localStorage.setItem(Ye,e)}function $(){return localStorage.getItem(Ye)||`dark`}function Ze(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Xe($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function Qe(){Xe($());let t=e(`main.main`),r=Ze(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):$e(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function $e(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}Qe(); \ No newline at end of file diff --git a/ui/src/base/api.js b/ui/src/base/api.js index dcb5e1575..7f7a51d21 100644 --- a/ui/src/base/api.js +++ b/ui/src/base/api.js @@ -86,6 +86,16 @@ export const api = { return res.json(); }, config: () => req("/api/config"), + configUpdate: async (updates) => { + const res = await fetch("/api/config", { + method: "PATCH", + headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" }, + body: JSON.stringify({ updates }), + signal: AbortSignal.timeout(15000), + }); + if (!res.ok) throw new ApiError(await errorMessage(res), res.status); + return res.json(); + }, logs: (params) => req("/api/logs" + qs(params)), memory: () => req("/api/memory"), chatSessions: () => req("/api/chat/sessions"), diff --git a/ui/src/settings/settings.css b/ui/src/settings/settings.css index 9911fb617..7b22a57cd 100644 --- a/ui/src/settings/settings.css +++ b/ui/src/settings/settings.css @@ -58,3 +58,96 @@ color: var(--fg); text-align: right; } + +/* Inline edit affordance: value + Edit on the right, input + Save / + Cancel while editing, and the server's reason for locked rows. */ +.cfg-value-cell { + display: flex; + align-items: center; + justify-content: flex-end; + gap: var(--sp-2); + min-width: 0; +} + +.cfg-edit { + font: inherit; + font-size: var(--text-xs); + color: var(--fg-muted); + background: var(--surface-hover); + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + padding: 2px var(--sp-2); + cursor: pointer; + flex: none; +} + +.cfg-edit:hover { + color: var(--fg); + border-color: var(--accent); +} + +.cfg-editing { + flex-wrap: wrap; +} + +.cfg-input { + font: inherit; + font-size: var(--text-xs); + color: var(--fg); + background: var(--surface); + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + padding: var(--sp-1) var(--sp-2); + min-width: 0; + flex: 1 1 10rem; +} + +.cfg-input:focus { + outline: 2px solid var(--accent); + outline-offset: -1px; +} + +.cfg-save, +.cfg-cancel { + font: inherit; + font-size: var(--text-xs); + border-radius: var(--radius-sm); + padding: var(--sp-1) var(--sp-2); + cursor: pointer; + flex: none; +} + +.cfg-save { + background: var(--accent); + border: 1px solid var(--accent); + color: var(--accent-fg); + font-weight: 500; +} + +.cfg-save:disabled { + opacity: 0.6; + cursor: default; +} + +.cfg-cancel { + background: transparent; + border: 1px solid var(--border-strong); + color: var(--fg-muted); +} + +.cfg-cancel:hover { + color: var(--fg); +} + +.cfg-locked { + font-size: var(--text-xs); + color: var(--fg-subtle); + font-style: italic; +} + +.cfg-error { + font-size: var(--text-xs); + color: var(--danger); + flex-basis: 100%; + text-align: right; +} diff --git a/ui/src/settings/settings.js b/ui/src/settings/settings.js index 902221d05..94021c0c3 100644 --- a/ui/src/settings/settings.js +++ b/ui/src/settings/settings.js @@ -3,11 +3,18 @@ import { api } from "../base/api.js"; import { el, empty, mount, pill } from "../base/dom.js"; /** - * A read-only view of the config archied is actually running with, grouped - * by domain and explained in plain language. Backed by GET /api/config, + * A view of the config archied is actually running with, grouped by + * domain and explained in plain language. Backed by GET /api/config, * which is built from an explicit, hand-picked allowlist on the Go side - * (internal/webui/api_config.go handleConfig) -- secrets never reach this - * page, so nothing here needs to be hidden or redacted client-side. + * (internal/webui/api_config.go handleConfig) -- secrets never reach + * this page, so nothing here needs to be hidden or redacted client-side. + * + * Scalar rows that are not denylisted are editable inline: Edit swaps + * the value for an input, Save PATCHes the dotted key to /api/config, + * which validates the materialised config before persisting to the + * runtime overlay and republishing. Structured values (repositories, + * models, providers -- arrays and maps) render read-only; denylisted + * keys (db_path, work_dir) render disabled with the server's reason. */ export function settingsPage() { const root = el("div"); @@ -35,13 +42,13 @@ export function settingsPage() { async function load() { try { const cfg = await api.config(); - renderBody(cfg); + renderBody(cfg, load); } catch (err) { mount(body, el("div.card", empty("Cannot reach archied", String(err.message || err)))); } } - function renderBody(cfg) { + function renderBody(cfg, reload) { if (!cfg || Object.keys(cfg).length === 0) { mount( body, @@ -56,16 +63,17 @@ export function settingsPage() { return; } + const ctx = { locked: cfg.locked || {}, onSaved: reload }; mount( body, - identityCard(cfg.identity), + identityCard(cfg.identity, ctx), repositoriesCard(cfg.repositories), modelsAndProvidersCard(cfg.models, cfg.providers), - budgetsCard(cfg.budgets), - agentCard(cfg.agent), - storageCard(cfg.storage, cfg.containers), - webCard(cfg.web), - provenanceCard(cfg.provenance), + budgetsCard(cfg.budgets, ctx), + agentCard(cfg.agent, ctx), + storageCard(cfg.storage, cfg.containers, ctx), + webCard(cfg.web, ctx), + provenanceCard(cfg.provenance), ); } @@ -89,23 +97,107 @@ function section(title, sub, ...children) { ); } -function row(label, value) { - return el("div.cfg-row", el("span.cfg-label", label), el("span.cfg-value.mono", value ?? "—")); +// row renders one label/value pair. opts.key makes it editable via a +// PATCH to /api/config; opts.locked[key] disables it with the server's +// reason; no key means a plain read-only row (structured values and +// provenance). +function row(label, value, opts) { + const labelEl = el("span.cfg-label", label); + if (!opts?.key) { + return el("div.cfg-row", labelEl, el("span.cfg-value.mono", value ?? "—")); + } + if (opts.locked?.[opts.key]) { + return el( + "div.cfg-row", + labelEl, + el( + "div.cfg-value-cell", + el("span.cfg-value.mono", value ?? "—"), + el("span.cfg-locked", opts.locked[opts.key]), + ), + ); + } + const display = el("span.cfg-value.mono", value ?? "—"); + const editBtn = el("button.cfg-edit", { title: `Edit ${label}` }, "Edit"); + const cell = el("div.cfg-value-cell", display, editBtn); + const rowEl = el("div.cfg-row", labelEl, cell); + editBtn.addEventListener("click", () => startEdit(rowEl, cell, label, opts)); + return rowEl; } -function identityCard(identity) { +function startEdit(rowEl, cell, label, opts) { + const { key, type, raw, onSaved } = opts; + const input = type === "bool" + ? el( + "select.cfg-input", + el("option", { value: "true", selected: raw === true }, "true"), + el("option", { value: "false", selected: raw === false }, "false"), + ) + : el("input.cfg-input", { type: "text", value: String(raw ?? "") }); + const save = el("button.cfg-save", { type: "button" }, "Save"); + const cancel = el("button.cfg-cancel", { type: "button" }, "Cancel"); + const error = el("span.cfg-error"); + const editing = el("div.cfg-value-cell.cfg-editing", input, save, cancel, error); + rowEl.replaceChild(editing, cell); + input.focus(); + + const done = () => rowEl.replaceChild(cell, editing); + cancel.addEventListener("click", done); + input.addEventListener("keydown", (e) => { + if (e.key === "Enter") save.click(); + if (e.key === "Escape") done(); + }); + + save.addEventListener("click", async () => { + const parsed = parseEdit(type, input.value); + if (parsed.error) { + error.textContent = parsed.error; + return; + } + save.disabled = true; + try { + await api.configUpdate({ [key]: parsed.value }); + onSaved?.(); + } catch (err) { + // The server's reason (validation failure, denylisted key) is the + // part the operator can act on; show it instead of the status. + error.textContent = String(err.message || err); + save.disabled = false; + } + }); +} + +// parseEdit converts the input text to the JSON type the config field +// expects. Durations and strings pass through (the server validates +// duration syntax); ints are parsed client-side so a typo fails before +// a round trip. +function parseEdit(type, text) { + switch (type) { + case "int": { + const n = parseInt(text, 10); + if (Number.isNaN(n)) return { error: "Enter a whole number" }; + return { value: n }; + } + case "bool": + return { value: text === "true" }; + default: + return { value: text }; + } +} + +function identityCard(identity, ctx) { if (!identity) return section("Identity", "Who Archie is on the forge.", empty("Not available")); return section( "Identity", "Who Archie is on the forge, and how it addresses commits and comments.", el( "div.cfg-rows", - row("Bot account", identity.bot_user), - row("Commit author email", identity.bot_email), - row("Pickup label", identity.label), - row("Forge type", identity.forge_type), - row("Forge host", identity.forge_host), - row("Max diff size (lines)", identity.diff_cap_lines), + row("Bot account", identity.bot_user, { key: "bot_user", type: "string", raw: identity.bot_user, ...ctx }), + row("Commit author email", identity.bot_email, { key: "bot_email", type: "string", raw: identity.bot_email, ...ctx }), + row("Pickup label", identity.label, { key: "label", type: "string", raw: identity.label, ...ctx }), + row("Forge type", identity.forge_type, { key: "forge.type", type: "string", raw: identity.forge_type, ...ctx }), + row("Forge host", identity.forge_host, { key: "forge.host", type: "string", raw: identity.forge_host, ...ctx }), + row("Max diff size (lines)", identity.diff_cap_lines || "Unlimited", { key: "diff_cap_lines", type: "int", raw: identity.diff_cap_lines, ...ctx }), ), ); } @@ -198,30 +290,30 @@ function roleLabel(role) { return role.charAt(0).toUpperCase() + role.slice(1).replace(/_/g, " "); } -function budgetsCard(budgets) { +function budgetsCard(budgets, ctx) { if (!budgets) return section("Budgets", "Limits on every agent stage.", empty("Not available")); return section( "Budgets", "The limits every autonomous stage runs under, so a stuck task cannot run forever.", el( "div.cfg-rows", - row("Max steps", budgets.max_steps || "Unlimited"), - row("Max tokens", budgets.max_tokens || "Unlimited"), - row("Wall clock", budgets.wall_clock), - row("Max gate failures before parking", budgets.gate_max_failures || "Unlimited"), + row("Max steps", budgets.max_steps || "Unlimited", { key: "budgets.max_steps", type: "int", raw: budgets.max_steps, ...ctx }), + row("Max tokens", budgets.max_tokens || "Unlimited", { key: "budgets.max_tokens", type: "int", raw: budgets.max_tokens, ...ctx }), + row("Wall clock", budgets.wall_clock, { key: "budgets.wall_clock", type: "string", raw: budgets.wall_clock, ...ctx }), + row("Max gate failures before parking", budgets.gate_max_failures || "Unlimited", { key: "budgets.gate_max_failures", type: "int", raw: budgets.gate_max_failures, ...ctx }), ), ); } -function agentCard(agent) { +function agentCard(agent, ctx) { if (!agent) return section("Agent execution", "How Archie runs autonomous stages.", empty("Not available")); return section( "Agent execution", "How archied actually runs a stage of work.", el( "div.cfg-rows", - row("Execution mode", agentModeLabel(agent.mode)), - row("Worker command", agent.command), + row("Execution mode", agentModeLabel(agent.mode), { key: "agent.mode", type: "string", raw: agent.mode, ...ctx }), + row("Worker command", agent.command, { key: "agent.command", type: "string", raw: agent.command, ...ctx }), row("Extra environment variables passed through", agent.env?.length ? agent.env.join(", ") : "None"), ), ); @@ -240,18 +332,18 @@ function agentModeLabel(mode) { } } -function storageCard(storage, containers) { +function storageCard(storage, containers, ctx) { const children = []; if (storage) { children.push( el("h3.cfg-subhead", "Paths"), el( "div.cfg-rows", - row("Work directory", storage.work_dir), - row("State path prefix", storage.db_path), - row("Shared skills directory", storage.skills_dir || "None (uses the work directory)"), - row("Daemon plugin directory", storage.plugin_dir || "None"), - row("Secret engine plugin directory", storage.secret_engine_dir || "None (built-in engines only)"), + row("Work directory", storage.work_dir, { key: "work_dir", type: "string", ...ctx }), + row("State path prefix", storage.db_path, { key: "db_path", type: "string", ...ctx }), + row("Shared skills directory", storage.skills_dir || "None (uses the work directory)", { key: "skills_dir", type: "string", raw: storage.skills_dir, ...ctx }), + row("Daemon plugin directory", storage.plugin_dir || "None", { key: "plugin_dir", type: "string", raw: storage.plugin_dir, ...ctx }), + row("Secret engine plugin directory", storage.secret_engine_dir || "None (built-in engines only)", { key: "secret_engine_dir", type: "string", raw: storage.secret_engine_dir, ...ctx }), ), ); } @@ -260,13 +352,13 @@ function storageCard(storage, containers) { el("h3.cfg-subhead", "Sandboxed containers"), el( "div.cfg-rows", - row("Sandboxing enabled", containers.enabled ? "Yes" : "No"), - row("Agent image", containers.image || "Not set"), - row("Max concurrent tasks", containers.max_concurrency || "Unlimited"), - row("Container max lifetime", containers.max_uptime), - row("Persistent volume retention", containers.volume_ttl), - row("How images are refreshed", pullPolicyLabel(containers.pull_policy)), - row("Docker network", containers.network || "Auto-detected"), + row("Sandboxing enabled", containers.enabled ? "Yes" : "No", { key: "containers.enabled", type: "bool", raw: containers.enabled, ...ctx }), + row("Agent image", containers.image || "Not set", { key: "containers.image", type: "string", raw: containers.image, ...ctx }), + row("Max concurrent tasks", containers.max_concurrency || "Unlimited", { key: "containers.max_concurrency", type: "int", raw: containers.max_concurrency, ...ctx }), + row("Container max lifetime", containers.max_uptime, { key: "containers.max_uptime", type: "string", raw: containers.max_uptime, ...ctx }), + row("Persistent volume retention", containers.volume_ttl, { key: "containers.volume_ttl", type: "string", raw: containers.volume_ttl, ...ctx }), + row("How images are refreshed", pullPolicyLabel(containers.pull_policy), { key: "containers.pull_policy", type: "string", raw: containers.pull_policy, ...ctx }), + row("Docker network", containers.network || "Auto-detected", { key: "containers.network", type: "string", raw: containers.network, ...ctx }), ), ); } @@ -279,11 +371,11 @@ function pullPolicyLabel(policy) { return "Only pull when the image is missing locally"; } -function webCard(web) { +function webCard(web, ctx) { if (!web) return section("Dashboard", "This dashboard's own listen address.", empty("Not available")); return section( "Dashboard", "This dashboard's own listen address.", - el("div.cfg-rows", row("Listen address", web.listen === "off" ? "Disabled" : web.listen)), + el("div.cfg-rows", row("Listen address", web.listen === "off" ? "Disabled" : web.listen, { key: "web.listen", type: "string", raw: web.listen === "off" ? "" : web.listen, ...ctx })), ); } From 171e1b26868fb72c036235fb65d8bca99f1a977f Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 01:09:05 +1000 Subject: [PATCH 08/13] feat(config): surface overlay state, shadowed keys, and per-row reset Three gaps closed, all in the 'your change didn't take effect and nothing told you' family: 1. MaxRetries joins the reloadable allowlist, and the criterion is fixed on reloadableFields: a field is reloadable when EVERY consumer re-reads it. MaxRetries is the worked example -- its only consumer is the webui maxRetriesFor handler, which re-reads per request (api_tasks.go:380,383); nothing in the daemon reads it, so warning 'requires restart' was spurious. Chat.Telegram.TokenEnv is documented as the counter-example (webui reads it per request but a startup-built telegram bot consumes it, so it is not reloadable). Pinned by TestChangedNonReloadableFields alongside the comment. 2. Boot-time overlay degradation is now surfaced. config.ReloadStatus gains OverlayUnavailable; main.go records the reason when the overlay store cannot be opened or its values fail validation, and /api/config carries it (merged into LastReload). Cleared by a successful dashboard write or reset. The settings page renders a warning banner, so a daemon running on file config alone says so where the operator is looking, not only in logs. 3. Overlay-shadowed file edits are visible and recoverable. ConfigView.Overridden lists the dotted keys the runtime overlay currently sets, so the UI marks those rows (their file value is shadowed until reset). POST /api/config/reset exposes the store's Delete as a per-row reset: it deletes the row and republishes file + remaining overlay, which is also the answer to 'my file edit isn't taking effect'. The dashboard can now remove every override it can create. Verified: task check clean; -race clean on cmd/archied, webui, infrastructure/configuration; new handler tests cover the reset 200/400/503 paths and the overridden list. --- cmd/archied/main.go | 69 +++++++++++++++++++++++++++++- cmd/archied/reload.go | 21 +++++++++- cmd/archied/reload_test.go | 1 + internal/config/reload.go | 7 ++++ internal/webui/api_config.go | 44 +++++++++++++++++++ internal/webui/api_config_test.go | 70 +++++++++++++++++++++++++++++++ internal/webui/server.go | 13 ++++++ ui/dist/assets/index.css | 2 +- ui/dist/assets/index.js | 12 +++--- ui/src/base/api.js | 10 +++++ ui/src/settings/settings.css | 15 +++++++ ui/src/settings/settings.js | 46 ++++++++++++++++++-- 12 files changed, 295 insertions(+), 15 deletions(-) diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 26fedb1b7..bf72855e9 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -16,6 +16,7 @@ import ( "os" "os/signal" "path/filepath" + "sort" "strconv" "strings" "syscall" @@ -347,20 +348,26 @@ func run() int { // migrator, no contention with the task store). Skipped under // --no-config-overlay / ARCHIE_SKIP_CONFIG_OVERLAY=1, or when the // store cannot be opened or its values fail validation -- a broken - // overlay must not brick the daemon. + // overlay must not brick the daemon. bootOverlayErr carries the + // degrade reason into /api/config's reload status so it is visible + // where the operator is looking, not only in logs. var overlayStore *overlay.Store + var bootOverlayErr string if !skipOverlay { overlayStore, err = overlay.Open(ctx, configDBPath(doc.Config.DBPath)) if err != nil { + bootOverlayErr = err.Error() log.Error("config overlay unavailable; booting on file config alone", "path", configDBPath(doc.Config.DBPath), "err", err) } else { defer overlayStore.Close() if overrides, err := overlayStore.Snapshot(ctx); err != nil { + bootOverlayErr = err.Error() log.Error("config overlay unreadable; booting on file config alone", "err", err) } else if len(overrides) > 0 { next := *doc applied, err := loader.ApplyOverlay(&next, overrides) if err != nil { + bootOverlayErr = err.Error() log.Error("config overlay rejected by validation; booting on file config alone", "err", err) } else { doc = applied @@ -1065,7 +1072,14 @@ func run() int { if overlayStore != nil { reloadController.WithOverlay(func() (map[string]any, error) { return overlayStore.Snapshot(ctx) }) } - web.LastReload = reloadController.Status + // LastReload merges the reload controller's outcome with the boot-time + // overlay degrade, so /api/config carries both the last reload result + // and whether the runtime overlay is in effect at all. + web.LastReload = func() config.ReloadStatus { + st := reloadController.Status() + st.OverlayUnavailable = bootOverlayErr + return st + } // PATCH /api/config goes through the same publish path as reload: // apply to a copy of the published config, validate the materialised @@ -1100,10 +1114,61 @@ func run() int { configuration.Origin{Path: "config_overlay (runtime)", Role: configuration.RoleMain, Layer: configuration.LayerOverlay})} currentProvenance = prov publishConfig(next, prov) + bootOverlayErr = "" // a successful write proves the overlay works again log.Info("config updated from dashboard", "keys", len(updates)) return nil } + // ConfigOverrides lists the dotted keys currently overridden by the + // runtime overlay, so the dashboard can mark those rows and offer a + // reset. A disabled store reports no overrides. + web.ConfigOverrides = func(ctx context.Context) ([]string, error) { + if overlayStore == nil { + return nil, nil + } + rows, err := overlayStore.Snapshot(ctx) + if err != nil { + return nil, err + } + keys := make([]string, 0, len(rows)) + for k := range rows { + keys = append(keys, k) + } + sort.Strings(keys) + return keys, nil + } + + // ResetConfig deletes one overlay row and republishes file + remaining + // overlay, so a dashboard-created override can be removed without + // editing SQL -- and so an operator whose file edit is shadowed by an + // override can recover it with one click. + web.ResetConfig = func(ctx context.Context, key string) error { + if overlayStore == nil { + return fmt.Errorf("%w: config overlay is disabled", webui.ErrConfigUpdateUnavailable) + } + if err := overlayStore.Delete(ctx, key); err != nil { + return err + } + doc, err := loader.Resolve(*cfgPath, *overlayPath) + if err != nil { + return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + } + if overrides, err := overlayStore.Snapshot(ctx); err != nil { + return err + } else if len(overrides) > 0 { + next := *doc + if doc, err = loader.ApplyOverlay(&next, overrides); err != nil { + return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + } + } + applyModelCatalog(&doc.Config, catalog) + currentProvenance = doc.Provenance + publishConfig(doc.Config, doc.Provenance) + bootOverlayErr = "" + log.Info("config key reset to file value", "key", key) + return nil + } + reloadCh := make(chan os.Signal, 1) signal.Notify(reloadCh, syscall.SIGHUP) defer signal.Stop(reloadCh) diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go index 66468af0e..473dc075b 100644 --- a/cmd/archied/reload.go +++ b/cmd/archied/reload.go @@ -115,8 +115,19 @@ func reloadLoop(ctx context.Context, ch <-chan os.Signal, c *ReloadController, l } } -// reloadableFields are the Config fields the daemon re-reads per cycle -// or per dispatched task, so a reload takes effect without a restart. +// reloadableFields are the Config fields a reload takes effect on +// without a restart. The criterion: a field is reloadable when EVERY +// consumer re-reads it. That question read as "what does the daemon +// re-read" while the daemon owned the only Holder; it stopped being +// sufficient when webui began sharing that Holder, because webui +// handlers re-read on every request. MaxRetries is the worked example: +// its only consumer is api_tasks.go:380,383, reading per-request +// s.Cfg.Get(), and nothing in the daemon reads it -- so it reloads. +// Chat.Telegram.TokenEnv is the counter-example: webui reads it per +// request AND a telegram bot built at startup consumes it, so it is +// NOT reloadable, and treating "webui reads it" as sufficient would +// display a new token while the bot uses the old one. +// // This is deliberately an allowlist: a field added to Config later // defaults to requires-restart, which is the safe direction and forces // whoever adds it to decide deliberately. @@ -140,6 +151,12 @@ var reloadableFields = map[string]bool{ // pinned by hand in TestReloadableFieldsCoverForTaskSnapshot. "Label": true, "BotUser": true, + // Worked example of the every-consumer criterion above: the sole + // consumer is the webui maxRetriesFor handler (api_tasks.go:380,383), + // which re-reads per request; the daemon never reads MaxRetries. The + // per-task half of this list is pinned mechanically; this webui-only + // entry is pinned by TestChangedNonReloadableFields. + "MaxRetries": true, } // reloadableSubFields are sub-fields of structs that are otherwise diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go index 5dbe070ba..efcae7d77 100644 --- a/cmd/archied/reload_test.go +++ b/cmd/archied/reload_test.go @@ -207,6 +207,7 @@ func TestChangedNonReloadableFields(t *testing.T) { reloadableOnly.Label = "archie" reloadableOnly.BotUser = "new-bot" reloadableOnly.Forge = config.Forge{Host: "https://new-forge.example"} + reloadableOnly.MaxRetries = 5 if got := changedNonReloadableFields(base, reloadableOnly); len(got) != 0 { t.Fatalf("reloadable-only: got %v, want []", got) } diff --git a/internal/config/reload.go b/internal/config/reload.go index 6e2c770c3..7dbb86f5d 100644 --- a/internal/config/reload.go +++ b/internal/config/reload.go @@ -14,4 +14,11 @@ type ReloadStatus struct { // LastReloadAt is the RFC3339 UTC timestamp of the most recent // successful reload. Empty until the first reload. LastReloadAt string `json:"last_reload_at,omitempty"` + // OverlayUnavailable is the reason the runtime config overlay is not + // in effect, so the running config is file-only. Set at boot when + // the overlay store cannot be opened or its values fail validation, + // and cleared by a successful dashboard write or reset. The + // dashboard shows it so a boot-time degrade is visible where the + // operator is looking, not only in logs. + OverlayUnavailable string `json:"overlay_unavailable,omitempty"` } diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index b0b0c3f31..5b7f1107e 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -221,6 +221,10 @@ type ConfigView struct { // dashboard to the reason. The UI renders these rows disabled rather // than silently omitting the edit affordance. Locked map[string]string `json:"locked,omitempty"` + // Overridden lists the dotted config keys currently set by the + // runtime overlay, so the UI can mark those rows (their file value + // is shadowed until reset) and offer a per-row reset. + Overridden []string `json:"overridden,omitempty"` } // IdentityView is who Archie is on the forge -- never the token that @@ -372,6 +376,13 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { Provenance: provenance, Locked: lockedConfigKeys(), } + if s.ConfigOverrides != nil { + if overridden, err := s.ConfigOverrides(r.Context()); err == nil { + view.Overridden = overridden + } + // A failed read omits the list rather than failing the whole + // view; the reload status carries the overlay degrade reason. + } if s.LastReload != nil { rs := s.LastReload() view.Reload = &rs @@ -380,6 +391,39 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { writeJSON(w, view) } +// handleConfigReset deletes one runtime-overlay row via ResetConfig, +// restoring the file value for that key. The dashboard offers this on +// overridden rows so it can remove an override it created. +func (s *Server) handleConfigReset(w http.ResponseWriter, r *http.Request) { + if s.ResetConfig == nil { + http.Error(w, ErrConfigUpdateUnavailable.Error(), http.StatusServiceUnavailable) + return + } + var body struct { + Key string `json:"key"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest) + return + } + if body.Key == "" { + http.Error(w, "key required", http.StatusBadRequest) + return + } + if err := s.ResetConfig(r.Context(), body.Key); err != nil { + switch { + case errors.Is(err, ErrConfigUpdateUnavailable): + http.Error(w, err.Error(), http.StatusServiceUnavailable) + case errors.Is(err, ErrConfigUpdateInvalid): + http.Error(w, err.Error(), http.StatusBadRequest) + default: + http.Error(w, "config reset failed: "+err.Error(), http.StatusInternalServerError) + } + return + } + writeJSON(w, map[string]any{"ok": true}) +} + // lockedConfigKeys returns the dotted config keys the overlay refuses // to set, with the reason shown in the UI. These are the daemon's own // bootstrap inputs; changing them from the dashboard could break the diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index c0f1e1dd9..586fe73a8 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -320,6 +320,76 @@ func TestHandleConfigUpdateWithoutSeamMapsTo503(t *testing.T) { } } +// TestHandleConfigIncludesOverridden proves the overridden dotted keys +// reach the view so the UI can mark rows shadowed by the runtime overlay. +func TestHandleConfigIncludesOverridden(t *testing.T) { + srv := newTestServer(t) + srv.Cfg = configWithFakeSecrets() + srv.ConfigOverrides = func(context.Context) ([]string, error) { + return []string{"budgets.max_steps", "label"}, nil + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + var got ConfigView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got.Overridden) != 2 || got.Overridden[0] != "budgets.max_steps" || got.Overridden[1] != "label" { + t.Errorf("Overridden = %v, want [budgets.max_steps label]", got.Overridden) + } +} + +func TestHandleConfigResetCallsSeamAndAnswersOk(t *testing.T) { + srv := newTestServer(t) + var got string + srv.ResetConfig = func(_ context.Context, key string) error { + got = key + return nil + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/config/reset", + strings.NewReader(`{"key": "budgets.max_steps"}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", w.Code, w.Body) + } + if got != "budgets.max_steps" { + t.Errorf("ResetConfig called with %q, want budgets.max_steps", got) + } +} + +func TestHandleConfigResetWithoutSeamMapsTo503(t *testing.T) { + srv := newTestServer(t) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/config/reset", + strings.NewReader(`{"key": "label"}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503, body = %s", w.Code, w.Body) + } +} + +func TestHandleConfigResetRejectsEmptyKey(t *testing.T) { + srv := newTestServer(t) + srv.ResetConfig = func(context.Context, string) error { return nil } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/config/reset", + strings.NewReader(`{"key": ""}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400, body = %s", w.Code, w.Body) + } +} + func TestHandleChannelsReportsConfiguredState(t *testing.T) { srv := newTestServer(t) srv.Cfg = configWithFakeSecrets() diff --git a/internal/webui/server.go b/internal/webui/server.go index 2fa1d4a9c..2eeff0a68 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -78,6 +78,18 @@ type Server struct { // Cfg field doc. UpdateConfig func(context.Context, map[string]any) error + // ConfigOverrides lists the dotted config keys currently overridden + // by the runtime overlay, so the dashboard can mark those rows and + // offer a reset. Optional: when nil, the /api/config response omits + // the overridden list. + ConfigOverrides func(context.Context) ([]string, error) + + // ResetConfig deletes one runtime-overlay row and republishes file + + // remaining overlay. Optional: when nil, POST /api/config/reset + // answers 503. Like UpdateConfig, it never touches the Cfg Holder + // directly. + ResetConfig func(context.Context, string) error + // Channels reports actual adapter lifecycle, independently of configuration // presence. Nil preserves the configuration-only fallback for tests and // minimal embedding. @@ -177,6 +189,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /api/channels/{id}/reload", s.handleChannelReload) mux.HandleFunc("GET /api/config", s.handleConfig) mux.HandleFunc("PATCH /api/config", s.handleConfigUpdate) + mux.HandleFunc("POST /api/config/reset", s.handleConfigReset) mux.HandleFunc("GET /api/logs", s.handleLogs) mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs) mux.HandleFunc("GET /api/logs/stream", s.handleLogStream) diff --git a/ui/dist/assets/index.css b/ui/dist/assets/index.css index 5c5d84baf..370276088 100644 --- a/ui/dist/assets/index.css +++ b/ui/dist/assets/index.css @@ -1 +1 @@ -:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}@media (width<=1220px) and (width>=901px){.topbar{flex-wrap:wrap}.nav{border-radius:var(--radius-lg);flex-wrap:wrap;order:3;justify-content:center;width:100%;margin:0}}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;flex-wrap:nowrap;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{background:0 0;border:0;padding:0;overflow:hidden}.topbar-search-icon{display:none}.mobile-search-toggle{display:grid}.topbar-search input{opacity:0;pointer-events:none;width:0;transition:width var(--transition), opacity var(--transition);padding:0}.topbar-search.is-open,.topbar-search:focus-within{padding-right:var(--sp-2);border:1px solid var(--hairline);background:var(--surface-glass-strong)}.topbar-search.is-open input,.topbar-search:focus-within input{opacity:1;pointer-events:auto;width:min(9rem,34vw)}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-complete-actions{align-items:center;gap:var(--sp-2);display:flex}.setup-dismiss{width:28px;height:28px;font-size:var(--text-lg);line-height:1}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row{cursor:pointer}.task-expand{width:1.5rem;height:1.5rem;margin-right:var(--sp-2);color:var(--fg-muted);border:1px solid var(--border);font:inherit;cursor:pointer;background:0 0;border-radius:50%;padding:0;line-height:1}.task-expand:hover,.task-expand:focus-visible{color:var(--fg);border-color:var(--accent)}.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-actions{gap:var(--sp-1);white-space:nowrap;flex-wrap:wrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:180px;color:var(--danger);font-size:var(--text-xs);white-space:normal}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-detail-actions{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);padding-bottom:var(--sp-3);border-bottom:1px solid var(--hairline);display:flex}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}.table-scroll:has(.task-row){overflow:visible}.table:has(.task-row){display:block}.table:has(.task-row) tbody{display:block}.table-scroll>.table:has(.task-row){width:100%;min-width:0}.table:has(.task-row) thead{display:none}.task-row{gap:var(--sp-2) var(--sp-4);margin-bottom:var(--sp-3);padding:var(--sp-3);border:1px solid var(--hairline);border-radius:var(--radius-lg);background:var(--surface-glass);grid-template-columns:1fr 1fr;display:grid}.task-row td{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-1) 0;text-align:right;border:0;display:flex}.task-row td:before{content:attr(data-label);color:var(--fg-subtle);font-size:var(--text-xs);text-align:left;font-weight:500}.task-row td:nth-child(3),.task-row td:last-child{grid-column:1/-1}.task-row td:last-child{align-items:flex-start}.task-timeline-row,.task-timeline-row td{width:100%;display:block}.task-timeline-row td{margin:calc(var(--sp-2) * -1) 0 var(--sp-4);border-radius:0 0 var(--radius-lg) var(--radius-lg)}.task-detail-actions{flex-direction:column;align-items:flex-start}}@media (width<=480px){.task-row{grid-template-columns:1fr}.task-row td:nth-child(3),.task-row td:last-child{grid-column:auto}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-4) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.cfg-rows{gap:var(--sp-2);flex-direction:column;display:flex}.cfg-row{justify-content:space-between;align-items:baseline;gap:var(--sp-4);padding:var(--sp-2) 0;border-bottom:1px solid var(--border);display:flex}.cfg-section .cfg-rows{gap:0}.cfg-section .cfg-row{padding:var(--sp-1) 0}.cfg-row:last-child{border-bottom:0}.cfg-label{font-size:var(--text-sm);color:var(--fg-muted)}.cfg-value{font-size:var(--text-sm);color:var(--fg);text-align:right}.cfg-value-cell{justify-content:flex-end;align-items:center;gap:var(--sp-2);min-width:0;display:flex}.cfg-edit{font:inherit;font-size:var(--text-xs);color:var(--fg-muted);background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:2px var(--sp-2);cursor:pointer;flex:none}.cfg-edit:hover{color:var(--fg);border-color:var(--accent)}.cfg-editing{flex-wrap:wrap}.cfg-input{font:inherit;font-size:var(--text-xs);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);flex:10rem;min-width:0}.cfg-input:focus{outline:2px solid var(--accent);outline-offset:-1px}.cfg-save,.cfg-cancel{font:inherit;font-size:var(--text-xs);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);cursor:pointer;flex:none}.cfg-save{background:var(--accent);border:1px solid var(--accent);color:var(--accent-fg);font-weight:500}.cfg-save:disabled{opacity:.6;cursor:default}.cfg-cancel{border:1px solid var(--border-strong);color:var(--fg-muted);background:0 0}.cfg-cancel:hover{color:var(--fg)}.cfg-locked{font-size:var(--text-xs);color:var(--fg-subtle);font-style:italic}.cfg-error{font-size:var(--text-xs);color:var(--danger);text-align:right;flex-basis:100%}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.chat-page{flex-direction:column;height:calc(100vh - 5rem);display:flex;overflow:hidden}.chat-page-content{flex-direction:column;flex:auto;min-height:0;display:flex;overflow:hidden}.chat-topbar{flex:none;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;display:flex}.chat-kicker,.chat-workspace-label{color:var(--fg-muted);letter-spacing:.12em;font-size:.68rem;font-weight:700}.chat-topbar-actions{align-items:center;gap:.55rem;display:flex}.chat-topbar-actions .chat-select{min-width:0;max-width:14rem}.chat-update-panel{border:1px solid var(--border);color:var(--fg-muted);border-radius:.75rem;flex:none;justify-content:space-between;align-items:center;gap:1rem;margin:0 0 .75rem;padding:.7rem .9rem;font-size:.8rem;display:flex}.chat-update-panel>div:first-child{gap:.2rem;display:grid}.chat-update-panel strong{color:var(--fg)}.chat-update-actions{flex-shrink:0;gap:.45rem;display:flex}.chat-dangerous-panel{border:1px solid color-mix(in srgb, var(--danger) 45%, var(--border));border-radius:.75rem;flex:none;margin:0 0 .75rem;padding:.8rem .9rem}.chat-dangerous-head,.chat-dangerous-controls,.chat-dangerous-pending{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-dangerous-head{margin-bottom:.7rem}.chat-dangerous-controls{flex-wrap:wrap;align-items:stretch}.chat-dangerous-controls>div{flex:18rem;gap:.45rem;display:flex}.chat-dangerous-input{background:var(--surface-hover);min-width:0;color:var(--fg);border:1px solid var(--border-strong);font:inherit;border-radius:.5rem;flex:1;padding:.5rem .65rem}.chat-dangerous-pending-list{gap:.45rem;margin-top:.75rem;display:grid}.chat-dangerous-pending{border-top:1px solid var(--border);color:var(--fg-muted);padding-top:.55rem;font-size:.8rem}.chat-layout{flex:auto;grid-template-columns:242px minmax(0,1fr);gap:.75rem;min-height:0;display:grid;overflow:hidden}.chat-sidebar,.chat-workspace{background:var(--surface);border:1px solid var(--border);border-radius:1rem}.chat-sidebar{padding:.8rem;overflow-y:auto}.chat-sidebar-head,.chat-toolbar,.chat-compose-actions{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-session-list{gap:.35rem;margin-top:1rem;display:grid}.chat-session{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.65rem;gap:.25rem;padding:.7rem;display:grid}.chat-session:hover,.chat-session.active{background:var(--surface-hover);color:var(--fg);border-color:var(--border-strong)}.chat-session span{font-size:.72rem}.chat-workspace{grid-template-rows:auto minmax(0,1fr) auto;min-width:0;display:grid;overflow:hidden}.chat-workspace-head{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;padding:.85rem 1.1rem;display:flex}.chat-session-tools{color:var(--fg-muted);margin-left:.6rem;font-size:.78rem;position:relative}.chat-session-tools summary{cursor:pointer}.chat-session-tool-list{z-index:2;background:var(--surface);border:1px solid var(--border-strong);border-radius:.65rem;flex-wrap:wrap;gap:.35rem;width:min(22rem,72vw);padding:.55rem;display:flex;position:absolute;top:calc(100% + .45rem);right:0;box-shadow:0 .7rem 2rem #0000004d}.chat-select{background:var(--surface-hover);color:var(--fg);border:1px solid var(--border-strong);border-radius:.5rem;padding:.5rem .65rem}.chat-transcript{align-content:start;gap:1rem;padding:1.25rem;display:grid;overflow:auto}.chat-empty-state{text-align:center;place-self:center;width:min(100%,40rem);padding:3rem 1rem}.chat-empty-mark{border:1px solid var(--border-strong);width:2.6rem;height:2.6rem;color:var(--accent);border-radius:.8rem;place-items:center;margin:0 auto 1rem;font-weight:700;display:grid}.chat-empty-state h2{letter-spacing:-.04em;margin:0;font-size:clamp(1.5rem,3vw,2.25rem)}.chat-empty-state p{color:var(--fg-muted);margin:.6rem 0 1.4rem}.chat-prompt-grid{flex-wrap:wrap;justify-content:center;gap:.5rem;display:flex}.chat-prompt{border:1px solid var(--border);background:var(--surface-hover);color:var(--fg-muted);cursor:pointer;border-radius:999px;padding:.55rem .75rem}.chat-prompt:hover{color:var(--fg);border-color:var(--border-strong)}.chat-bubble-row{display:flex}.chat-bubble-row.user{justify-content:flex-end}.chat-bubble{background:var(--surface-hover);border-radius:.85rem;max-width:min(78ch,86%);padding:.8rem 1rem;line-height:1.5}.chat-bubble-row.user .chat-bubble{background:color-mix(in srgb, var(--accent) 18%, var(--surface))}.chat-bubble-meta{color:var(--fg-muted);margin-bottom:.3rem;font-size:.7rem}.chat-bubble-text{white-space:pre-wrap;overflow-wrap:anywhere}.chat-bubble-text p{margin:0 0 .7rem}.chat-bubble-text p:last-child{margin-bottom:0}.chat-bubble-text h1,.chat-bubble-text h2,.chat-bubble-text h3{letter-spacing:-.02em;margin:.2rem 0 .6rem;line-height:1.2}.chat-bubble-text h1{font-size:1.25rem}.chat-bubble-text h2{font-size:1.1rem}.chat-bubble-text h3{font-size:1rem}.chat-bubble-text ul,.chat-bubble-text ol{margin:.25rem 0 .75rem;padding-left:1.35rem}.chat-bubble-text blockquote{border-left:3px solid var(--accent);color:var(--fg-muted);margin:.5rem 0;padding:.35rem .75rem}.chat-bubble-text code{background:color-mix(in srgb, var(--fg) 10%, transparent);border-radius:.3rem;padding:.1rem .3rem;font-size:.9em}.chat-bubble-text pre{border:1px solid var(--border);background:color-mix(in srgb, var(--surface) 75%, #000);border-radius:.5rem;margin:.6rem 0;padding:.75rem;overflow:auto}.chat-bubble-text pre code{background:0 0;padding:0}.chat-bubble-text a{color:var(--accent)}.chat-bubble-text table{border-collapse:collapse;width:100%;margin:.7rem 0;font-size:.92em}.chat-bubble-text th,.chat-bubble-text td{text-align:left;border:1px solid var(--border);padding:.45rem .6rem}.chat-bubble-text th{color:var(--fg);background:color-mix(in srgb, var(--surface) 70%, transparent);font-weight:700}.chat-compose{border-top:1px solid var(--border);padding:.85rem 1rem 1rem}.chat-composer-shell{background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:.9rem;padding:.7rem .8rem .55rem;position:relative}.chat-composer{resize:vertical;box-sizing:border-box;width:100%;min-height:3.3rem;color:var(--fg);font:inherit;background:0 0;border:0;padding:.25rem 0}.chat-composer:focus{outline:0}.chat-command-menu{z-index:3;background:var(--surface);border:1px solid var(--border-strong);border-radius:.7rem;gap:.15rem;max-height:18rem;padding:.35rem;display:grid;position:absolute;bottom:calc(100% - .25rem);left:.8rem;right:.8rem;overflow:auto;box-shadow:0 .7rem 2rem #0000004d}.chat-command-menu[hidden]{display:none}.chat-command-option{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.45rem;grid-template-columns:minmax(8rem,14rem) 1fr;align-items:center;gap:.65rem;padding:.5rem .6rem;display:grid}.chat-command-option:hover,.chat-command-option[aria-selected=true]{color:var(--fg);background:var(--surface-hover);border-color:var(--border)}.chat-command-option code{color:var(--fg)}.chat-compose-actions{margin-top:.55rem}.chat-hint,.chat-empty{color:var(--fg-muted);font-size:.78rem}.chat-command-help{color:var(--fg-muted);margin-right:auto;font-size:.78rem}.chat-command-help summary{cursor:pointer}.chat-command-list{min-width:min(34rem,70vw);max-width:40rem;padding-top:.4rem;line-height:1.45}.chat-command-item{grid-template-columns:minmax(10rem,16rem) 1fr;gap:.7rem;padding:.3rem 0;display:grid}.chat-command-item code{color:var(--fg)}@media (width<=760px){.chat-topbar,.chat-topbar-actions{flex-direction:column;align-items:flex-start}.chat-layout{grid-template-columns:1fr}.chat-sidebar{max-height:14rem;overflow:auto}}@media (width<=520px){.chat-update-panel{flex-direction:column;align-items:flex-start}} +:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}@media (width<=1220px) and (width>=901px){.topbar{flex-wrap:wrap}.nav{border-radius:var(--radius-lg);flex-wrap:wrap;order:3;justify-content:center;width:100%;margin:0}}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;flex-wrap:nowrap;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{background:0 0;border:0;padding:0;overflow:hidden}.topbar-search-icon{display:none}.mobile-search-toggle{display:grid}.topbar-search input{opacity:0;pointer-events:none;width:0;transition:width var(--transition), opacity var(--transition);padding:0}.topbar-search.is-open,.topbar-search:focus-within{padding-right:var(--sp-2);border:1px solid var(--hairline);background:var(--surface-glass-strong)}.topbar-search.is-open input,.topbar-search:focus-within input{opacity:1;pointer-events:auto;width:min(9rem,34vw)}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-complete-actions{align-items:center;gap:var(--sp-2);display:flex}.setup-dismiss{width:28px;height:28px;font-size:var(--text-lg);line-height:1}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row{cursor:pointer}.task-expand{width:1.5rem;height:1.5rem;margin-right:var(--sp-2);color:var(--fg-muted);border:1px solid var(--border);font:inherit;cursor:pointer;background:0 0;border-radius:50%;padding:0;line-height:1}.task-expand:hover,.task-expand:focus-visible{color:var(--fg);border-color:var(--accent)}.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-actions{gap:var(--sp-1);white-space:nowrap;flex-wrap:wrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:180px;color:var(--danger);font-size:var(--text-xs);white-space:normal}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-detail-actions{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);padding-bottom:var(--sp-3);border-bottom:1px solid var(--hairline);display:flex}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}.table-scroll:has(.task-row){overflow:visible}.table:has(.task-row){display:block}.table:has(.task-row) tbody{display:block}.table-scroll>.table:has(.task-row){width:100%;min-width:0}.table:has(.task-row) thead{display:none}.task-row{gap:var(--sp-2) var(--sp-4);margin-bottom:var(--sp-3);padding:var(--sp-3);border:1px solid var(--hairline);border-radius:var(--radius-lg);background:var(--surface-glass);grid-template-columns:1fr 1fr;display:grid}.task-row td{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-1) 0;text-align:right;border:0;display:flex}.task-row td:before{content:attr(data-label);color:var(--fg-subtle);font-size:var(--text-xs);text-align:left;font-weight:500}.task-row td:nth-child(3),.task-row td:last-child{grid-column:1/-1}.task-row td:last-child{align-items:flex-start}.task-timeline-row,.task-timeline-row td{width:100%;display:block}.task-timeline-row td{margin:calc(var(--sp-2) * -1) 0 var(--sp-4);border-radius:0 0 var(--radius-lg) var(--radius-lg)}.task-detail-actions{flex-direction:column;align-items:flex-start}}@media (width<=480px){.task-row{grid-template-columns:1fr}.task-row td:nth-child(3),.task-row td:last-child{grid-column:auto}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-4) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.cfg-rows{gap:var(--sp-2);flex-direction:column;display:flex}.cfg-row{justify-content:space-between;align-items:baseline;gap:var(--sp-4);padding:var(--sp-2) 0;border-bottom:1px solid var(--border);display:flex}.cfg-section .cfg-rows{gap:0}.cfg-section .cfg-row{padding:var(--sp-1) 0}.cfg-row:last-child{border-bottom:0}.cfg-label{font-size:var(--text-sm);color:var(--fg-muted)}.cfg-value{font-size:var(--text-sm);color:var(--fg);text-align:right}.cfg-value-cell{justify-content:flex-end;align-items:center;gap:var(--sp-2);min-width:0;display:flex}.cfg-edit{font:inherit;font-size:var(--text-xs);color:var(--fg-muted);background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:2px var(--sp-2);cursor:pointer;flex:none}.cfg-edit:hover{color:var(--fg);border-color:var(--accent)}.cfg-editing{flex-wrap:wrap}.cfg-input{font:inherit;font-size:var(--text-xs);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);flex:10rem;min-width:0}.cfg-input:focus{outline:2px solid var(--accent);outline-offset:-1px}.cfg-save,.cfg-cancel{font:inherit;font-size:var(--text-xs);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);cursor:pointer;flex:none}.cfg-save{background:var(--accent);border:1px solid var(--accent);color:var(--accent-fg);font-weight:500}.cfg-save:disabled{opacity:.6;cursor:default}.cfg-cancel{border:1px solid var(--border-strong);color:var(--fg-muted);background:0 0}.cfg-cancel:hover{color:var(--fg)}.cfg-locked{font-size:var(--text-xs);color:var(--fg-subtle);font-style:italic}.cfg-overridden{font-size:var(--text-xs);color:var(--warn)}.cfg-notice{border-left:3px solid var(--warn)}.cfg-notice p{font-size:var(--text-sm);color:var(--warn);margin:0}.cfg-error{font-size:var(--text-xs);color:var(--danger);text-align:right;flex-basis:100%}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.chat-page{flex-direction:column;height:calc(100vh - 5rem);display:flex;overflow:hidden}.chat-page-content{flex-direction:column;flex:auto;min-height:0;display:flex;overflow:hidden}.chat-topbar{flex:none;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;display:flex}.chat-kicker,.chat-workspace-label{color:var(--fg-muted);letter-spacing:.12em;font-size:.68rem;font-weight:700}.chat-topbar-actions{align-items:center;gap:.55rem;display:flex}.chat-topbar-actions .chat-select{min-width:0;max-width:14rem}.chat-update-panel{border:1px solid var(--border);color:var(--fg-muted);border-radius:.75rem;flex:none;justify-content:space-between;align-items:center;gap:1rem;margin:0 0 .75rem;padding:.7rem .9rem;font-size:.8rem;display:flex}.chat-update-panel>div:first-child{gap:.2rem;display:grid}.chat-update-panel strong{color:var(--fg)}.chat-update-actions{flex-shrink:0;gap:.45rem;display:flex}.chat-dangerous-panel{border:1px solid color-mix(in srgb, var(--danger) 45%, var(--border));border-radius:.75rem;flex:none;margin:0 0 .75rem;padding:.8rem .9rem}.chat-dangerous-head,.chat-dangerous-controls,.chat-dangerous-pending{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-dangerous-head{margin-bottom:.7rem}.chat-dangerous-controls{flex-wrap:wrap;align-items:stretch}.chat-dangerous-controls>div{flex:18rem;gap:.45rem;display:flex}.chat-dangerous-input{background:var(--surface-hover);min-width:0;color:var(--fg);border:1px solid var(--border-strong);font:inherit;border-radius:.5rem;flex:1;padding:.5rem .65rem}.chat-dangerous-pending-list{gap:.45rem;margin-top:.75rem;display:grid}.chat-dangerous-pending{border-top:1px solid var(--border);color:var(--fg-muted);padding-top:.55rem;font-size:.8rem}.chat-layout{flex:auto;grid-template-columns:242px minmax(0,1fr);gap:.75rem;min-height:0;display:grid;overflow:hidden}.chat-sidebar,.chat-workspace{background:var(--surface);border:1px solid var(--border);border-radius:1rem}.chat-sidebar{padding:.8rem;overflow-y:auto}.chat-sidebar-head,.chat-toolbar,.chat-compose-actions{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-session-list{gap:.35rem;margin-top:1rem;display:grid}.chat-session{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.65rem;gap:.25rem;padding:.7rem;display:grid}.chat-session:hover,.chat-session.active{background:var(--surface-hover);color:var(--fg);border-color:var(--border-strong)}.chat-session span{font-size:.72rem}.chat-workspace{grid-template-rows:auto minmax(0,1fr) auto;min-width:0;display:grid;overflow:hidden}.chat-workspace-head{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;padding:.85rem 1.1rem;display:flex}.chat-session-tools{color:var(--fg-muted);margin-left:.6rem;font-size:.78rem;position:relative}.chat-session-tools summary{cursor:pointer}.chat-session-tool-list{z-index:2;background:var(--surface);border:1px solid var(--border-strong);border-radius:.65rem;flex-wrap:wrap;gap:.35rem;width:min(22rem,72vw);padding:.55rem;display:flex;position:absolute;top:calc(100% + .45rem);right:0;box-shadow:0 .7rem 2rem #0000004d}.chat-select{background:var(--surface-hover);color:var(--fg);border:1px solid var(--border-strong);border-radius:.5rem;padding:.5rem .65rem}.chat-transcript{align-content:start;gap:1rem;padding:1.25rem;display:grid;overflow:auto}.chat-empty-state{text-align:center;place-self:center;width:min(100%,40rem);padding:3rem 1rem}.chat-empty-mark{border:1px solid var(--border-strong);width:2.6rem;height:2.6rem;color:var(--accent);border-radius:.8rem;place-items:center;margin:0 auto 1rem;font-weight:700;display:grid}.chat-empty-state h2{letter-spacing:-.04em;margin:0;font-size:clamp(1.5rem,3vw,2.25rem)}.chat-empty-state p{color:var(--fg-muted);margin:.6rem 0 1.4rem}.chat-prompt-grid{flex-wrap:wrap;justify-content:center;gap:.5rem;display:flex}.chat-prompt{border:1px solid var(--border);background:var(--surface-hover);color:var(--fg-muted);cursor:pointer;border-radius:999px;padding:.55rem .75rem}.chat-prompt:hover{color:var(--fg);border-color:var(--border-strong)}.chat-bubble-row{display:flex}.chat-bubble-row.user{justify-content:flex-end}.chat-bubble{background:var(--surface-hover);border-radius:.85rem;max-width:min(78ch,86%);padding:.8rem 1rem;line-height:1.5}.chat-bubble-row.user .chat-bubble{background:color-mix(in srgb, var(--accent) 18%, var(--surface))}.chat-bubble-meta{color:var(--fg-muted);margin-bottom:.3rem;font-size:.7rem}.chat-bubble-text{white-space:pre-wrap;overflow-wrap:anywhere}.chat-bubble-text p{margin:0 0 .7rem}.chat-bubble-text p:last-child{margin-bottom:0}.chat-bubble-text h1,.chat-bubble-text h2,.chat-bubble-text h3{letter-spacing:-.02em;margin:.2rem 0 .6rem;line-height:1.2}.chat-bubble-text h1{font-size:1.25rem}.chat-bubble-text h2{font-size:1.1rem}.chat-bubble-text h3{font-size:1rem}.chat-bubble-text ul,.chat-bubble-text ol{margin:.25rem 0 .75rem;padding-left:1.35rem}.chat-bubble-text blockquote{border-left:3px solid var(--accent);color:var(--fg-muted);margin:.5rem 0;padding:.35rem .75rem}.chat-bubble-text code{background:color-mix(in srgb, var(--fg) 10%, transparent);border-radius:.3rem;padding:.1rem .3rem;font-size:.9em}.chat-bubble-text pre{border:1px solid var(--border);background:color-mix(in srgb, var(--surface) 75%, #000);border-radius:.5rem;margin:.6rem 0;padding:.75rem;overflow:auto}.chat-bubble-text pre code{background:0 0;padding:0}.chat-bubble-text a{color:var(--accent)}.chat-bubble-text table{border-collapse:collapse;width:100%;margin:.7rem 0;font-size:.92em}.chat-bubble-text th,.chat-bubble-text td{text-align:left;border:1px solid var(--border);padding:.45rem .6rem}.chat-bubble-text th{color:var(--fg);background:color-mix(in srgb, var(--surface) 70%, transparent);font-weight:700}.chat-compose{border-top:1px solid var(--border);padding:.85rem 1rem 1rem}.chat-composer-shell{background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:.9rem;padding:.7rem .8rem .55rem;position:relative}.chat-composer{resize:vertical;box-sizing:border-box;width:100%;min-height:3.3rem;color:var(--fg);font:inherit;background:0 0;border:0;padding:.25rem 0}.chat-composer:focus{outline:0}.chat-command-menu{z-index:3;background:var(--surface);border:1px solid var(--border-strong);border-radius:.7rem;gap:.15rem;max-height:18rem;padding:.35rem;display:grid;position:absolute;bottom:calc(100% - .25rem);left:.8rem;right:.8rem;overflow:auto;box-shadow:0 .7rem 2rem #0000004d}.chat-command-menu[hidden]{display:none}.chat-command-option{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.45rem;grid-template-columns:minmax(8rem,14rem) 1fr;align-items:center;gap:.65rem;padding:.5rem .6rem;display:grid}.chat-command-option:hover,.chat-command-option[aria-selected=true]{color:var(--fg);background:var(--surface-hover);border-color:var(--border)}.chat-command-option code{color:var(--fg)}.chat-compose-actions{margin-top:.55rem}.chat-hint,.chat-empty{color:var(--fg-muted);font-size:.78rem}.chat-command-help{color:var(--fg-muted);margin-right:auto;font-size:.78rem}.chat-command-help summary{cursor:pointer}.chat-command-list{min-width:min(34rem,70vw);max-width:40rem;padding-top:.4rem;line-height:1.45}.chat-command-item{grid-template-columns:minmax(10rem,16rem) 1fr;gap:.7rem;padding:.3rem 0;display:grid}.chat-command-item code{color:var(--fg)}@media (width<=760px){.chat-topbar,.chat-topbar-actions{flex-direction:column;align-items:flex-start}.chat-layout{grid-template-columns:1fr}.chat-sidebar{max-height:14rem;overflow:auto}}@media (width<=520px){.chat-update-panel{flex-direction:column;align-items:flex-start}} diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index ca5909e07..e6536f166 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -1,12 +1,12 @@ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n!==void 0&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,help:``};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=c[e]||c.dashboard,r}async function u(e){let t=await fetch(e,{headers:{Accept:`application/json`},signal:AbortSignal.timeout(15e3)});if(t.status===401)throw new p(`unauthorised`,401);if(!t.ok)throw new p(`${t.status} ${t.statusText}`,t.status);return t.json()}function d(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function f(e){try{let t=(await e.text()).trim();if(t)return t.split(` -`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},logs:e=>u(`/api/logs`+d(e)),memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function _({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&v(o,u===!1?`var(--danger)`:`var(--ok)`))}function v(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=``,u}function y({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`var(--danger)`,o=r/2,s=r/2,c=2*Math.PI*62*(240/360),l=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${o+62*Math.cos(n)} ${s+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${o+62*Math.cos(r)} ${s+62*Math.sin(r)}`].join(` `)},u=e(`svg.gauge`,{viewBox:`0 0 ${r} ${r*.78}`,role:`img`,"aria-label":`${n}: ${i}%`});return u.innerHTML=` +`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},logs:e=>u(`/api/logs`+d(e)),memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function _({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&v(o,u===!1?`var(--danger)`:`var(--ok)`))}function v(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=``,u}function y({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`var(--danger)`,o=r/2,s=r/2,c=2*Math.PI*62*(240/360),l=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${o+62*Math.cos(n)} ${s+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${o+62*Math.cos(r)} ${s+62*Math.sin(r)}`].join(` `)},u=e(`svg.gauge`,{viewBox:`0 0 ${r} ${r*.78}`,role:`img`,"aria-label":`${n}: ${i}%`});return u.innerHTML=` `,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function I(e,t){A(u,e,t)}function L(e){j(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function D(t,n){let r=O(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function O(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function k(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function A(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),y({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function j(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),b([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function M(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function N(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var P=new Set([`waiting_human`,`parked`]),F=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function I(e){let t=e?.get?.(`status`)||``;return F.has(t)?t:``}function L(e,t){return t?t===`needs_you`?P.has(e.status):e.status===t:!0}var R={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function z(e){return R[e]||e||`Unknown`}function B(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=I(t),f=``,p=Number(t.get(`task`)),h=Number.isFinite(p)&&p>0?p:null,g=h!==null,v=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(R).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,v]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),h&&u.some(e=>String(e.id)===String(h))&&W(h),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,_({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),_({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>L(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),h===e.id&&l.append(H(e));k()}function k(){!g||!h||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${h}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=h===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),h=h===t.id?null:t.id,O(),h===t.id&&W(t.id)};return e(`tr.task-row`,{...N(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),B(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(z(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await m.taskAction(e,t),x.delete(e),t===`archive`&&(h=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function P(e){return!v||!e.owner||!e.repo?null:`${v.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=P(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function B(t){let n=P(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=P(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await m.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function V(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var H={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function U(e){return H[e]?H[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function W(e,t){return t?Math.round(e/t*100):0}function G(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await m.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},U(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.cfg-rows`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await m.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=W(t.merged,t.runs);return e(`tr`,e(`td.strong`,U(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),G(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),G(W(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),G(W(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await m.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},`Refresh`))),r)}async function a(){try{o(await m.config(),a)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}function o(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},onSaved:i};n(r,ce(t.identity,a),le(t.repositories),de(t.models,t.providers),pe(t.budgets,a),me(t.agent,a),ge(t.storage,t.containers,a),ve(t.web,a),ae(t.provenance))}return t}function ae(t){return t?.length?K(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.cfg-rows`,...t.map(e=>q(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):K(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function K(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function q(t,n,r){let i=e(`span.cfg-label`,t);if(!r?.key)return e(`div.cfg-row`,i,e(`span.cfg-value.mono`,n??`—`));if(r.locked?.[r.key])return e(`div.cfg-row`,i,e(`div.cfg-value-cell`,e(`span.cfg-value.mono`,n??`—`),e(`span.cfg-locked`,r.locked[r.key])));let a=e(`span.cfg-value.mono`,n??`—`),o=e(`button.cfg-edit`,{title:`Edit ${t}`},`Edit`),s=e(`div.cfg-value-cell`,a,o),c=e(`div.cfg-row`,i,s);return o.addEventListener(`click`,()=>oe(c,s,t,r)),c}function oe(t,n,r,i){let{key:a,type:o,raw:s,onSaved:c}=i,l=o===`bool`?e(`select.cfg-input`,e(`option`,{value:`true`,selected:s===!0},`true`),e(`option`,{value:`false`,selected:s===!1},`false`)):e(`input.cfg-input`,{type:`text`,value:String(s??``)}),u=e(`button.cfg-save`,{type:`button`},`Save`),d=e(`button.cfg-cancel`,{type:`button`},`Cancel`),f=e(`span.cfg-error`),p=e(`div.cfg-value-cell.cfg-editing`,l,u,d,f);t.replaceChild(p,n),l.focus();let h=()=>t.replaceChild(n,p);d.addEventListener(`click`,h),l.addEventListener(`keydown`,e=>{e.key===`Enter`&&u.click(),e.key===`Escape`&&h()}),u.addEventListener(`click`,async()=>{let e=se(o,l.value);if(e.error){f.textContent=e.error;return}u.disabled=!0;try{await m.configUpdate({[a]:e.value}),c?.()}catch(e){f.textContent=String(e.message||e),u.disabled=!1}})}function se(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}function ce(t,n){return t?K(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.cfg-rows`,q(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),q(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),q(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),q(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),q(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),q(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):K(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function le(t){return t?.length?K(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,ue(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):K(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function ue(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function de(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.cfg-rows`,...i.map(([e,t])=>q(fe(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return K(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function fe(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function pe(t,n){return t?K(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.cfg-rows`,q(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),q(`Max tokens`,t.max_tokens||`Unlimited`,{key:`budgets.max_tokens`,type:`int`,raw:t.max_tokens,...n}),q(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),q(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):K(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function me(t,n){return t?K(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.cfg-rows`,q(`Execution mode`,he(t.mode),{key:`agent.mode`,type:`string`,raw:t.mode,...n}),q(`Worker command`,t.command,{key:`agent.command`,type:`string`,raw:t.command,...n}),q(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):K(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function he(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function ge(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.cfg-rows`,q(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),q(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),q(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),q(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),q(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.cfg-rows`,q(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),q(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),q(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),q(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),q(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),q(`How images are refreshed`,_e(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),q(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),K(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function _e(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function ve(t,n){return t?K(`Dashboard`,`This dashboard's own listen address.`,e(`div.cfg-rows`,q(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):K(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var ye=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function be(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function xe(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...ye.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:De(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(Ee(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(Se(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(Se(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Ce)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function Se(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Ce(t){let n=t.fields||{};return e(`div.log-row.log-${be(t.level)}`,e(`span.log-time.mono`,Te(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(we(n))))))}function we(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Te(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function Ee(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function De(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Oe(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(ke)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function ke(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ae(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ae(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var je=`
+ class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function I(e,t){A(u,e,t)}function L(e){j(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function D(t,n){let r=O(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function O(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function k(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function A(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),y({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function j(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),b([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function M(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function N(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var P=new Set([`waiting_human`,`parked`]),F=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function I(e){let t=e?.get?.(`status`)||``;return F.has(t)?t:``}function L(e,t){return t?t===`needs_you`?P.has(e.status):e.status===t:!0}var R={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function z(e){return R[e]||e||`Unknown`}function B(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=I(t),f=``,p=Number(t.get(`task`)),h=Number.isFinite(p)&&p>0?p:null,g=h!==null,v=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(R).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,v]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),h&&u.some(e=>String(e.id)===String(h))&&W(h),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,_({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),_({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>L(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),h===e.id&&l.append(H(e));k()}function k(){!g||!h||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${h}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=h===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),h=h===t.id?null:t.id,O(),h===t.id&&W(t.id)};return e(`tr.task-row`,{...N(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),B(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(z(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await m.taskAction(e,t),x.delete(e),t===`archive`&&(h=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function P(e){return!v||!e.owner||!e.repo?null:`${v.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=P(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function B(t){let n=P(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=P(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await m.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function V(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var H={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function U(e){return H[e]?H[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function W(e,t){return t?Math.round(e/t*100):0}function G(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await m.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},U(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.cfg-rows`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await m.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=W(t.merged,t.runs);return e(`tr`,e(`td.strong`,U(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),G(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),G(W(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),G(W(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await m.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},`Refresh`))),r)}async function a(){try{o(await m.config(),a)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}function o(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,le(t.identity,a),ue(t.repositories),fe(t.models,t.providers),me(t.budgets,a),he(t.agent,a),_e(t.storage,t.containers,a),ye(t.web,a),ae(t.provenance))}return t}function ae(t){return t?.length?K(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.cfg-rows`,...t.map(e=>q(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):K(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function K(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function q(t,n,r){let i=e(`span.cfg-label`,t);if(!r?.key)return e(`div.cfg-row`,i,e(`span.cfg-value.mono`,n??`—`));if(r.locked?.[r.key])return e(`div.cfg-row`,i,e(`div.cfg-value-cell`,e(`span.cfg-value.mono`,n??`—`),e(`span.cfg-locked`,r.locked[r.key])));let a=e(`span.cfg-value.mono`,n??`—`),o=e(`button.cfg-edit`,{title:`Edit ${t}`},`Edit`),s=r.overridden?.includes(r.key),c=e(`div.cfg-value-cell`,a,s&&e(`span.cfg-overridden`,{title:`Set via the dashboard; edit the file, then reset`},`overridden`),o,s&&e(`button.cfg-edit`,{title:`Reset to the file value`},`Reset`)),l=e(`div.cfg-row`,i,c);if(o.addEventListener(`click`,()=>se(l,c,t,r)),s){let e=c.lastChild;e.addEventListener(`click`,()=>oe(e,r))}return l}function oe(e,t){let{key:n,onSaved:r}=t,i=e.parentElement.querySelector(`.cfg-overridden`);e.disabled=!0,m.configReset(n).then(()=>r?.()).catch(t=>{e.disabled=!1,i&&(i.textContent=String(t.message||t),i.classList.add(`cfg-error`))})}function se(t,n,r,i){let{key:a,type:o,raw:s,onSaved:c}=i,l=o===`bool`?e(`select.cfg-input`,e(`option`,{value:`true`,selected:s===!0},`true`),e(`option`,{value:`false`,selected:s===!1},`false`)):e(`input.cfg-input`,{type:`text`,value:String(s??``)}),u=e(`button.cfg-save`,{type:`button`},`Save`),d=e(`button.cfg-cancel`,{type:`button`},`Cancel`),f=e(`span.cfg-error`),p=e(`div.cfg-value-cell.cfg-editing`,l,u,d,f);t.replaceChild(p,n),l.focus();let h=()=>t.replaceChild(n,p);d.addEventListener(`click`,h),l.addEventListener(`keydown`,e=>{e.key===`Enter`&&u.click(),e.key===`Escape`&&h()}),u.addEventListener(`click`,async()=>{let e=ce(o,l.value);if(e.error){f.textContent=e.error;return}u.disabled=!0;try{await m.configUpdate({[a]:e.value}),c?.()}catch(e){f.textContent=String(e.message||e),u.disabled=!1}})}function ce(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}function le(t,n){return t?K(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.cfg-rows`,q(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),q(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),q(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),q(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),q(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),q(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):K(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ue(t){return t?.length?K(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,de(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):K(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function de(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function fe(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.cfg-rows`,...i.map(([e,t])=>q(pe(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return K(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function pe(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function me(t,n){return t?K(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.cfg-rows`,q(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),q(`Max tokens`,t.max_tokens||`Unlimited`,{key:`budgets.max_tokens`,type:`int`,raw:t.max_tokens,...n}),q(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),q(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):K(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function he(t,n){return t?K(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.cfg-rows`,q(`Execution mode`,ge(t.mode),{key:`agent.mode`,type:`string`,raw:t.mode,...n}),q(`Worker command`,t.command,{key:`agent.command`,type:`string`,raw:t.command,...n}),q(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):K(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function ge(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function _e(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.cfg-rows`,q(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),q(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),q(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),q(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),q(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.cfg-rows`,q(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),q(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),q(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),q(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),q(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),q(`How images are refreshed`,ve(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),q(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),K(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function ve(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function ye(t,n){return t?K(`Dashboard`,`This dashboard's own listen address.`,e(`div.cfg-rows`,q(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):K(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var be=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function xe(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Se(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...be.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Oe(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(De(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(Ce(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(Ce(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(we)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function Ce(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function we(t){let n=t.fields||{};return e(`div.log-row.log-${xe(t.level)}`,e(`span.log-time.mono`,Ee(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(Te(n))))))}function Te(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Ee(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function De(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Oe(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function ke(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Ae)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Ae(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,je(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function je(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var Me=`
ARCHIE WORKSPACE

Chat

@@ -71,10 +71,10 @@
-`;function Me(){let e=document.createElement(`template`);e.innerHTML=je.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function J(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return ii&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i{i.length&&(n.append(e(`p`,J(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;te(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` -`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Pe(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Fe(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Ie(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?Ne(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=Ne(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}var Le=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(Le);return e||(e=crypto.randomUUID(),localStorage.setItem(Le,e)),e}function Re(e){return{text:e,sourceID:crypto.randomUUID()}}function ze(e){return{...e}}function Be(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?ze(e.turn):Re(r),isRetry:n}}function Ve({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Fe(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function He(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,Ue(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function Ue(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function We(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function Ge(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function Ke(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function qe(e){return e?.status===501?null:`Could not check for updates.`}function Je(){let{root:t,refs:n}=Me(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(Ie(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await m.chatUpdate();E=e?.snapshot||null,Ge(h,e,{onDefer:async()=>{await m.chatUpdateDefer(E),Ge(h,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(E),c.textContent=`Update started`,I()}})}catch(t){let n=qe(t);h.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{Ke(g,await m.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await m.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await m.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await m.chatSessions();C=e.sessions||[],D=e,He({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=We(y,e.commands),Ve({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await m.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,Ve({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await m.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let t=await m.chatMessages(e);for(let e of t)j(e);i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=Be(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-bubble-text`)));l||i.append(u),u.querySelector(`.chat-retry`)?.remove();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` +`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=Y(l),d=t+1e(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` +`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Fe(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Ie(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Le(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?Pe(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=Pe(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}var Re=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(Re);return e||(e=crypto.randomUUID(),localStorage.setItem(Re,e)),e}function ze(e){return{text:e,sourceID:crypto.randomUUID()}}function Be(e){return{...e}}function Ve(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?Be(e.turn):ze(r),isRetry:n}}function He({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Ie(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function Ue(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,We(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function We(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function Ge(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function Ke(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function qe(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function Je(e){return e?.status===501?null:`Could not check for updates.`}function Ye(){let{root:t,refs:n}=Ne(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(Le(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await m.chatUpdate();E=e?.snapshot||null,Ke(h,e,{onDefer:async()=>{await m.chatUpdateDefer(E),Ke(h,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(E),c.textContent=`Update started`,I()}})}catch(t){let n=Je(t);h.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{qe(g,await m.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await m.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await m.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await m.chatSessions();C=e.sessions||[],D=e,Ue({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=Ge(y,e.commands),He({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await m.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,He({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await m.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let t=await m.chatMessages(e);for(let e of t)j(e);i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=Ve(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-bubble-text`)));l||i.append(u),u.querySelector(`.chat-retry`)?.remove();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` `);i=a.pop()||``;for(let e of a){let t=e.split(` -`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=ze(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{Ue({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:Je},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:xe},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:Oe},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:ie}],Ye=`archie.theme`;function Xe(e){document.documentElement.dataset.theme=e,localStorage.setItem(Ye,e)}function $(){return localStorage.getItem(Ye)||`dark`}function Ze(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Xe($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function Qe(){Xe($());let t=e(`main.main`),r=Ze(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):$e(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function $e(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}Qe(); \ No newline at end of file +`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=Be(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{We({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:Ye},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:Se},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:ke},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:ie}],Xe=`archie.theme`;function Ze(e){document.documentElement.dataset.theme=e,localStorage.setItem(Xe,e)}function $(){return localStorage.getItem(Xe)||`dark`}function Qe(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Ze($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function $e(){Ze($());let t=e(`main.main`),r=Qe(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):et(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function et(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}$e(); \ No newline at end of file diff --git a/ui/src/base/api.js b/ui/src/base/api.js index 7f7a51d21..3b56e0c07 100644 --- a/ui/src/base/api.js +++ b/ui/src/base/api.js @@ -96,6 +96,16 @@ export const api = { if (!res.ok) throw new ApiError(await errorMessage(res), res.status); return res.json(); }, + configReset: async (key) => { + const res = await fetch("/api/config/reset", { + method: "POST", + headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" }, + body: JSON.stringify({ key }), + signal: AbortSignal.timeout(15000), + }); + if (!res.ok) throw new ApiError(await errorMessage(res), res.status); + return res.json(); + }, logs: (params) => req("/api/logs" + qs(params)), memory: () => req("/api/memory"), chatSessions: () => req("/api/chat/sessions"), diff --git a/ui/src/settings/settings.css b/ui/src/settings/settings.css index 7b22a57cd..288f36fdc 100644 --- a/ui/src/settings/settings.css +++ b/ui/src/settings/settings.css @@ -145,6 +145,21 @@ font-style: italic; } +.cfg-overridden { + font-size: var(--text-xs); + color: var(--warn); +} + +.cfg-notice { + border-left: 3px solid var(--warn); +} + +.cfg-notice p { + margin: 0; + font-size: var(--text-sm); + color: var(--warn); +} + .cfg-error { font-size: var(--text-xs); color: var(--danger); diff --git a/ui/src/settings/settings.js b/ui/src/settings/settings.js index 94021c0c3..3b909f294 100644 --- a/ui/src/settings/settings.js +++ b/ui/src/settings/settings.js @@ -63,9 +63,16 @@ export function settingsPage() { return; } - const ctx = { locked: cfg.locked || {}, onSaved: reload }; + const ctx = { locked: cfg.locked || {}, overridden: cfg.overridden || [], onSaved: reload }; + const banners = [ + cfg.reload?.overlay_unavailable && + el("div.card.cfg-notice", el("p", `The runtime config overlay is not in effect: ${cfg.reload.overlay_unavailable}`)), + cfg.reload?.last_error && + el("div.card.cfg-notice", el("p", `The last config reload failed; the running config is unchanged: ${cfg.reload.last_error}`)), + ]; mount( body, + ...banners, identityCard(cfg.identity, ctx), repositoriesCard(cfg.repositories), modelsAndProvidersCard(cfg.models, cfg.providers), @@ -99,8 +106,9 @@ function section(title, sub, ...children) { // row renders one label/value pair. opts.key makes it editable via a // PATCH to /api/config; opts.locked[key] disables it with the server's -// reason; no key means a plain read-only row (structured values and -// provenance). +// reason; opts.overridden marks a key whose file value is shadowed by +// the runtime overlay and offers a reset; no key means a plain read-only +// row (structured values and provenance). function row(label, value, opts) { const labelEl = el("span.cfg-label", label); if (!opts?.key) { @@ -119,12 +127,42 @@ function row(label, value, opts) { } const display = el("span.cfg-value.mono", value ?? "—"); const editBtn = el("button.cfg-edit", { title: `Edit ${label}` }, "Edit"); - const cell = el("div.cfg-value-cell", display, editBtn); + const overridden = opts.overridden?.includes(opts.key); + const cell = el( + "div.cfg-value-cell", + display, + overridden && el("span.cfg-overridden", { title: "Set via the dashboard; edit the file, then reset" }, "overridden"), + editBtn, + overridden && el("button.cfg-edit", { title: "Reset to the file value" }, "Reset"), + ); const rowEl = el("div.cfg-row", labelEl, cell); editBtn.addEventListener("click", () => startEdit(rowEl, cell, label, opts)); + if (overridden) { + const resetBtn = cell.lastChild; + resetBtn.addEventListener("click", () => resetOverride(resetBtn, opts)); + } return rowEl; } +// resetOverride deletes one runtime-overlay row via the reset seam, then +// re-renders so the row returns to its file value. Errors show inline in +// the row's marker slot. +function resetOverride(btn, opts) { + const { key, onSaved } = opts; + const marker = btn.parentElement.querySelector(".cfg-overridden"); + btn.disabled = true; + api + .configReset(key) + .then(() => onSaved?.()) + .catch((err) => { + btn.disabled = false; + if (marker) { + marker.textContent = String(err.message || err); + marker.classList.add("cfg-error"); + } + }); +} + function startEdit(rowEl, cell, label, opts) { const { key, type, raw, onSaved } = opts; const input = type === "bool" From 479ed95a91f3f4f55e282b8183dcdf7a077ac6b6 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 01:23:34 +1000 Subject: [PATCH 09/13] fix(config): close review blocker on the PATCH path; deep-copy snapshots; atomics for shared state Second adversarial pass findings, fixed: BLOCKER -- PATCH silently dropped every dotted key. The UI sends dotted keys ('budgets.max_steps') but ApplyOverlayValues fed them straight to yaml.Unmarshal, which cannot decode a dotted key as a struct field and silently ignored it: 200 OK, zero effect, and the row still persisted (poisoning later reloads with an unvalidated value). The reload path worked only because overlay.Snapshot nests first. Fix: applyDottedOverlay nests dotted keys via overlay.Nest before decode -- the same nesting Snapshot performs -- and is pinned by TestApplyDottedOverlayNestsBeforeDecode, which fails against the old behaviour. MAJOR -- shallow copies let overlay decode mutate the published snapshot. Holder.Get and *doc are shallow; yaml decodes maps in place, so a crafted nested update (or a failed boot overlay apply) mutated shared maps of the published config before validation. Fix: config.Clone deep-copies every reference field (Models, Providers, Repos, Identities, Dispatch.Labels, Agent.Env, Chat/Telegram slices, Tools.MCPServers, Memory.ProviderConfig, WebFetch.Enabled pointer, Extra), used by the PATCH path (next := d.Cfg.Get().Clone()) and by Loader.ApplyOverlay, which now never mutates its input (clones Config and the provenance chain internally), so boot and reload pass the base document directly and a failed apply leaves it exactly as it was. Pinned by TestConfigCloneDeepCopiesReferenceFields. MAJOR -- data races on captured main.go variables. bootOverlayErr and currentProvenance were plain values written by the SIGHUP goroutine and the PATCH/Reset handlers and read by every GET /api/config; -race passed only because no test exercised the composition root concurrently. Both are now atomic.Pointer; the LastReload closure and the provenance dedup read them atomically. MINOR -- MaxConcurrency removed from the reloadable allowlist. The dispatchers re-read it but the startup-built container pool captures it (container/pool.go:94,163), so 'every consumer re-reads it' is false and a change only partially applies. It now warns requires-restart; the criterion comment on reloadableFields documents the pool capture. MINOR -- ResetConfig now resolves and validates the target state BEFORE deleting the row, so a broken file cannot leave the store and the running config disagreeing; the provenance chain no longer grows unboundedly (the runtime-overlay origin replaces, not appends). Also: holder.go no longer references a file watcher that does not exist. Verified: task check clean; -race clean on cmd/archied, webui, daemon, config; new findings from the second adversarial pass are closed. --- cmd/archied/config_update.go | 24 +++++ cmd/archied/config_update_test.go | 34 +++++++ cmd/archied/main.go | 96 ++++++++++++------- cmd/archied/reload.go | 22 +++-- cmd/archied/reload_test.go | 7 +- internal/config/clone_test.go | 74 ++++++++++++++ internal/config/config.go | 69 +++++++++++++ internal/config/holder.go | 10 +- .../configuration/apply_test.go | 7 +- .../infrastructure/configuration/loader.go | 25 +++-- 10 files changed, 301 insertions(+), 67 deletions(-) create mode 100644 cmd/archied/config_update.go create mode 100644 cmd/archied/config_update_test.go create mode 100644 internal/config/clone_test.go diff --git a/cmd/archied/config_update.go b/cmd/archied/config_update.go new file mode 100644 index 000000000..2bce0cf53 --- /dev/null +++ b/cmd/archied/config_update.go @@ -0,0 +1,24 @@ +package main + +import ( + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay" +) + +// applyDottedOverlay decodes dotted-path updates into cfg. yaml cannot +// decode dotted keys ("budgets.max_steps" is not a struct field), so +// the updates are nested into a map first -- the same nesting the +// overlay store's Snapshot performs -- then decoded with the same +// field-level merge the file overlay uses. cfg must be a copy the +// caller owns (a Clone of the published config); it is never decoded +// into a published snapshot directly. +func applyDottedOverlay(cfg *config.Config, updates map[string]any) error { + nested := make(map[string]any) + for key, value := range updates { + if err := overlay.Nest(nested, key, value); err != nil { + return err + } + } + return configuration.ApplyOverlayValues(cfg, nested) +} diff --git a/cmd/archied/config_update_test.go b/cmd/archied/config_update_test.go new file mode 100644 index 000000000..3faf58c69 --- /dev/null +++ b/cmd/archied/config_update_test.go @@ -0,0 +1,34 @@ +package main + +import ( + "testing" + + "github.com/samcharles93/archie-core/internal/config" +) + +// TestApplyDottedOverlayNestsBeforeDecode pins the PATCH-path fix: the +// UI sends dotted keys ("budgets.max_steps") and yaml cannot decode a +// dotted key as a struct field, so the updates must be nested first. A +// regression here silently drops every dotted update while returning 200. +func TestApplyDottedOverlayNestsBeforeDecode(t *testing.T) { + cfg := config.Config{Budgets: config.Budgets{MaxSteps: 10}} + if err := applyDottedOverlay(&cfg, map[string]any{"budgets.max_steps": 20}); err != nil { + t.Fatal(err) + } + if cfg.Budgets.MaxSteps != 20 { + t.Fatalf("MaxSteps = %d, want 20 (dotted key must be nested before decode)", cfg.Budgets.MaxSteps) + } + // A field the update does not name keeps its value. + if cfg.Budgets.MaxTokens != 0 { + t.Errorf("MaxTokens = %d, want 0 (untouched)", cfg.Budgets.MaxTokens) + } +} + +// TestApplyDottedOverlayRejectsEmptyKey pins that a malformed dotted key +// fails instead of silently nesting under a synthetic root. +func TestApplyDottedOverlayRejectsEmptyKey(t *testing.T) { + cfg := config.Config{} + if err := applyDottedOverlay(&cfg, map[string]any{"": 1}); err == nil { + t.Fatal("empty dotted key accepted") + } +} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index bf72855e9..48c94920d 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -19,6 +19,7 @@ import ( "sort" "strconv" "strings" + "sync/atomic" "syscall" "time" @@ -352,22 +353,24 @@ func run() int { // degrade reason into /api/config's reload status so it is visible // where the operator is looking, not only in logs. var overlayStore *overlay.Store - var bootOverlayErr string + var bootOverlayErr atomic.Pointer[string] if !skipOverlay { overlayStore, err = overlay.Open(ctx, configDBPath(doc.Config.DBPath)) if err != nil { - bootOverlayErr = err.Error() + reason := err.Error() + bootOverlayErr.Store(&reason) log.Error("config overlay unavailable; booting on file config alone", "path", configDBPath(doc.Config.DBPath), "err", err) } else { defer overlayStore.Close() if overrides, err := overlayStore.Snapshot(ctx); err != nil { - bootOverlayErr = err.Error() + reason := err.Error() + bootOverlayErr.Store(&reason) log.Error("config overlay unreadable; booting on file config alone", "err", err) } else if len(overrides) > 0 { - next := *doc - applied, err := loader.ApplyOverlay(&next, overrides) + applied, err := loader.ApplyOverlay(doc, overrides) if err != nil { - bootOverlayErr = err.Error() + reason := err.Error() + bootOverlayErr.Store(&reason) log.Error("config overlay rejected by validation; booting on file config alone", "err", err) } else { doc = applied @@ -376,6 +379,8 @@ func run() int { } } cfg := doc.Config + var currentProvenance atomic.Pointer[configuration.Provenance] + currentProvenance.Store(&doc.Provenance) // Re-create the logger now the config is known. Everything above this // point logs to stderr only, which is unavoidable: the log destination is @@ -1033,9 +1038,9 @@ func run() int { // publishConfig publishes a config snapshot and its provenance to // both the daemon and the dashboard (they share one Holder). Reload // and the PATCH path both go through it, so the two can never - // diverge. currentProvenance is the last published provenance chain; - // the PATCH path appends the runtime-overlay origin to it. - currentProvenance := doc.Provenance + // diverge. currentProvenance (an atomic) is the last published + // provenance chain; the PATCH path appends the runtime-overlay + // origin to it. publishConfig := func(cfg config.Config, provenance configuration.Provenance) { d.Cfg.Set(cfg) origins := make([]webui.ConfigOrigin, 0, len(provenance.Origins)) @@ -1060,7 +1065,7 @@ func run() int { // failed to load merges to identity). applyModelCatalog(&doc.Config, catalog) old := d.Cfg.Get() - currentProvenance = doc.Provenance + currentProvenance.Store(&doc.Provenance) publishConfig(doc.Config, doc.Provenance) if fields := changedNonReloadableFields(old, doc.Config); len(fields) > 0 { log.Warn("config reloaded; some changes require a restart", @@ -1077,14 +1082,18 @@ func run() int { // and whether the runtime overlay is in effect at all. web.LastReload = func() config.ReloadStatus { st := reloadController.Status() - st.OverlayUnavailable = bootOverlayErr + if p := bootOverlayErr.Load(); p != nil { + st.OverlayUnavailable = *p + } return st } // PATCH /api/config goes through the same publish path as reload: - // apply to a copy of the published config, validate the materialised - // result, persist to the overlay, then publish. It must never call - // Set directly from the handler -- web.Cfg is the daemon's own Holder. + // apply to a deep copy of the published config, validate the + // materialised result, persist to the overlay, then publish. It must + // never call Set directly from the handler -- web.Cfg is the daemon's + // own Holder -- and it decodes into a Clone so a failed validation + // cannot mutate the published snapshot's shared maps. web.UpdateConfig = func(ctx context.Context, updates map[string]any) error { if overlayStore == nil { return fmt.Errorf("%w: config overlay is disabled (--no-config-overlay or ARCHIE_SKIP_CONFIG_OVERLAY=1)", webui.ErrConfigUpdateUnavailable) @@ -1094,27 +1103,36 @@ func run() int { return fmt.Errorf("%w: config key %s is not runtime-tunable: %s", webui.ErrConfigUpdateInvalid, key, reason) } } - next := d.Cfg.Get() - if err := configuration.ApplyOverlayValues(&next, updates); err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + next := d.Cfg.Get().Clone() + if err := applyDottedOverlay(&next, updates); err != nil { + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) } if err := configuration.Validate(&next); err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) } for key, value := range updates { data, err := json.Marshal(value) if err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) } if err := overlayStore.Set(ctx, key, string(data), "dashboard"); err != nil { return err } } - prov := configuration.Provenance{Origins: append(append([]configuration.Origin{}, currentProvenance.Origins...), + // Provenance gets the runtime-overlay origin, replacing any prior + // one so the chain does not grow unboundedly across edits. + var kept []configuration.Origin + for _, origin := range currentProvenance.Load().Origins { + if origin.Path == "config_overlay (runtime)" { + continue + } + kept = append(kept, origin) + } + prov := configuration.Provenance{Origins: append(kept, configuration.Origin{Path: "config_overlay (runtime)", Role: configuration.RoleMain, Layer: configuration.LayerOverlay})} - currentProvenance = prov + currentProvenance.Store(&prov) publishConfig(next, prov) - bootOverlayErr = "" // a successful write proves the overlay works again + bootOverlayErr.Store(nil) // a successful write proves the overlay works again log.Info("config updated from dashboard", "keys", len(updates)) return nil } @@ -1141,30 +1159,34 @@ func run() int { // ResetConfig deletes one overlay row and republishes file + remaining // overlay, so a dashboard-created override can be removed without // editing SQL -- and so an operator whose file edit is shadowed by an - // override can recover it with one click. + // override can recover it with one click. The file is resolved and + // the target state validated BEFORE the row is deleted, so a broken + // file cannot leave the store and the running config disagreeing. web.ResetConfig = func(ctx context.Context, key string) error { if overlayStore == nil { return fmt.Errorf("%w: config overlay is disabled", webui.ErrConfigUpdateUnavailable) } + overrides, err := overlayStore.Snapshot(ctx) + if err != nil { + return err + } + delete(overrides, key) // the target overlay state after the reset + doc, err := loader.Resolve(*cfgPath, *overlayPath) + if err != nil { + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) + } + if len(overrides) > 0 { + if doc, err = loader.ApplyOverlay(doc, overrides); err != nil { + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) + } + } if err := overlayStore.Delete(ctx, key); err != nil { return err } - doc, err := loader.Resolve(*cfgPath, *overlayPath) - if err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) - } - if overrides, err := overlayStore.Snapshot(ctx); err != nil { - return err - } else if len(overrides) > 0 { - next := *doc - if doc, err = loader.ApplyOverlay(&next, overrides); err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) - } - } applyModelCatalog(&doc.Config, catalog) - currentProvenance = doc.Provenance + currentProvenance.Store(&doc.Provenance) publishConfig(doc.Config, doc.Provenance) - bootOverlayErr = "" + bootOverlayErr.Store(nil) log.Info("config key reset to file value", "key", key) return nil } diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go index 473dc075b..06c6b315f 100644 --- a/cmd/archied/reload.go +++ b/cmd/archied/reload.go @@ -67,8 +67,9 @@ func (c *ReloadController) Reload() error { return err } if len(values) > 0 { - next := *doc - if doc, err = c.loader.ApplyOverlay(&next, values); err != nil { + // ApplyOverlay never mutates its input: on failure the + // resolved document (and the running config) is untouched. + if doc, err = c.loader.ApplyOverlay(doc, values); err != nil { c.status.Store(&config.ReloadStatus{ LastError: err.Error(), LastErrorAt: time.Now().UTC().Format(time.RFC3339), @@ -160,14 +161,17 @@ var reloadableFields = map[string]bool{ } // reloadableSubFields are sub-fields of structs that are otherwise -// startup-built. VolumeTTL and MaxConcurrency are re-read per cycle -// (cleanupExpiredStorage, drainSQLite/drainNATS); everything else in -// Containers (Image, Enabled, MaxUptime, PullPolicy, Network) is frozen -// in the startup-built container pool. Forge.Host is carried into -// TaskContext by ForTask (display/link building only); the forge client -// itself is startup-built, so Type/Token/TokenEnv stay requires-restart. +// startup-built. VolumeTTL is re-read per cycle in cleanupExpiredStorage; +// everything else in Containers (Image, Enabled, MaxConcurrency, +// MaxUptime, PullPolicy, Network) is frozen in the startup-built +// container pool -- the dispatchers re-read MaxConcurrency but the pool +// captures it at construction (container/pool.go:94,163), so a change +// only partially applies and must warn requires-restart. Forge.Host is +// carried into TaskContext by ForTask (display/link building only); the +// forge client itself is startup-built, so Type/Token/TokenEnv stay +// requires-restart. var reloadableSubFields = map[string]map[string]bool{ - "Containers": {"VolumeTTL": true, "MaxConcurrency": true}, + "Containers": {"VolumeTTL": true}, "Forge": {"Host": true}, } diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go index efcae7d77..e155330df 100644 --- a/cmd/archied/reload_test.go +++ b/cmd/archied/reload_test.go @@ -230,8 +230,11 @@ func TestChangedNonReloadableFields(t *testing.T) { } c3 := c1 c3.Containers.MaxConcurrency = 4 - if got := changedNonReloadableFields(c1, c3); len(got) != 0 { - t.Fatalf("MaxConcurrency change: got %v, want []", got) + // MaxConcurrency is NOT reloadable: the dispatchers re-read it but the + // startup-built container pool captures it (container/pool.go:94), so + // a change only partially applies and must warn requires-restart. + if got := changedNonReloadableFields(c1, c3); len(got) != 1 || got[0] != "Containers.MaxConcurrency" { + t.Fatalf("MaxConcurrency change: got %v, want [Containers.MaxConcurrency]", got) } c4 := c1 c4.Containers.VolumeTTL = config.Duration(48 * time.Hour) diff --git a/internal/config/clone_test.go b/internal/config/clone_test.go new file mode 100644 index 000000000..e53148bee --- /dev/null +++ b/internal/config/clone_test.go @@ -0,0 +1,74 @@ +package config + +import "testing" + +// TestConfigCloneDeepCopiesReferenceFields pins that Clone returns a +// value sharing no memory with the original: mutating the clone's maps +// and slices must not touch the original. A shallow copy here would +// silently let a failed overlay decode mutate the published snapshot. +func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { + enabled := true + orig := Config{ + Models: map[string]string{"builder": "m"}, + Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}}, + Identities: []IdentityConfig{{ + Models: map[string]string{"planner": "m2"}, + Repos: []Repo{{Gate: [][]string{{"go", "vet"}}}}, + }}, + Dispatch: Dispatch{Labels: map[string]string{"q": "archie:q"}}, + Tools: ToolsConfig{ + MCPServers: []MCPServer{{Headers: map[string]string{"A": "b"}, Args: []string{"x"}}}, + WebFetch: WebFetchConfig{Enabled: &enabled}, + }, + Memory: MemoryConfig{ProviderConfig: map[string]string{"k": "v"}}, + Chat: ChatConfig{Telegram: TelegramConfig{AllowedUserIDs: []int64{1}}}, + Agent: Agent{Env: []string{"HOME"}}, + Extra: map[string]any{"custom": 1}, + } + + got := orig.Clone() + got.Models["builder"] = "changed" + got.Repos[0].Gate[0][0] = "changed" + got.Repos[0].Protect[0] = "changed" + got.Identities[0].Models["planner"] = "changed" + got.Identities[0].Repos[0].Gate[0][0] = "changed" + got.Dispatch.Labels["q"] = "changed" + got.Tools.MCPServers[0].Headers["A"] = "changed" + got.Tools.MCPServers[0].Args[0] = "changed" + got.Memory.ProviderConfig["k"] = "changed" + got.Chat.Telegram.AllowedUserIDs[0] = 99 + got.Agent.Env[0] = "changed" + got.Extra["custom"] = 2 + *got.Tools.WebFetch.Enabled = false + + if orig.Models["builder"] != "m" { + t.Error("Models map is shared") + } + if orig.Repos[0].Gate[0][0] != "task" || orig.Repos[0].Protect[0] != "p" { + t.Error("Repo nested slices are shared") + } + if orig.Identities[0].Models["planner"] != "m2" || orig.Identities[0].Repos[0].Gate[0][0] != "go" { + t.Error("Identity nested fields are shared") + } + if orig.Dispatch.Labels["q"] != "archie:q" { + t.Error("Dispatch.Labels map is shared") + } + if orig.Tools.MCPServers[0].Headers["A"] != "b" || orig.Tools.MCPServers[0].Args[0] != "x" { + t.Error("MCP server fields are shared") + } + if orig.Memory.ProviderConfig["k"] != "v" { + t.Error("Memory.ProviderConfig is shared") + } + if orig.Chat.Telegram.AllowedUserIDs[0] != 1 { + t.Error("Telegram.AllowedUserIDs is shared") + } + if orig.Agent.Env[0] != "HOME" { + t.Error("Agent.Env is shared") + } + if orig.Extra["custom"] != 1 { + t.Error("Extra map is shared") + } + if !*orig.Tools.WebFetch.Enabled { + t.Error("WebFetch.Enabled pointer is shared") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index bdc088795..8f59d3ca9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -489,6 +489,75 @@ func cloneStringMap(src map[string]string) map[string]string { return dst } +// Clone returns a deep copy of c: every reference-type field (maps, +// slices, and the reference fields nested inside them) is copied, so +// mutating the returned value cannot touch c or anything sharing memory +// with it. It is used before the runtime overlay (or a dashboard PATCH) +// decodes into a snapshot, so a failed or partial decode cannot mutate +// the published config -- Holder.Get returns a shallow copy whose maps +// are shared with the published snapshot. +func (c Config) Clone() Config { + c.Models = cloneStringMap(c.Models) + c.Providers = maps.Clone(c.Providers) + c.Dispatch.Labels = cloneStringMap(c.Dispatch.Labels) + c.Agent.Env = append([]string(nil), c.Agent.Env...) + c.Repos = cloneRepos(c.Repos) + c.Identities = cloneIdentities(c.Identities) + c.Chat.Models = append([]string(nil), c.Chat.Models...) + c.Chat.Telegram.AllowedUserIDs = append([]int64(nil), c.Chat.Telegram.AllowedUserIDs...) + c.Chat.Telegram.UpdateCheckCommand = append([]string(nil), c.Chat.Telegram.UpdateCheckCommand...) + c.Chat.Telegram.UpdateInstallCommand = append([]string(nil), c.Chat.Telegram.UpdateInstallCommand...) + c.Tools.MCPServers = cloneMCPServers(c.Tools.MCPServers) + c.Memory.ProviderConfig = maps.Clone(c.Memory.ProviderConfig) + if c.Tools.WebFetch.Enabled != nil { + v := *c.Tools.WebFetch.Enabled + c.Tools.WebFetch.Enabled = &v + } + c.Extra = maps.Clone(c.Extra) + return c +} + +func cloneRepos(repos []Repo) []Repo { + out := make([]Repo, len(repos)) + for i, r := range repos { + r.Gate = cloneStringSlices(r.Gate) + r.Protect = append([]string(nil), r.Protect...) + r.Preflight = cloneStringSlices(r.Preflight) + out[i] = r + } + return out +} + +func cloneIdentities(ids []IdentityConfig) []IdentityConfig { + out := make([]IdentityConfig, len(ids)) + for i, id := range ids { + id.Models = cloneStringMap(id.Models) + id.Providers = maps.Clone(id.Providers) + id.Dispatch.Labels = cloneStringMap(id.Dispatch.Labels) + id.Repos = cloneRepos(id.Repos) + out[i] = id + } + return out +} + +func cloneMCPServers(servers []MCPServer) []MCPServer { + out := make([]MCPServer, len(servers)) + for i, s := range servers { + s.Args = append([]string(nil), s.Args...) + s.Headers = maps.Clone(s.Headers) + out[i] = s + } + return out +} + +func cloneStringSlices(ss [][]string) [][]string { + out := make([][]string, len(ss)) + for i, s := range ss { + out[i] = append([]string(nil), s...) + } + return out +} + // NATSConfig configures NATS JetStream for task distribution. When URL is // empty the existing SQLite ClaimNext flow is used unchanged. type NATSConfig struct { diff --git a/internal/config/holder.go b/internal/config/holder.go index 1e2210d7e..02f4bece5 100644 --- a/internal/config/holder.go +++ b/internal/config/holder.go @@ -16,11 +16,11 @@ import "sync" // mutates the published snapshot too, and any other reader sees the // mutation outside the protection of the read lock. // -// Reload paths (Loader.Reload, the file watcher, the UI PATCH handler) -// construct a fresh Config and call Set; they never mutate an existing -// one. Decode paths must finish constructing the new Config before Set -// is called; the existing decode.go:80 cfg.Extra[name] = value is fine -// because it runs pre-publish. +// Reload paths (a SIGHUP reload re-calling Loader.Resolve, the UI PATCH +// handler) construct a fresh Config and call Set; they never mutate an +// existing one. Decode paths must finish constructing the new Config +// before Set is called; the existing decode.go:80 cfg.Extra[name] = value +// is fine because it runs pre-publish. // // # Torn reads across a field group // diff --git a/internal/infrastructure/configuration/apply_test.go b/internal/infrastructure/configuration/apply_test.go index 31dcf90c3..dd5aa0e4f 100644 --- a/internal/infrastructure/configuration/apply_test.go +++ b/internal/infrastructure/configuration/apply_test.go @@ -57,10 +57,9 @@ func TestLoaderApplyOverlayLayersDefaultsValidatesAndRecordsProvenance(t *testin t.Errorf("Origins = %+v, want 2 (file + runtime overlay)", applied.Provenance.Origins) } - // An overlay that fails validation aborts; the base document is - // untouched when a copy is passed. - next := *doc - if _, err := l.ApplyOverlay(&next, map[string]any{"agent": map[string]any{"mode": "bogus"}}); err == nil { + // An overlay that fails validation aborts; ApplyOverlay never mutates + // its input, so the base document is untouched even without a copy. + if _, err := l.ApplyOverlay(doc, map[string]any{"agent": map[string]any{"mode": "bogus"}}); err == nil { t.Fatal("invalid overlay accepted") } if doc.Config.Agent.Mode != "inprocess" { diff --git a/internal/infrastructure/configuration/loader.go b/internal/infrastructure/configuration/loader.go index 73cb71a01..93d2e80fe 100644 --- a/internal/infrastructure/configuration/loader.go +++ b/internal/infrastructure/configuration/loader.go @@ -114,22 +114,27 @@ func (l *Loader) Overlay(basePath, overlayPath string) (*Document, error) { } // ApplyOverlay decodes the runtime config overlay (a nested map of -// dotted-path values from the overlay store) into doc with the same -// field-level precedence as a file overlay, records the overlay origin, -// then applies defaults and validates. It is used at boot and on reload -// to layer dashboard-edited overrides over the file config. +// dotted-path values from the overlay store) into a copy of doc with the +// same field-level precedence as a file overlay, records the overlay +// origin, then applies defaults and validates. It is used at boot and on +// reload to layer dashboard-edited overrides over the file config. // -// doc is decoded in place; pass a copy when the base document must -// survive a decode or validation failure (the boot path does). +// ApplyOverlay never mutates its input: the returned Document owns fresh +// copies of the Config and the provenance chain, so a decode or +// validation failure leaves the caller's document (and whatever it was +// published from) exactly as it was. func (l *Loader) ApplyOverlay(doc *Document, overrides map[string]any) (*Document, error) { + next := *doc + next.Config = doc.Config.Clone() + next.Provenance.Origins = append([]Origin(nil), doc.Provenance.Origins...) if len(overrides) == 0 { - return l.finalize(doc) + return l.finalize(&next) } - if err := ApplyOverlayValues(&doc.Config, overrides); err != nil { + if err := ApplyOverlayValues(&next.Config, overrides); err != nil { return nil, err } - doc.Provenance.record(Origin{Path: "config_overlay (runtime)", Role: RoleMain, Layer: LayerOverlay}) - return l.finalize(doc) + next.Provenance.record(Origin{Path: "config_overlay (runtime)", Role: RoleMain, Layer: LayerOverlay}) + return l.finalize(&next) } func (l *Loader) overlayFile(basePath, overlayPath string) (*Document, error) { From 3802ed473d05cce6796010a28be8520b9b8200bc Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 01:41:20 +1000 Subject: [PATCH 10/13] fix(config): preserve nil slices in Clone to avoid spurious reload warnings Clone normalized nil slices to empty non-nil (make([]T, 0)), so after a dashboard PATCH the cloned published config carried [] where the file decodes to nil -- a subsequent SIGHUP reload's diff-and-warn compared old [] against fresh nil and reported 'Repos changed; requires a restart' for a field that had not changed at all. The exact warning fatigue the allowlist exists to prevent. cloneRepos/cloneIdentities/ cloneMCPServers/cloneStringSlices now return nil for nil input (the append-based copies already preserved nilness). --- internal/config/config.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/internal/config/config.go b/internal/config/config.go index 8f59d3ca9..fb68c525f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -518,6 +518,9 @@ func (c Config) Clone() Config { } func cloneRepos(repos []Repo) []Repo { + if repos == nil { + return nil + } out := make([]Repo, len(repos)) for i, r := range repos { r.Gate = cloneStringSlices(r.Gate) @@ -529,6 +532,9 @@ func cloneRepos(repos []Repo) []Repo { } func cloneIdentities(ids []IdentityConfig) []IdentityConfig { + if ids == nil { + return nil + } out := make([]IdentityConfig, len(ids)) for i, id := range ids { id.Models = cloneStringMap(id.Models) @@ -541,6 +547,9 @@ func cloneIdentities(ids []IdentityConfig) []IdentityConfig { } func cloneMCPServers(servers []MCPServer) []MCPServer { + if servers == nil { + return nil + } out := make([]MCPServer, len(servers)) for i, s := range servers { s.Args = append([]string(nil), s.Args...) @@ -551,6 +560,9 @@ func cloneMCPServers(servers []MCPServer) []MCPServer { } func cloneStringSlices(ss [][]string) [][]string { + if ss == nil { + return nil + } out := make([][]string, len(ss)) for i, s := range ss { out[i] = append([]string(nil), s...) From 5343c68160b49a06e07c7dc8c3447ee2fac78e75 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 01:45:44 +1000 Subject: [PATCH 11/13] docs(architecture): record the implemented config reload and runtime overlay Per the sequencing call (adversarial pass first, docs last), the docs now reflect the design the reviews confirmed. configuration.md: - Mutation ledger gains rows for SIGHUP reload, dashboard PATCH, dashboard reset, and the runtime overlay store, each mapping to the universal change protocol with what is and is not yet implemented. - New section 'Implemented runtime reload and config overlay (2026-08)': the Holder published-snapshot model, the reloadable-field criterion (a field is reloadable when EVERY consumer re-reads it), SIGHUP reload semantics, the overlay store (separate -config.sqlite, dotted keys, denylist, bootstrap degrade), and the PATCH/reset paths. safe-change-and-recovery.md: - New section 'Runtime config overlay: degrade paths and recovery' tabulating the three boot degrade paths and the reload degrade, all verified by the adversarial passes, plus the three documented recoveries (--no-config-overlay flag, rm the overlay file, dashboard reset). Status line notes the overlay subset is implemented while the full runtime-supervision protocol remains under design. No new documents, per the constraint. --- docs/architecture/configuration.md | 79 +++++++++++++++++++ docs/architecture/safe-change-and-recovery.md | 35 ++++++++ 2 files changed, 114 insertions(+) diff --git a/docs/architecture/configuration.md b/docs/architecture/configuration.md index b5384dfc3..cd34e43cc 100644 --- a/docs/architecture/configuration.md +++ b/docs/architecture/configuration.md @@ -244,6 +244,10 @@ The application currently changes behavioural values through unrelated paths: | Persona selection | `PersonaRegistry.SetActive` mutates an in-memory per-session choice. | Agent-system session state. Persistence and audit requirements are owned by that domain, not the configuration loader. | | Memory provider `SaveConfig` | Accepts an untyped map, delegates validation/persistence to an optional provider interface, then providers reload backing files. | A typed provider-owned configuration command using candidate validation, versioning, atomic promotion, health observation, audit, and rollback. | | File and environment overlays | Applied while loading `internal/config`; defaults are filled by mutation in `finalize`. | Configuration-infrastructure input processing that produces separately typed candidates. Defaults and derivations remain visible in provenance. | +| SIGHUP config reload (2026-08) | Re-resolves the file config (+ the runtime overlay), validates, then atomically republishes through `config.Holder`. A failed reload keeps the running config and records `last_error`/`last_error_at` in `/api/config`. | Candidate promotion with last-known-good retention: the running snapshot is untouched on failure. A bounded observation period and actor audit are not yet implemented. | +| Dashboard PATCH `/api/config` (2026-08) | Applies dotted-key updates to a deep copy of the published config, validates the materialised result, persists to the runtime overlay, then republishes. Denylisted keys (`db_path`, `work_dir`) return 400; a rejected candidate never reaches `Set`. | The universal change protocol's validate-stage-promote path with the overlay store as persistence. Actor is recorded as `dashboard`; no per-field health observation or versioned audit trail yet. | +| Dashboard reset `POST /api/config/reset` (2026-08) | Deletes one overlay row after resolving and validating the target state, then republishes file + remaining overlay, so a dashboard-created override can be removed without editing SQL. | Remediation/rollback: the last-known-good (file) value is restored for that key. | +| Runtime config overlay store (2026-08) | Dashboard-edited overrides in `cfg.DBPath + "-config.sqlite"` (own `user_version`, own migrator), layered over the file config at boot and on every reload. A broken overlay degrades to file config alone, surfaced via `ReloadStatus.OverlayUnavailable`. | External configuration storage for runtime-tunable values, separate from the task/conversation stores so each file owns its migration. The `--no-config-overlay` / `ARCHIE_SKIP_CONFIG_OVERLAY=1` recovery hatch skips it entirely. | Any further mutation seam discovered during migration MUST be added here before it is changed. Direct field assignment on a live settings object is prohibited. @@ -274,6 +278,81 @@ Settings that cannot safely reload in-process are marked restart-required. The change may still be validated and versioned immediately, but promotion occurs through a controlled restart with the same health and rollback semantics. +## Implemented runtime reload and config overlay (2026-08) + +A first implementation of the universal change protocol now exists for the +runtime-tunable surface: SIGHUP reload, the dashboard PATCH, and the runtime +config overlay. The mechanics below are the current implementation; the +aspirational protocol (bounded observation, versioned audit trail, per-actor +audit) remains future work. + +### Published snapshot: `config.Holder` + +The running configuration is a published snapshot held in `config.Holder` +(`internal/config/holder.go`). Get returns a value under RLock; Set replaces the +whole snapshot. A published Config is immutable: reload constructs a fresh one +and calls Set. `config.Clone` deep-copies every reference-type field so a failed +decode cannot mutate the published snapshot's shared maps. `Holder.Get` panics +on a nil receiver — a forgotten `NewHolder` must fail loudly, not boot a daemon +that silently runs on an empty config. + +### The reloadable-field criterion + +The diff-and-warn on reload asks whether a changed field takes effect without a +restart. The criterion is: **a field is reloadable when every consumer re-reads +it.** That question read as "what does the daemon re-read" while the daemon owned +the only Holder; it stopped being sufficient when webui began sharing that +Holder, because webui handlers re-read on every request. The allowlist lives in +`cmd/archied/reload.go` and is deliberately a deny-by-default list: a field added +to Config later defaults to requires-restart, forcing whoever adds it to decide +deliberately. A reload that changes any non-allowlisted field logs +"requires a restart" with the field names; a fully-applied reload logs Info. + +### SIGHUP reload + +SIGHUP re-resolves the file config (plus the runtime overlay), validates, and +atomically republishes through the shared Holder. A failed reload — bad file, +bad overlay — keeps the running config and records `last_error`/`last_error_at` +in `/api/config` so the stale state is visible where the operator is looking. +The three poll tickers re-read `PollInterval` per iteration and reset on change, +so a reloaded interval genuinely takes effect. + +### The runtime config overlay + +The dashboard's edits persist to a dedicated SQLite file +(`cfg.DBPath + "-config.sqlite"`, its own `user_version` and migrator — no +contention with the task or conversation stores). The `config_overlay` table +stores dotted-path keys with JSON-encoded values; the daemon layers them over +the file config at boot and on every reload, with the same field-level +precedence as a file overlay. + +- **Denylist:** `db_path` and `work_dir` cannot be set (the daemon must read them + before it can open the overlay store; changing them could break the next + boot). Enforced at write time with a 400 and in the store. +- **Bootstrap degrade:** a broken overlay (unopenable store, unreadable value, + values failing validation) degrades to file config alone — it must not brick +the daemon. The reason is surfaced via `ReloadStatus.OverlayUnavailable` in +`/api/config` and rendered as a banner by the dashboard. +- **Recovery hatch:** `--no-config-overlay` / `ARCHIE_SKIP_CONFIG_OVERLAY=1` + skips the overlay entirely; removing the `-config.sqlite` file is the +documented manual recovery. See safe-change-and-recovery.md. +- **Shadowed file edits are visible:** `/api/config` reports which dotted keys +the overlay currently sets (`overridden`), so the dashboard marks those rows and +offers a per-row reset. + +### Dashboard PATCH and reset + +`PATCH /api/config` receives `{"updates": {"dotted.key": value}}`. It applies the +updates to a deep copy of the published config, validates the materialised +result, persists to the overlay, then republishes — it never calls Set directly +from the handler, since the dashboard shares the daemon's Holder. Dotted keys +are nested before decode (yaml cannot decode a dotted key as a struct field). +Error classification: 400 for a denylisted key or failed validation, 503 when +the overlay is disabled, 500 for a persistence failure. `POST /api/config/reset` +deletes one overlay row after resolving and validating the target state, +restoring the file value — the answer to "my file edit isn't taking effect +because an override shadows it". + ## Completion criteria The configuration rearchitecture is complete only when: diff --git a/docs/architecture/safe-change-and-recovery.md b/docs/architecture/safe-change-and-recovery.md index 38f3320f8..718310dc8 100644 --- a/docs/architecture/safe-change-and-recovery.md +++ b/docs/architecture/safe-change-and-recovery.md @@ -100,6 +100,41 @@ capabilities continue operating. Remediation MUST be bounded, observable, and policy-driven. Recovery MUST NOT silently oscillate between versions or retry forever. +## Runtime config overlay: degrade paths and recovery (2026-08) + +The dashboard edits runtime-tunable settings into a dedicated overlay store +(`cfg.DBPath + "-config.sqlite"`), layered over the file config at boot and on +reload. The file remains the authoritative, editor-reachable source; the overlay +is a runtime-tunable overlay on top of it. A broken overlay must never brick +the daemon, for the same reason a bad file edit must not: the operator needs a +path back that does not depend on the daemon's health. + +### Degrade paths (all verified by the reload design) + +| Failure | Boot behaviour | Where the operator sees it | +| --- | --- | --- | +| Overlay store cannot be opened (permissions, corrupt file) | Boots on file config alone; logs at error level | `/api/config` → `reload.overlay_unavailable` → dashboard banner | +| Overlay snapshot unreadable (a row holds invalid JSON) | Boots on file config alone | Same | +| Overlay values fail validation | Boots on file config alone; the overlay is rejected wholesale, never partially applied | Same | +| SIGHUP reload with a bad file or bad overlay | Running config is kept; the reload records `last_error` / `last_error_at` | `/api/config` → `reload.last_error` → dashboard banner | + +The overlay degrade paths never partially apply: `Loader.ApplyOverlay` decodes +into a deep copy (`config.Clone`) and validates before anything is published, +so a rejected overlay leaves the boot config exactly as the file produced it. + +### Recovery + +1. **`--no-config-overlay`** (or `ARCHIE_SKIP_CONFIG_OVERLAY=1`) boots the +daemon on file config alone, ignoring the overlay entirely. This is the escape +hatch that works when the daemon will not start. +2. **Remove the overlay file** (`rm -config.sqlite`) — the overlay is +recreated empty on next boot, so the daemon returns to pure file config. +3. **Dashboard reset** (`POST /api/config/reset`) removes a single override +whose file edit is shadowed, without stopping the daemon. + +These are the documented recovery paths; they are deliberate, bounded, and do +not require hand-editing SQL in a shared database. + ## Gateway restart: two constraints learned the hard way Telegram `/restart` (`internal/channels/telegram/restart.go` plus the `Start` From 99fb1102ccb70253ccb1fa50e81acff49992eabf Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 10 Aug 2026 01:46:18 +1000 Subject: [PATCH 12/13] docs(architecture): mark the config-overlay subset implemented on safe-change-and-recovery --- docs/architecture/safe-change-and-recovery.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture/safe-change-and-recovery.md b/docs/architecture/safe-change-and-recovery.md index 718310dc8..519bf8fc6 100644 --- a/docs/architecture/safe-change-and-recovery.md +++ b/docs/architecture/safe-change-and-recovery.md @@ -1,6 +1,6 @@ # Safe Change and Recovery -**Status:** Requirements approved; mechanics are under design +**Status:** Requirements approved; mechanics are under design. The runtime config overlay subset is implemented (2026-08): see the degrade/recovery section below. The full runtime-supervision protocol (bounded observation, versioned audit trail) remains under design. **Date:** 2026-07-28 **Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73) From c06dd9c6687ed475d029e1d3282544972fd3aab0 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 9 Aug 2026 23:18:55 +1000 Subject: [PATCH 13/13] fix(gateway): harden session recovery paths Repair future-dated conversation history on SQLite open and cap newly supplied timestamps so one bad platform clock cannot pin a session indefinitely. Make message and turn identifiers injective while preserving legacy redelivery and crash-recovery compatibility, retire idle turn lanes safely, and pin the existing compression and partial-undo behavior with focused regressions. --- internal/gateway/redelivery_test.go | 20 ++ internal/gateway/session_commands_test.go | 30 +++ internal/gateway/session_store.go | 39 +++- internal/gateway/session_store_sqlite.go | 71 +++++- internal/gateway/session_store_sqlite_test.go | 213 ++++++++++++++++++ internal/gateway/turn.go | 27 ++- internal/gateway/turn_ledger.go | 11 + internal/gateway/turn_ledger_test.go | 81 ++++++- internal/gateway/turns.go | 53 +++-- internal/gateway/turns_internal_test.go | 52 +++++ 10 files changed, 570 insertions(+), 27 deletions(-) create mode 100644 internal/gateway/turns_internal_test.go diff --git a/internal/gateway/redelivery_test.go b/internal/gateway/redelivery_test.go index 0bec633e9..662713477 100644 --- a/internal/gateway/redelivery_test.go +++ b/internal/gateway/redelivery_test.go @@ -3,8 +3,28 @@ package gateway import ( "testing" "time" + + "github.com/google/uuid" ) +func TestPriorReplyRecognisesLegacyCanonicalMessageID(t *testing.T) { + t.Parallel() + + const ( + sessionID = "a\x00b" + sourceID = "source" + identity = "archie" + ) + legacyID := uuid.NewSHA1(messageIDNamespace, []byte(sessionID+"\x00"+sourceID)).String() + history := []Message{ + {MessageID: legacyID, SourceID: sourceID, From: "alice", Text: "question"}, + {From: identity, Text: "answer"}, + } + if got := PriorReply(history, sessionID, sourceID, identity); got != "answer" { + t.Fatalf("PriorReply = %q, want legacy reply", got) + } +} + // Making the store idempotent only stopped the duplicate *record*. The chat // path saved the inbound message, ignored the fact that nothing changed, and // went on to call the model again -- a second billed turn, any tool side diff --git a/internal/gateway/session_commands_test.go b/internal/gateway/session_commands_test.go index 91e691b2b..bc8ba4e19 100644 --- a/internal/gateway/session_commands_test.go +++ b/internal/gateway/session_commands_test.go @@ -462,6 +462,36 @@ func TestRouteUndoRemovesMultiple(t *testing.T) { } } +func TestRouteUndoReportsActualPartialRemoval(t *testing.T) { + r := newTestRouter("telegram") + ctx := t.Context() + const sessionID = "test-undo-partial" + sc := SessionContext{ + SessionID: sessionID, + Source: SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "chat-partial"}, + CreatedAt: time.Now(), LastActiveAt: time.Now(), + } + if err := r.sessionTracker.sessions.Save(ctx, sc); err != nil { + t.Fatalf("Save session: %v", err) + } + for i := range 6 { + if err := r.sessionTracker.sessions.SaveMessage(ctx, sessionID, Message{ + From: "alice", Text: fmt.Sprintf("msg%d", i), + }); err != nil { + t.Fatalf("SaveMessage(%d): %v", i, err) + } + } + r.sessionTracker.setActive("chat-partial", "", sessionID) + + reply, err := r.Route(ctx, Message{Text: "/undo 10", ChannelID: "chat-partial"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Removed 6 messages") { + t.Fatalf("reply = %q, want actual removal count", reply) + } +} + func TestRouteUndoNoMessages(t *testing.T) { r := newTestRouter("telegram") diff --git a/internal/gateway/session_store.go b/internal/gateway/session_store.go index 77bf8dec5..791ab5b92 100644 --- a/internal/gateway/session_store.go +++ b/internal/gateway/session_store.go @@ -2,6 +2,7 @@ package gateway import ( "context" + "encoding/binary" "strings" "time" @@ -101,16 +102,42 @@ func sessionRecency(sc SessionContext) time.Time { // messageIDNamespace scopes deterministic canonical message identifiers. var messageIDNamespace = uuid.MustParse("6f8d2b1e-9c4a-4f37-8a56-1d0e7b3c9a42") +// messageIDNamespaceV2 isolates the injective encoding used for inputs that +// contain the legacy separator. Ordinary platform/session IDs keep their +// existing canonical IDs, so an upgrade cannot duplicate redelivered messages. +var messageIDNamespaceV2 = uuid.MustParse("e6ac7868-cf49-4e65-a5a1-a1549fd12f67") + func newMessageID(sessionID, sourceID string) string { if sourceID == "" { return uuid.NewString() } - return uuid.NewSHA1(messageIDNamespace, []byte(sessionID+"\x00"+sourceID)).String() + current, _ := canonicalMessageIDs(sessionID, sourceID) + return current +} + +func canonicalMessageIDs(sessionID, sourceID string) (current, legacy string) { + legacy = uuid.NewSHA1(messageIDNamespace, []byte(sessionID+"\x00"+sourceID)).String() + if strings.ContainsRune(sessionID, '\x00') || strings.ContainsRune(sourceID, '\x00') { + return uuid.NewSHA1(messageIDNamespaceV2, encodeCanonicalPair(sessionID, sourceID)).String(), legacy + } + return legacy, "" +} + +func encodeCanonicalPair(first, second string) []byte { + encoded := make([]byte, 8+len(first)+len(second)) + binary.BigEndian.PutUint64(encoded, uint64(len(first))) + copy(encoded[8:], first) + copy(encoded[8+len(first):], second) + return encoded } func stamp(msg Message) time.Time { - if msg.At.IsZero() { - return time.Now().UTC() + now := time.Now().UTC() + if msg.At.IsZero() || msg.At.After(now) { + // At orders the canonical conversation; it is not an authoritative + // copy of a platform clock. Persisting a future platform timestamp + // would force every later message beyond it to preserve monotonicity. + return now } return msg.At.UTC() } @@ -125,12 +152,12 @@ func CanonicalMessageID(sessionID, sourceID string) string { // PriorReply returns the reply already produced for an upstream message. func PriorReply(history []Message, sessionID, sourceID, identity string) string { - id := CanonicalMessageID(sessionID, sourceID) - if id == "" { + if sourceID == "" { return "" } + id, legacyID := canonicalMessageIDs(sessionID, sourceID) for i, message := range history { - if message.MessageID != id { + if message.MessageID != id && message.MessageID != legacyID { continue } if i+1 < len(history) && history[i+1].From == identity && diff --git a/internal/gateway/session_store_sqlite.go b/internal/gateway/session_store_sqlite.go index df54ca9b5..e75fafe29 100644 --- a/internal/gateway/session_store_sqlite.go +++ b/internal/gateway/session_store_sqlite.go @@ -151,9 +151,43 @@ func openSQLiteSessionStore(dsn string) (SessionStore, error) { if _, err := db.ExecContext(ctx, sqliteSessionSchema); err != nil { return nil, errors.Join(fmt.Errorf("sessionstore: init schema: %w", err), db.Close()) } + if err := repairFutureMessageTimestamps(ctx, db, time.Now().UTC()); err != nil { + return nil, errors.Join(err, db.Close()) + } return &sqliteSessionStore{db: db}, nil } +// repairFutureMessageTimestamps heals sessions poisoned by older versions +// that accepted a platform timestamp arbitrarily far ahead of the daemon's +// clock. Future rows retain their order and are rebased immediately after the +// session's last non-future row. With no earlier row, they end at now. A dense +// history can finish a few milliseconds beyond now, but never preserves the +// original hours- or days-long skew. +func repairFutureMessageTimestamps(ctx context.Context, db *sql.DB, now time.Time) error { + cutoff := now.UnixMilli() + _, err := db.ExecContext(ctx, ` + WITH future AS MATERIALIZED ( + SELECT m.id, + COALESCE( + (SELECT MAX(p.ts) FROM messages p + WHERE p.session_id = m.session_id AND p.ts <= ?), + ? - COUNT(*) OVER (PARTITION BY m.session_id) + ) + ROW_NUMBER() OVER ( + PARTITION BY m.session_id ORDER BY m.ts, m.id + ) AS repaired_ts + FROM messages m + WHERE m.ts > ? + ) + UPDATE messages + SET ts = (SELECT repaired_ts FROM future WHERE future.id = messages.id) + WHERE id IN (SELECT id FROM future) AND ts > ?`, + cutoff, cutoff, cutoff, cutoff) + if err != nil { + return fmt.Errorf("sessionstore: repair future message timestamps: %w", err) + } + return nil +} + func (s *sqliteSessionStore) Close() error { return s.db.Close() } @@ -579,8 +613,34 @@ func saveMessage(ctx context.Context, ex execer, sessionID string, msg Message) // placing records deliberately. func saveMessageAt(ctx context.Context, ex execer, sessionID string, msg Message, clamp bool) (string, error) { id := msg.MessageID - if id == "" { - id = newMessageID(sessionID, msg.SourceID) + legacyID := "" + if msg.SourceID == "" { + if id == "" { + id = newMessageID(sessionID, "") + } + } else { + currentID, compatibleLegacyID := canonicalMessageIDs(sessionID, msg.SourceID) + if id == "" { + id = currentID + } + // TurnRunner supplies the current canonical ID before calling the + // store. Still check the compatible legacy identity: a crash can + // leave the old message durable before its turn record names it. + if id == currentID { + legacyID = compatibleLegacyID + } + } + if legacyID != "" { + var existingID string + err := ex.QueryRowContext(ctx, + `SELECT message_id FROM messages WHERE session_id = ? AND message_id = ?`, + sessionID, legacyID).Scan(&existingID) + switch { + case err == nil: + return existingID, nil + case !errors.Is(err, sql.ErrNoRows): + return "", fmt.Errorf("sessionstore: read legacy message identity: %w", err) + } } at := stamp(msg) if clamp { @@ -710,10 +770,13 @@ func (s *sqliteSessionStore) FindPriorReply(ctx context.Context, sessionID, sour s.mu.Lock() defer s.mu.Unlock() + currentID, legacyID := canonicalMessageIDs(sessionID, sourceID) var ts int64 err := s.db.QueryRowContext(ctx, ` - SELECT ts FROM messages WHERE session_id = ? AND message_id = ?`, - sessionID, CanonicalMessageID(sessionID, sourceID)).Scan(&ts) + SELECT ts FROM messages + WHERE session_id = ? AND message_id IN (?, ?) + ORDER BY CASE WHEN message_id = ? THEN 0 ELSE 1 END + LIMIT 1`, sessionID, currentID, legacyID, legacyID).Scan(&ts) if errors.Is(err, sql.ErrNoRows) { return "", nil } diff --git a/internal/gateway/session_store_sqlite_test.go b/internal/gateway/session_store_sqlite_test.go index ac9266e44..68d4ef31d 100644 --- a/internal/gateway/session_store_sqlite_test.go +++ b/internal/gateway/session_store_sqlite_test.go @@ -9,6 +9,8 @@ import ( "sync" "testing" "time" + + "github.com/google/uuid" ) func newTestSQLiteStore(t *testing.T) SessionStore { @@ -93,6 +95,217 @@ func TestMessageIDsAreUnique(t *testing.T) { } } +func TestCanonicalMessageIDComponentsAreInjectivelyEncoded(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + firstSession string + firstSource string + secondSession string + secondSource string + }{ + { + name: "separator can occur in session", + firstSession: "a\x00b", + firstSource: "c", + secondSession: "a", + secondSource: "b\x00c", + }, + { + name: "empty session does not alias prefixed source", + firstSession: "", + firstSource: "a\x00b", + secondSession: "\x00a", + secondSource: "b", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + first := CanonicalMessageID(tc.firstSession, tc.firstSource) + second := CanonicalMessageID(tc.secondSession, tc.secondSource) + if first == second { + t.Fatalf("CanonicalMessageID(%q, %q) = CanonicalMessageID(%q, %q) = %q", + tc.firstSession, tc.firstSource, tc.secondSession, tc.secondSource, first) + } + }) + } +} + +func TestSQLiteSessionStoreRecognisesLegacyCanonicalIDOnRedelivery(t *testing.T) { + t.Parallel() + + store := newTestSQLiteStore(t) + ctx := t.Context() + const ( + sessionID = "a\x00b" + sourceID = "source" + ) + legacyID := uuid.NewSHA1(messageIDNamespace, []byte(sessionID+"\x00"+sourceID)).String() + if _, err := sqliteStoreDB(t, store).ExecContext(ctx, ` + INSERT INTO messages (message_id, session_id, source_id, sender, text, ts) + VALUES (?, ?, ?, 'alice', 'original', ?)`, + legacyID, sessionID, sourceID, time.Now().Add(-time.Minute).UnixMilli()); err != nil { + t.Fatalf("seed legacy message: %v", err) + } + + if err := store.SaveMessage(ctx, sessionID, Message{ + MessageID: CanonicalMessageID(sessionID, sourceID), + SourceID: sourceID, From: "alice", Text: "redelivered", + }); err != nil { + t.Fatalf("SaveMessage(redelivery): %v", err) + } + messages, err := store.RecentMessages(ctx, sessionID, 10) + if err != nil { + t.Fatalf("RecentMessages: %v", err) + } + if len(messages) != 1 { + t.Fatalf("redelivery produced %d messages, want 1", len(messages)) + } + if messages[0].MessageID != legacyID || messages[0].Text != "original" { + t.Fatalf("legacy message changed on redelivery: %#v", messages[0]) + } +} + +func TestSQLiteSessionStoreFindPriorReplyRecognisesLegacyCanonicalID(t *testing.T) { + t.Parallel() + + store := newTestSQLiteStore(t) + ctx := t.Context() + const ( + sessionID = "a\x00b" + sourceID = "source" + identity = "archie" + ) + legacyID := uuid.NewSHA1(messageIDNamespace, []byte(sessionID+"\x00"+sourceID)).String() + inputAt := time.Now().Add(-time.Minute).UnixMilli() + statements := []struct { + id string + source string + sender string + text string + at int64 + }{ + {id: legacyID, source: sourceID, sender: "alice", text: "question", at: inputAt}, + {id: "reply", sender: identity, text: "answer", at: inputAt + 1}, + } + for _, row := range statements { + if _, err := sqliteStoreDB(t, store).ExecContext(ctx, ` + INSERT INTO messages (message_id, session_id, source_id, sender, text, ts) + VALUES (?, ?, ?, ?, ?, ?)`, + row.id, sessionID, row.source, row.sender, row.text, row.at); err != nil { + t.Fatalf("seed %s: %v", row.id, err) + } + } + + replayStore, ok := store.(TurnReplayStore) + if !ok { + t.Fatalf("store is %T, want TurnReplayStore", store) + } + got, err := replayStore.FindPriorReply(ctx, sessionID, sourceID, identity) + if err != nil { + t.Fatalf("FindPriorReply: %v", err) + } + if got != "answer" { + t.Fatalf("FindPriorReply = %q, want legacy reply", got) + } +} + +func TestSQLiteSessionStoreCapsFutureMessageTimestamp(t *testing.T) { + t.Parallel() + + store := newTestSQLiteStore(t) + ctx := t.Context() + now := time.Now().UTC() + if err := store.SaveMessage(ctx, "sess", Message{ + From: "alice", Text: "future", At: now.Add(24 * time.Hour), + }); err != nil { + t.Fatalf("SaveMessage(future): %v", err) + } + if err := store.SaveMessage(ctx, "sess", Message{ + From: "alice", Text: "current", At: now, + }); err != nil { + t.Fatalf("SaveMessage(current): %v", err) + } + + messages, err := store.RecentMessages(ctx, "sess", 10) + if err != nil { + t.Fatalf("RecentMessages: %v", err) + } + if len(messages) != 2 { + t.Fatalf("RecentMessages returned %d messages, want 2", len(messages)) + } + if messages[0].At.After(time.Now().UTC().Add(time.Minute)) { + t.Fatalf("future timestamp was persisted as %s", messages[0].At) + } + if !messages[1].At.After(messages[0].At) { + t.Fatalf("current message timestamp %s does not follow capped future timestamp %s", + messages[1].At, messages[0].At) + } +} + +func TestSQLiteSessionStoreRepairsPersistedFutureTimestampsOnReopen(t *testing.T) { + t.Parallel() + + ctx := t.Context() + path := filepath.Join(t.TempDir(), "future.db") + store, err := OpenSQLiteSessionStore(path) + if err != nil { + t.Fatalf("OpenSQLiteSessionStore: %v", err) + } + now := time.Now().UTC() + rows := []struct { + id string + text string + at time.Time + }{ + {id: "past", text: "past", at: now.Add(-time.Minute)}, + {id: "future-1", text: "future-1", at: now.Add(24 * time.Hour)}, + {id: "future-2", text: "future-2", at: now.Add(25 * time.Hour)}, + } + for _, row := range rows { + if _, err := sqliteStoreDB(t, store).ExecContext(ctx, ` + INSERT INTO messages (message_id, session_id, sender, text, ts) + VALUES (?, 'sess', 'alice', ?, ?)`, row.id, row.text, row.at.UnixMilli()); err != nil { + t.Fatalf("seed %s: %v", row.id, err) + } + } + if err := store.Close(); err != nil { + t.Fatalf("Close seeded store: %v", err) + } + + reopened, err := OpenSQLiteSessionStore(path) + if err != nil { + t.Fatalf("reopen store: %v", err) + } + t.Cleanup(func() { _ = reopened.Close() }) + if err := reopened.SaveMessage(ctx, "sess", Message{ + From: "alice", Text: "current", At: time.Now().UTC(), + }); err != nil { + t.Fatalf("SaveMessage(current): %v", err) + } + + messages, err := reopened.RecentMessages(ctx, "sess", 10) + if err != nil { + t.Fatalf("RecentMessages: %v", err) + } + want := []string{"past", "future-1", "future-2", "current"} + if got := texts(messages); !equal(got, want) { + t.Fatalf("history = %v, want %v", got, want) + } + for i := 1; i < len(messages); i++ { + if !messages[i].At.After(messages[i-1].At) { + t.Fatalf("timestamp %d (%s) does not follow %d (%s)", + i, messages[i].At, i-1, messages[i-1].At) + } + } + if messages[len(messages)-1].At.After(time.Now().UTC().Add(time.Second)) { + t.Fatalf("repaired history remains pinned in the future: last timestamp %s", + messages[len(messages)-1].At) + } +} + func TestSQLiteMessageTimestampRoundTrips(t *testing.T) { st := newTestSQLiteStore(t) want := sqliteBase().Add(90*time.Minute + 123*time.Millisecond) diff --git a/internal/gateway/turn.go b/internal/gateway/turn.go index 3e508de5b..0b026ff19 100644 --- a/internal/gateway/turn.go +++ b/internal/gateway/turn.go @@ -146,7 +146,10 @@ func (r *TurnRunner) Run(ctx context.Context, msg Message, onDelta func(string)) if err != nil { return "", fmt.Errorf("resolve chat session: %w", err) } - turnID := CanonicalTurnID(sessionID, msg.SourceID) + turnID, err := r.canonicalTurnID(ctx, sessionID, msg.SourceID) + if err != nil { + return "", fmt.Errorf("resolve canonical turn ID: %w", err) + } if turnID == "" { turnID = NewTurnID() } @@ -303,6 +306,28 @@ func (r *TurnRunner) Run(ctx context.Context, msg Message, onDelta func(string)) return text, nil } +// canonicalTurnID preserves a matching identifier written by the legacy +// separator encoding. A legacy collision belonging to a different +// session/source pair is ignored in favour of the injective identifier. +func (r *TurnRunner) canonicalTurnID(ctx context.Context, sessionID, sourceID string) (string, error) { + current := CanonicalTurnID(sessionID, sourceID) + if current == "" { + return "", nil + } + legacy := legacyCanonicalTurnID(sessionID, sourceID) + if current == legacy { + return current, nil + } + turn, ok, err := r.Ledger.GetTurn(ctx, legacy) + if err != nil { + return "", err + } + if ok && turn.SessionID == sessionID && turn.SourceID == sourceID { + return legacy, nil + } + return current, nil +} + func (r *TurnRunner) failTurn(ctx context.Context, turn TurnRecord, cause error) error { if errors.Is(cause, context.Canceled) { turn.Status = TurnStatusCancelled diff --git a/internal/gateway/turn_ledger.go b/internal/gateway/turn_ledger.go index efe281278..04ccfef68 100644 --- a/internal/gateway/turn_ledger.go +++ b/internal/gateway/turn_ledger.go @@ -3,6 +3,7 @@ package gateway import ( "context" "errors" + "strings" "time" "github.com/google/uuid" @@ -80,9 +81,19 @@ func assistantMessageIDForTurn(turnID string) string { return uuid.NewSHA1(uuid.NameSpaceURL, []byte("archie-assistant-turn:\x00"+turnID)).String() } +var turnIDNamespaceV2 = uuid.MustParse("59ca315e-3b2d-4a2f-bd46-93e0ebf30788") + func CanonicalTurnID(sessionID, sourceID string) string { if sourceID == "" { return "" } + legacy := legacyCanonicalTurnID(sessionID, sourceID) + if strings.ContainsRune(sessionID, '\x00') || strings.ContainsRune(sourceID, '\x00') { + return uuid.NewSHA1(turnIDNamespaceV2, encodeCanonicalPair(sessionID, sourceID)).String() + } + return legacy +} + +func legacyCanonicalTurnID(sessionID, sourceID string) string { return uuid.NewSHA1(uuid.NameSpaceURL, []byte("archie-turn:\x00"+sessionID+"\x00"+sourceID)).String() } diff --git a/internal/gateway/turn_ledger_test.go b/internal/gateway/turn_ledger_test.go index 753f3aa62..e997e3d4a 100644 --- a/internal/gateway/turn_ledger_test.go +++ b/internal/gateway/turn_ledger_test.go @@ -203,7 +203,10 @@ func TestSQLiteTurnLedgerSurvivesReopen(t *testing.T) { if err != nil { t.Fatalf("OpenSQLiteSessionStore() error = %v", err) } - ledger := store.(TurnLedger) + ledger, ok := store.(TurnLedger) + if !ok { + t.Fatalf("store is %T, want TurnLedger", store) + } turn := TurnRecord{ TurnID: CanonicalTurnID("session-reopen", "source-reopen"), SessionID: "session-reopen", @@ -253,3 +256,79 @@ func TestCanonicalTurnIDIsStableAndSessionScoped(t *testing.T) { t.Fatalf("empty source ID produced %q, want empty", got) } } + +func TestCanonicalTurnIDComponentsAreInjectivelyEncoded(t *testing.T) { + t.Parallel() + + first := CanonicalTurnID("a\x00b", "c") + second := CanonicalTurnID("a", "b\x00c") + if first == second { + t.Fatalf("ambiguous component pairs shared turn ID %q", first) + } +} + +func TestTurnRunnerCanonicalTurnIDPreservesMatchingLegacyRecord(t *testing.T) { + t.Parallel() + + store := newTestSQLiteStore(t) + ledger, ok := store.(TurnLedger) + if !ok { + t.Fatalf("store is %T, want TurnLedger", store) + } + ctx := t.Context() + const ( + sessionID = "a\x00b" + sourceID = "c" + ) + legacyID := legacyCanonicalTurnID(sessionID, sourceID) + if _, claim, err := ledger.ClaimTurn(ctx, TurnRecord{ + TurnID: legacyID, SessionID: sessionID, SourceID: sourceID, + Status: TurnStatusAccepted, OwnerID: "old-process", + }); err != nil || claim != TurnClaimOwned { + t.Fatalf("seed legacy turn = %q, %v", claim, err) + } + + runner := NewTurnRunner(TurnRunnerConfig{Ledger: ledger}) + got, err := runner.canonicalTurnID(ctx, sessionID, sourceID) + if err != nil { + t.Fatalf("canonicalTurnID: %v", err) + } + if got != legacyID { + t.Fatalf("canonicalTurnID = %q, want matching legacy ID %q", got, legacyID) + } +} + +func TestTurnRunnerCanonicalTurnIDRejectsCollidingLegacyRecord(t *testing.T) { + t.Parallel() + + store := newTestSQLiteStore(t) + ledger, ok := store.(TurnLedger) + if !ok { + t.Fatalf("store is %T, want TurnLedger", store) + } + ctx := t.Context() + const ( + firstSession = "a\x00b" + firstSource = "c" + secondSession = "a" + secondSource = "b\x00c" + ) + collidingLegacyID := legacyCanonicalTurnID(firstSession, firstSource) + if _, claim, err := ledger.ClaimTurn(ctx, TurnRecord{ + TurnID: collidingLegacyID, SessionID: firstSession, SourceID: firstSource, + Status: TurnStatusAccepted, OwnerID: "first-process", + }); err != nil || claim != TurnClaimOwned { + t.Fatalf("seed colliding turn = %q, %v", claim, err) + } + + runner := NewTurnRunner(TurnRunnerConfig{Ledger: ledger}) + got, err := runner.canonicalTurnID(ctx, secondSession, secondSource) + if err != nil { + t.Fatalf("canonicalTurnID: %v", err) + } + want := CanonicalTurnID(secondSession, secondSource) + if got != want || got == collidingLegacyID { + t.Fatalf("canonicalTurnID = %q, want isolated ID %q (legacy collision %q)", + got, want, collidingLegacyID) + } +} diff --git a/internal/gateway/turns.go b/internal/gateway/turns.go index f6f92e233..506ab55ad 100644 --- a/internal/gateway/turns.go +++ b/internal/gateway/turns.go @@ -76,16 +76,14 @@ func NewTurns(log *slog.Logger) *Turns { // // Submit never blocks and never rejects: messages queue. func (t *Turns) Submit(ctx context.Context, session string, run func(context.Context)) { + turnCtx, cancel := context.WithCancel(ctx) + t.mu.Lock() l, ok := t.lanes[session] if !ok { l = &lane{} t.lanes[session] = l } - t.mu.Unlock() - - turnCtx, cancel := context.WithCancel(ctx) - l.mu.Lock() l.pending = append(l.pending, queued{run: func() { run(turnCtx) }, cancel: cancel}) depth := len(l.pending) @@ -94,9 +92,10 @@ func (t *Turns) Submit(ctx context.Context, session string, run func(context.Con l.working = true } l.mu.Unlock() + t.mu.Unlock() if start { - go l.serve(t.log.With("session", session)) + go t.serve(session, l) } if depth > 1 { t.log.Info("chat turn queued", "session", session, "queue_depth", depth) @@ -154,7 +153,8 @@ func (t *Turns) Queued(session string) int { return len(l.pending) } -// lane returns the session's lane, or nil if it has never been used. +// lane returns the session's active lane, or nil if it has never been used or +// its completed lane has already retired. func (t *Turns) lane(session string) *lane { t.mu.Lock() defer t.mu.Unlock() @@ -164,19 +164,45 @@ func (t *Turns) lane(session string) *lane { // serve drains the lane's backlog one turn at a time and exits once it is // empty. Submit starts a fresh worker when more arrives, so an idle session // costs no goroutine. -func (l *lane) serve(log *slog.Logger) { +func (t *Turns) serve(session string, l *lane) { + log := t.log.With("session", session) for { next, ok := l.begin() if !ok { - return + if t.retire(session, l) { + return + } + continue } l.runOne(next, log) } } +// retire removes an idle lane while holding the same two locks Submit uses to +// find and append to it. Without that joint critical section, Submit could find +// the old lane immediately before cleanup deleted it and strand the new turn on +// a worker that had already exited. +func (t *Turns) retire(session string, l *lane) bool { + t.mu.Lock() + defer t.mu.Unlock() + + current, ok := t.lanes[session] + if !ok || current != l { + return true + } + l.mu.Lock() + defer l.mu.Unlock() + if len(l.pending) != 0 { + return false + } + l.working = false + delete(t.lanes, session) + return true +} + // begin pops the oldest queued turn and publishes its cancel in the same -// critical section, reporting false when the backlog is empty -- at which -// point it also retires the worker. +// critical section. It reports false when the backlog is empty; the owning +// Turns then retires the worker and map entry under both locks. // // The pop and the publish must happen together. Were the turn popped first // and its cancel published after, a Stop landing in between would see an @@ -187,11 +213,8 @@ func (l *lane) begin() (queued, bool) { defer l.mu.Unlock() if len(l.pending) == 0 { - // Retire under the same lock Submit uses to decide whether a - // worker is live, so a turn arriving now either starts a new - // worker or is picked up before this one retires -- never - // neither, which would strand the backlog forever. - l.working = false + // The owning Turns retires the lane under both the map and lane + // locks. Changing working here would race a concurrent Submit. return queued{}, false } diff --git a/internal/gateway/turns_internal_test.go b/internal/gateway/turns_internal_test.go new file mode 100644 index 000000000..4f3c73c7a --- /dev/null +++ b/internal/gateway/turns_internal_test.go @@ -0,0 +1,52 @@ +package gateway + +import ( + "context" + "log/slog" + "testing" + "time" +) + +func TestTurnsRetiresIdleSessionLanes(t *testing.T) { + t.Parallel() + + turns := NewTurns(slog.New(slog.DiscardHandler)) + const sessions = 100 + done := make(chan struct{}, sessions) + for i := range sessions { + turns.Submit(context.Background(), string(rune(i)), func(context.Context) { + done <- struct{}{} + }) + } + for range sessions { + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("submitted turn did not finish") + } + } + + deadline := time.Now().Add(2 * time.Second) + for { + turns.mu.Lock() + remaining := len(turns.lanes) + turns.mu.Unlock() + if remaining == 0 { + break + } + if time.Now().After(deadline) { + t.Fatalf("%d idle session lanes remain allocated", remaining) + } + time.Sleep(time.Millisecond) + } + + // A retired session must remain reusable; cleanup cannot strand a turn + // between looking up the old lane and creating its replacement. + reused := make(chan struct{}) + turns.Submit(context.Background(), string(rune(0)), func(context.Context) { close(reused) }) + select { + case <-reused: + case <-time.After(2 * time.Second): + t.Fatal("retired session did not accept a new turn") + } +}