diff --git a/.rhizome/generated-files.yml b/.rhizome/generated-files.yml index 3015d5997..44e1a75e0 100644 --- a/.rhizome/generated-files.yml +++ b/.rhizome/generated-files.yml @@ -136,7 +136,7 @@ written: .rhizome/modules/compounding/scripts/lib/calibration-data.mjs: 50c7ba8e358f3780 .rhizome/modules/compounding/scripts/lib/calibration-models.mjs: 040bd397ef1cbe0c .rhizome/modules/compounding/scripts/lib/calibration-score.mjs: 56b8330db4ad1099 - .rhizome/modules/compounding/scripts/lib/calls.mjs: e43c954d88f347d7 + .rhizome/modules/compounding/scripts/lib/calls.mjs: fe26bac845d22335 .rhizome/modules/compounding/scripts/lib/episodes.mjs: 192fa78eda45082b .rhizome/modules/compounding/scripts/lib/estimate.mjs: 2a1caa922f7295f2 .rhizome/modules/compounding/scripts/lib/extract.mjs: b7e8d59f161d707b diff --git a/.rhizome/modules/compounding/scripts/lib/calls.mjs b/.rhizome/modules/compounding/scripts/lib/calls.mjs index b40393ac5..6e5a4533b 100755 --- a/.rhizome/modules/compounding/scripts/lib/calls.mjs +++ b/.rhizome/modules/compounding/scripts/lib/calls.mjs @@ -33,8 +33,16 @@ export function costOf(model, usage = {}) { if (!p) return usage.costUsd || null; const read = usage.cachedInputTokens ?? 0; const write = usage.cacheWriteInputTokens ?? 0; - const fresh = inputIncludesReads(model) ? (usage.inputTokens ?? 0) - read : usage.inputTokens ?? 0; - return (fresh * p.input + write * (p.write5m ?? p.input) + read * p.read + (usage.outputTokens ?? 0) * p.output) / 1e6; + const fresh = inputIncludesReads(model) + ? (usage.inputTokens ?? 0) - read + : (usage.inputTokens ?? 0); + return ( + (fresh * p.input + + write * (p.write5m ?? p.input) + + read * p.read + + (usage.outputTokens ?? 0) * p.output) / + 1e6 + ); } // Codex structured output needs strict schemas: every property required and @@ -58,7 +66,16 @@ export function strictSchema(s) { return out; } -export const dropNulls = (v) => (Array.isArray(v) ? v.map(dropNulls) : v && typeof v === "object" ? Object.fromEntries(Object.entries(v).filter(([, x]) => x !== null).map(([k, x]) => [k, dropNulls(x)])) : v); +export const dropNulls = (v) => + Array.isArray(v) + ? v.map(dropNulls) + : v && typeof v === "object" + ? Object.fromEntries( + Object.entries(v) + .filter(([, x]) => x !== null) + .map(([k, x]) => [k, dropNulls(x)]), + ) + : v; const CALL_TIMEOUT_MS = 60 * 60 * 1000; @@ -69,14 +86,27 @@ export function rzmClients(rzm = "rzm", { cwd } = {}) { const child = spawn(rzm, args, { cwd: dir, stdio: ["pipe", "pipe", "pipe"] }); let out = ""; let err = ""; + let inputError; // A hung CLI would hold the run's lock forever. const timer = setTimeout(() => child.kill("SIGKILL"), CALL_TIMEOUT_MS); child.stdout.on("data", (d) => (out += d)); child.stderr.on("data", (d) => (err += d)); child.on("error", fail); + child.stdin.on("error", (error) => { + // The CLI closed its input early: EPIPE on POSIX, EOF on Windows. Its reply still counts. + if (error.code === "EPIPE" || error.code === "EOF") return; + inputError = error; + child.kill("SIGKILL"); + }); child.on("close", (code) => { clearTimeout(timer); - done({ code, out, err: code === null ? `timed out after ${CALL_TIMEOUT_MS / 60000} minutes` : err }); + // A CLI may reply before input drains; keep its final status and diagnostic. + if (inputError) return fail(inputError); + done({ + code, + out, + err: code === null ? `timed out after ${CALL_TIMEOUT_MS / 60000} minutes` : err, + }); }); child.stdin.end(input); }); @@ -86,12 +116,19 @@ export function rzmClients(rzm = "rzm", { cwd } = {}) { try { detail = JSON.parse(detail.split("\n").pop()).error ?? detail; } catch {} - throw new Error(`${what}: ${typeof detail === "string" ? detail.slice(-500) : JSON.stringify(detail).slice(0, 500)}`); + throw new Error( + `${what}: ${typeof detail === "string" ? detail.slice(-500) : JSON.stringify(detail).slice(0, 500)}`, + ); }; return { async generate({ provider, model, effort, prompt, schema }) { const args = ["agent", "generate"]; - for (const [flag, v] of [["--provider", provider], ["--model", model], ["--effort", effort]]) if (v) args.push(flag, v); + for (const [flag, v] of [ + ["--provider", provider], + ["--model", model], + ["--effort", effort], + ]) + if (v) args.push(flag, v); const dir = schema ? mkdtempSync(join(tmpdir(), "sm-schema-")) : null; try { if (dir) { @@ -103,13 +140,17 @@ export function rzmClients(rzm = "rzm", { cwd } = {}) { if (dir) rmSync(dir, { recursive: true, force: true }); } }, - evaluateBatch: async (request) => parse(await run(["agent", "evaluate-batch"], JSON.stringify(request)), "evaluate-batch"), + evaluateBatch: async (request) => + parse(await run(["agent", "evaluate-batch"], JSON.stringify(request)), "evaluate-batch"), harnessStatus: async () => parse(await run(["harness", "status"]), "harness status"), - configuredHarness: async () => (parse(await run(["harness", "status", "--configured"]), "configured harness")).harness, + configuredHarness: async () => + parse(await run(["harness", "status", "--configured"]), "configured harness").harness, // Rhizome search for verification evidence; a failure is evidence too. async search(args, { cwd: dir } = {}) { const r = await run(["search", ...args], "", dir ?? cwd); - return r.code === 0 ? r.out : `(failed: ${(r.err || r.out).trim().split("\n")[0].slice(0, 200)})`; + return r.code === 0 + ? r.out + : `(failed: ${(r.err || r.out).trim().split("\n")[0].slice(0, 200)})`; }, }; } @@ -122,14 +163,25 @@ export class Stop extends Error { } // Cache keys: stage, prompt version, input content, and model binding. -export const callKey = ({ stage, binding: b, prompt, schema }) => sha({ stage, version: PROMPT_VERSION, provider: b.provider, model: b.model, effort: b.effort, prompt, schema }); -export const itemKey = ({ stage, model, item }) => sha({ stage, version: PROMPT_VERSION, model, state: item.state, questions: item.questions }); +export const callKey = ({ stage, binding: b, prompt, schema }) => + sha({ + stage, + version: PROMPT_VERSION, + provider: b.provider, + model: b.model, + effort: b.effort, + prompt, + schema, + }); +export const itemKey = ({ stage, model, item }) => + sha({ stage, version: PROMPT_VERSION, model, state: item.state, questions: item.questions }); // Rebuilds a run's spend from its ledger, so a resumed run counts what the // killed one paid for. export function spendFrom(entries, run) { const spend = { usd: 0, byRole: {} }; - for (const e of entries) if (e.run === run && (e.ok || e.usd)) account(spend, e.role, e.usage, e.usd, e.model); + for (const e of entries) + if (e.run === run && (e.ok || e.usd)) account(spend, e.role, e.usage, e.usd, e.model); return spend; } @@ -137,9 +189,18 @@ const FATAL = /harness (not installed|not logged in|unsupported)/; const JEV_ITEMS = 128; function account(spend, role, usage, usd, model) { - const r = (spend.byRole[role] ??= { calls: 0, cached: 0, inputTokens: 0, outputTokens: 0, usd: 0 }); + const r = (spend.byRole[role] ??= { + calls: 0, + cached: 0, + inputTokens: 0, + outputTokens: 0, + usd: 0, + }); r.calls++; - r.inputTokens += (usage?.inputTokens ?? 0) + (inputIncludesReads(model) ? 0 : usage?.cachedInputTokens ?? 0) + (usage?.cacheWriteInputTokens ?? 0); + r.inputTokens += + (usage?.inputTokens ?? 0) + + (inputIncludesReads(model) ? 0 : (usage?.cachedInputTokens ?? 0)) + + (usage?.cacheWriteInputTokens ?? 0); r.outputTokens += usage?.outputTokens ?? 0; r.usd += usd ?? 0; spend.usd += usd ?? 0; @@ -150,19 +211,30 @@ function account(spend, role, usage, usd, model) { export function makeCaller({ clients, store, run, bindings, budget = null, spend, onResult }) { let reserved = 0; const reserve = (usd) => { - if (budget !== null && spend.usd + reserved + usd > budget) throw new Stop("budget", `budget $${budget} reached ($${spend.usd.toFixed(4)} spent)`); + if (budget !== null && spend.usd + reserved + usd > budget) + throw new Stop("budget", `budget $${budget} reached ($${spend.usd.toFixed(4)} spent)`); reserved += usd; }; // `effort` overrides the binding's for cheap follow-ups such as repairs. - async function generate({ role, stage, prompt, schema, estimate = 0, effort, tally, bypassCache = false }) { + async function generate({ + role, + stage, + prompt, + schema, + estimate = 0, + effort, + tally, + bypassCache = false, + }) { const b = bindings[role]; if (!b) throw new Stop("binding", `no binding for ${role}`); effort ??= b.effort; const key = callKey({ stage, binding: { ...b, effort }, prompt, schema }); const hit = bypassCache ? null : store.cacheGet(key); if (hit) { - (spend.byRole[role] ??= { calls: 0, cached: 0, inputTokens: 0, outputTokens: 0, usd: 0 }).cached++; + (spend.byRole[role] ??= { calls: 0, cached: 0, inputTokens: 0, outputTokens: 0, usd: 0 }) + .cached++; if (tally) tally.cached++; onResult?.({ ...hit, role, cached: true }); return hit.output; @@ -173,24 +245,64 @@ export function makeCaller({ clients, store, run, bindings, budget = null, spend let r; const started = Date.now(); try { - r = await clients.generate({ provider: b.provider, model: b.model, effort, prompt, schema: b.provider === "codex" && schema ? strictSchema(schema) : schema }); + r = await clients.generate({ + provider: b.provider, + model: b.model, + effort, + prompt, + schema: b.provider === "codex" && schema ? strictSchema(schema) : schema, + }); } catch (err) { if (err instanceof Stop) throw err; - store.ledger({ run, stage, role, key, attempt, ok: false, error: String(err.message).slice(0, 500) }); - if (FATAL.test(err.message)) throw new Stop("binding", `${role} binding ${b.provider}:${b.model} is unavailable: ${err.message}`); + store.ledger({ + run, + stage, + role, + key, + attempt, + ok: false, + error: String(err.message).slice(0, 500), + }); + if (FATAL.test(err.message)) + throw new Stop( + "binding", + `${role} binding ${b.provider}:${b.model} is unavailable: ${err.message}`, + ); continue; } // A frozen model that now resolves to another is unavailable, not a substitute. if (r.model && b.model && r.model !== b.model) { const paid = Math.max(costOf(r.model, r.usage) ?? 0, r.usage?.costUsd ?? 0); - store.ledger({ run, stage, role, key, attempt, ok: false, model: r.model, usage: r.usage, usd: paid, error: `model ${r.model} ran instead of ${b.model}` }); + store.ledger({ + run, + stage, + role, + key, + attempt, + ok: false, + model: r.model, + usage: r.usage, + usd: paid, + error: `model ${r.model} ran instead of ${b.model}`, + }); account(spend, role, r.usage, paid, r.model); - throw new Stop("binding", `${role} is frozen to ${b.model} but ${r.model} ran; resume when ${b.model} is available`); + throw new Stop( + "binding", + `${role} is frozen to ${b.model} but ${r.model} ran; resume when ${b.model} is available`, + ); } // Token prices can miss requests a reply needed; Claude's own total covers them. const usd = Math.max(costOf(r.model || b.model, r.usage) ?? 0, r.usage?.costUsd ?? 0); const output = b.provider === "codex" ? dropNulls(r.output) : r.output; - const result = { stage, role, model: r.model || b.model, output, usage: r.usage, usd, ms: Date.now() - started }; + const result = { + stage, + role, + model: r.model || b.model, + output, + usage: r.usage, + usd, + ms: Date.now() - started, + }; store.ledger({ run, key, attempt, ok: true, ...result, output: undefined }); store.cachePut(key, result); account(spend, role, r.usage, usd, r.model || b.model); @@ -216,7 +328,13 @@ export function makeCaller({ clients, store, run, bindings, budget = null, spend if (hit) out.set(item.id, hit.answers); else todo.push({ ...item, key }); } - (spend.byRole.decide ??= { calls: 0, cached: 0, inputTokens: 0, outputTokens: 0, usd: 0 }).cached += items.length - todo.length; + (spend.byRole.decide ??= { + calls: 0, + cached: 0, + inputTokens: 0, + outputTokens: 0, + usd: 0, + }).cached += items.length - todo.length; for (let attempt = 1; attempt <= 2 && todo.some((t) => !out.has(t.id)); attempt++) { const pending = todo.filter((t) => !out.has(t.id)); for (let k = 0; k < pending.length; k += JEV_ITEMS) { @@ -225,16 +343,41 @@ export function makeCaller({ clients, store, run, bindings, budget = null, spend reserve(est); let res; try { - res = await clients.evaluateBatch({ items: chunk.map((t) => ({ id: t.id, model: b.model, state: t.state, questions: t.questions })), concurrency: 8, budgetMs: 60000 }); + res = await clients.evaluateBatch({ + items: chunk.map((t) => ({ + id: t.id, + model: b.model, + state: t.state, + questions: t.questions, + })), + concurrency: 8, + budgetMs: 60000, + }); } catch (err) { - if (/\b40[13]\b|credential|api key|TYPESAFE/i.test(err.message)) throw new Stop("credential", `Jev is unavailable (${err.message.slice(0, 200)}); set up the TypeSafe key and resume, or pass --abandon and start an unscreened run (--unscreened) over a small window`); + if (/\b40[13]\b|credential|api key|TYPESAFE/i.test(err.message)) + throw new Stop( + "credential", + `Jev is unavailable (${err.message.slice(0, 200)}); set up the TypeSafe key and resume, or pass --abandon and start an unscreened run (--unscreened) over a small window`, + ); res = { items: [], error: err.message }; } finally { reserved -= est; } - const usage = { inputTokens: res.usage?.input_tokens ?? 0, outputTokens: res.usage?.output_tokens ?? 0 }; + const usage = { + inputTokens: res.usage?.input_tokens ?? 0, + outputTokens: res.usage?.output_tokens ?? 0, + }; const usd = costOf(b.model, usage); - store.ledger({ run, stage, role: "decide", attempt, ok: true, items: chunk.length, usage, usd }); + store.ledger({ + run, + stage, + role: "decide", + attempt, + ok: true, + items: chunk.length, + usage, + usd, + }); account(spend, "decide", usage, usd); const byId = new Map((res.items ?? []).map((it) => [it.id, it])); for (const t of chunk) { @@ -244,8 +387,21 @@ export function makeCaller({ clients, store, run, bindings, budget = null, spend store.cachePut(t.key, { stage, answers: it.response.answers }); continue; } - store.ledger({ run, stage, role: "decide", key: t.key, attempt, ok: false, status: it?.status ?? "missing", error: String(it?.error ?? res.error ?? "").slice(0, 300) }); - if ([401, 402, 403].includes(it?.statusCode)) throw new Stop("credential", `TypeSafe returned HTTP ${it.statusCode}; set up the TypeSafe key and resume, or pass --abandon and start an unscreened run (--unscreened) over a small window`); + store.ledger({ + run, + stage, + role: "decide", + key: t.key, + attempt, + ok: false, + status: it?.status ?? "missing", + error: String(it?.error ?? res.error ?? "").slice(0, 300), + }); + if ([401, 402, 403].includes(it?.statusCode)) + throw new Stop( + "credential", + `TypeSafe returned HTTP ${it.statusCode}; set up the TypeSafe key and resume, or pass --abandon and start an unscreened run (--unscreened) over a small window`, + ); } } } @@ -261,7 +417,8 @@ function addTally(t, usage, usd, ms) { t.calls++; t.usd += usd ?? 0; t.ms += ms; - for (const [k, v] of Object.entries(usage ?? {})) if (typeof v === "number") t.usage[k] = (t.usage[k] ?? 0) + v; + for (const [k, v] of Object.entries(usage ?? {})) + if (typeof v === "number") t.usage[k] = (t.usage[k] ?? 0) + v; } const SEVERITY = { failed: 1, budget: 2, binding: 3, credential: 3, error: 4 }; @@ -281,7 +438,8 @@ export async function pool(items, n, fn) { await fn(items[k], k); } catch (err) { const reason = err instanceof Stop ? err.reason : "error"; - if (!stop || SEVERITY[reason] > SEVERITY[stop instanceof Stop ? stop.reason : "error"]) stop = err; + if (!stop || SEVERITY[reason] > SEVERITY[stop instanceof Stop ? stop.reason : "error"]) + stop = err; if (reason !== "failed") halted = true; } } diff --git a/CHANGELOG.md b/CHANGELOG.md index ba9d53dc5..8e3726e56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - Refreshed the workbench with clearer tables and boards, calmer note and search pages, consistent type colours, and more readable graph labels. - GraphQL now shares the workbench sidebar and page layout. +- Explorer now shows the whole vault: every note and code file is counted, with large folders aggregated rather than cut off, folders expand in place without the rest of the graph moving, and links between code and notes are drawn. Each status word and each type now keep one mark and one colour everywhere, Action Items show their full titles, and collections, notes and search read more calmly. After updating, each repository refreshes its ontology catalog once to pick up the full titles; nothing is re-embedded. - Authored note-only ontology interfaces now get typed GraphQL roots, so a shared collection such as `meeting` can filter, sort and page across its concrete types while retaining concrete identity. diff --git a/DESIGN.md b/DESIGN.md index d263b5434..210fb848f 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -55,66 +55,16 @@ colors: indigo-chrome: "#3c3d63" white: "#ffffff" typography: - display: - fontFamily: "Merriweather, Georgia, Times New Roman, serif" - fontSize: "24px" - fontWeight: 900 - lineHeight: 1.18 - letterSpacing: "-0.015em" - headline: - fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif" - fontSize: "18px" - fontWeight: 700 - lineHeight: 1.2 - letterSpacing: "-0.01em" - section: - fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif" - fontSize: "18px" - fontWeight: 600 - lineHeight: 1.35 - letterSpacing: "-0.005em" - section-heading: - fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif" - fontSize: "15px" - fontWeight: 600 - lineHeight: 1.35 - letterSpacing: "0" - title: - fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif" - fontSize: "16px" - fontWeight: 600 - lineHeight: 1.25 - letterSpacing: "-0.005em" - prose: - fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif" - fontSize: "15px" - fontWeight: 400 - lineHeight: 1.6 - letterSpacing: "0" - body: - fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif" - fontSize: "14px" - fontWeight: 400 - lineHeight: 1.45 - letterSpacing: "0" - secondary: - fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif" - fontSize: "13px" - fontWeight: 500 - lineHeight: 1.3 - letterSpacing: "0" - label: - fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif" - fontSize: "13px" - fontWeight: 500 - lineHeight: 1.35 - letterSpacing: "0" - mono: - fontFamily: "JetBrains Mono, ui-monospace, Menlo, Consolas, monospace" - fontSize: "12px" - fontWeight: 500 - lineHeight: 1.4 - letterSpacing: "0" + display: { fontFamily: "Merriweather, Georgia, Times New Roman, serif", fontSize: "24px", fontWeight: 900, lineHeight: 1.18, letterSpacing: "-0.015em" } + headline: { fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif", fontSize: "18px", fontWeight: 700, lineHeight: 1.2, letterSpacing: "-0.01em" } + section: { fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif", fontSize: "18px", fontWeight: 600, lineHeight: 1.35, letterSpacing: "-0.005em" } + section-heading: { fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif", fontSize: "15px", fontWeight: 600, lineHeight: 1.35, letterSpacing: "0" } + title: { fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif", fontSize: "16px", fontWeight: 600, lineHeight: 1.25, letterSpacing: "-0.005em" } + prose: { fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif", fontSize: "15px", fontWeight: 400, lineHeight: 1.6, letterSpacing: "0" } + body: { fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif", fontSize: "14px", fontWeight: 400, lineHeight: 1.45, letterSpacing: "0" } + secondary: { fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif", fontSize: "13px", fontWeight: 500, lineHeight: 1.3, letterSpacing: "0" } + label: { fontFamily: "Inter, -apple-system, system-ui, Segoe UI, sans-serif", fontSize: "13px", fontWeight: 500, lineHeight: 1.35, letterSpacing: "0" } + mono: { fontFamily: "JetBrains Mono, ui-monospace, Menlo, Consolas, monospace", fontSize: "12px", fontWeight: 500, lineHeight: 1.4, letterSpacing: "0" } rounded: sm: "3px" base: "4px" @@ -131,81 +81,18 @@ spacing: xxl: "24px" xxxl: "32px" components: - button-primary: - backgroundColor: "{colors.primary-red-deep}" - textColor: "{colors.white}" - typography: "{typography.secondary}" - rounded: "{rounded.base}" - padding: "4px 10px" - button-secondary: - backgroundColor: "{colors.surface}" - textColor: "{colors.ink}" - typography: "{typography.secondary}" - rounded: "{rounded.md}" - padding: "0 10px" - height: "28px" - button-ghost: - backgroundColor: "transparent" - textColor: "{colors.ink-muted}" - typography: "{typography.body}" - rounded: "{rounded.md}" - padding: "0 8px" - height: "30px" - input-find: - backgroundColor: "{colors.surface}" - textColor: "{colors.ink}" - typography: "{typography.body}" - rounded: "{rounded.md}" - padding: "0 10px" - height: "30px" - chip-type: - backgroundColor: "{colors.surface-tint}" - textColor: "{colors.ink-muted}" - typography: "{typography.label}" - rounded: "{rounded.sm}" - padding: "1px 6px" - sidebar-row: - backgroundColor: "{colors.graphite-chrome}" - textColor: "{colors.graphite-muted}" - typography: "{typography.body}" - rounded: "{rounded.md}" - padding: "0 10px 0 8px" - height: "30px" - sidebar-row-active: - backgroundColor: "{colors.graphite-pill}" - textColor: "{colors.graphite-pill-text}" - typography: "{typography.body}" - rounded: "{rounded.md}" - height: "30px" - table-row: - backgroundColor: "{colors.surface}" - textColor: "{colors.ink}" - typography: "{typography.body}" - padding: "0 10px" - height: "36px" - finder-palette: - backgroundColor: "{colors.surface}" - textColor: "{colors.ink}" - typography: "{typography.body}" - rounded: "{rounded.palette}" - width: "640px" - segmented-track: - backgroundColor: "{colors.surface-tint}" - textColor: "{colors.ink-muted}" - typography: "{typography.secondary}" - rounded: "{rounded.md}" - padding: "2px" - height: "28px" - segmented-selected: - backgroundColor: "{colors.surface}" - textColor: "{colors.ink}" - typography: "{typography.secondary}" - rounded: "{rounded.base}" - padding: "0 9px" - height: "22px" - link-quiet: - textColor: "{colors.connection-teal-ink}" - typography: "{typography.body}" + button-primary: { backgroundColor: "{colors.primary-red-deep}", textColor: "{colors.white}", typography: "{typography.secondary}", rounded: "{rounded.base}", padding: "4px 10px" } + button-secondary: { backgroundColor: "{colors.surface}", textColor: "{colors.ink}", typography: "{typography.secondary}", rounded: "{rounded.md}", padding: "0 10px", height: "28px" } + button-ghost: { backgroundColor: "transparent", textColor: "{colors.ink-muted}", typography: "{typography.body}", rounded: "{rounded.md}", padding: "0 8px", height: "30px" } + input-find: { backgroundColor: "{colors.surface}", textColor: "{colors.ink}", typography: "{typography.body}", rounded: "{rounded.md}", padding: "0 10px", height: "30px" } + chip-type: { backgroundColor: "{colors.surface-tint}", textColor: "{colors.ink-muted}", typography: "{typography.label}", rounded: "{rounded.sm}", padding: "1px 6px" } + sidebar-row: { backgroundColor: "{colors.graphite-chrome}", textColor: "{colors.graphite-muted}", typography: "{typography.body}", rounded: "{rounded.md}", padding: "0 10px 0 8px", height: "30px" } + sidebar-row-active: { backgroundColor: "{colors.graphite-pill}", textColor: "{colors.graphite-pill-text}", typography: "{typography.body}", rounded: "{rounded.md}", height: "30px" } + table-row: { backgroundColor: "{colors.surface}", textColor: "{colors.ink}", typography: "{typography.body}", padding: "0 10px", height: "36px" } + finder-palette: { backgroundColor: "{colors.surface}", textColor: "{colors.ink}", typography: "{typography.body}", rounded: "{rounded.palette}", width: "640px" } + segmented-track: { backgroundColor: "{colors.surface-tint}", textColor: "{colors.ink-muted}", typography: "{typography.secondary}", rounded: "{rounded.md}", padding: "2px", height: "28px" } + segmented-selected: { backgroundColor: "{colors.surface}", textColor: "{colors.ink}", typography: "{typography.secondary}", rounded: "{rounded.base}", padding: "0 9px", height: "22px" } + link-quiet: { textColor: "{colors.connection-teal-ink}", typography: "{typography.body}" } --- # Design System: Rhizome @@ -228,7 +115,7 @@ The supported product surface is desktop web and Rhizome Desktop. Optimize for 1 - One tinted chrome layer, white work surfaces, one tinted neutral, and hairlines. - Typography that separates roles: Merriweather for document titles, Inter for UI, prose, and every number, JetBrains Mono for identifiers, paths, and code. - Red is rare; selection is a neutral chrome tint, never red. -- Status always pairs colour with shape, text, or position. +- Status always pairs colour with shape, text, or position. Each status word keeps one mark everywhere: Active is a blue half circle; Complete, Done and Success are green filled dots; unsaved changes use gold triangles; failure, Blocked and Risk use red exclamation discs; Draft, Planned and Proposed use neutral rings; Archived, Dropped and Cancelled use muted dashed rings. Schema tones and lifecycle positions cannot override these words. ## 2. Colors @@ -255,7 +142,8 @@ Every colour in `web/src/tokens.css` is a `light-dark()` pair resolved by the ro - **Info Blue** (`info-blue`): the in-progress status mark and informational tints. - **Warning Gold** (`warning-gold`, `warning-soft`, `warning-ink`): staged (unsaved) edits everywhere, the dirty tab dot, warnings, and the connection banner. Gold means "changed, not yet saved", never "problem". -- **Type palette** (`--type-1` … `--type-13`, each with an `-ink` text variant): twelve saturated categorical hues, plus slot 8, the warm-gray neutral for interfaces, untyped notes, and essential edges. Code keeps its separate `--graph-code` gray. Fills and dots clear 3:1 and text variants clear 4.5:1 against all three content surfaces in each appearance. Dark mode uses its own brighter, saturated colours. Teal stays reserved for links and connections, and red for risk. +- **Type palette** (`--type-1` … `--type-13`, each with an `-ink` text variant): twelve saturated categorical hues, plus slot 8, the warm-gray neutral for untyped notes and essential edges. Code keeps its separate `--graph-code` gray. Fills and dots clear 3:1 and text variants clear 4.5:1 against all three content surfaces in each appearance. Dark mode uses its own brighter, saturated colours. Teal stays reserved for links and connections, and red for risk. +- **One colour per type.** `web/src/lib/typePalette.ts` owns type tokens for the sidebar, Finder, Atlas, ontology pages, chips, Explorer and Overview legends. Concrete types use one vivid token everywhere. An interface shares the token of its implementor with the most records (name order breaks ties); an interface without implementors uses the name hash. Code retains its separate Explorer colour. Labels and shapes accompany colour. - Keep the assignment order `1, 6, 7, 5, 2, 3, 4, 11, 10, 12, 13, 9`: name order, types with records first, with a hash fallback for unlisted names. Hue families remain stable. Grass, chartreuse, and emerald differ in hue and lightness; gold, orange, and copper replace overlapping browns. Twelve hues cannot all remain distinct under common colour-vision deficiencies: retain labels, legends, and shapes, and never encode meaning through colour alone. | Slot | Hue | Light fill | Light ink | Dark fill / ink | @@ -287,6 +175,8 @@ The content area uses white plus one tinted neutral per appearance, separated by - **Strong Tint** (`surface-strong`; `surface-strong-dark`): count badges on tool buttons. - **Borders** (`border`, `border-strong`, `border-faint`; dark counterparts): `border` separates regions and outlines controls, `border-strong` outlines inputs, segmented controls, and overlays, and `border-faint` separates table rows and the properties block. +In dark mode the content panel has a 1px inset outline at 8% white; cards and board cards use the strong dark border (`#45433f`). Light mode retains its existing panel and card edges. + ### Chrome themes A theme sets only the chrome tokens on `html[data-theme]`: `--chrome-bg` (sidebar and inset frame), `--chrome-top` (top bar, one step darker), `--chrome-text`, `--chrome-muted`, `--chrome-pill` with `--chrome-pill-text` (the active sidebar row), and the derived `--chrome-raised` (hover, 9% text mix) and `--chrome-active` (current top-bar tab, 16% mix). Selection (`--selection`, `--selection-edge`) is tinted from the chrome, so it changes with the theme. @@ -305,7 +195,7 @@ Every theme clears 4.5:1 for chrome text and muted chrome text in both appearanc **The Teal Means Connection Rule.** Teal means a link, a relationship, or provenance. It is never decoration and never a status: success is green (`--success`), and people (assignees) are ink, not links. -**The One Validation State Rule.** A clean validation result reads "✓ No issues" everywhere it appears (the Problems status line, Briefing, strips), once per screen, with the ✓ in `--success` and the words in `--success-ink` or ink. A result with problems reads as a count, "3 issues". Never "No issues found", "0 issues", "Valid", or a second clean badge on the same screen. +**The One Validation State Rule.** Clean validation uses the shared `ValidationCheck` green check-circle. A clean validation result reads "✓ No validation issues" in Briefings and "✓ No issues" on Problems (the Problems status line, Briefing, strips), once per screen, with the ✓ in `--success` and the words in `--success-ink` or ink. A result with problems reads as a count, "3 issues". Never "No issues found", "0 issues", "Valid", or a second clean badge on the same screen. **The Chrome Owns the Theme Rule.** Themes recolour the top bar, sidebar, and selection only. Content surfaces never take a theme colour, so every theme reads the same inside the panel. @@ -374,7 +264,7 @@ The scale is fixed: `--fs-xs` 12, `--fs-sm` 13, `--fs-base` 14, `--fs-md` 15, `- **Table column policy.** Every column except the title has a fixed width and never takes a share of extra space: ids 176px, enums and short text 136px, relations 220px, people 160px, dates 116px, due dates 188px (room for an Overdue label), ages 92px, numbers and flags 72px, plus a 30px select cell. The title takes all remaining width and never drops below 320px. When the columns cannot fit at those minimums, relation columns leave first, then ids, then dates; they show in the Record pane, and the footer names them. Rows are 36px in one-line density and 56px in two-line density with the summary. -**Reading and data surfaces.** A note is a capped reading surface: a centred 540px column for prose, properties, and body blocks, while the note's control row runs edge to edge with the panel gutter, as an HTML note's does. The built-in views are capped and centred on wide screens: Briefing in one centred column of about 1320px and Overview in one of about 1520px, shared by the header, tabs, status line, and body so all four start on the same edge. Data surfaces fill the width with bounded columns: tables stretch, and board columns are fixed tracks of 260–360px shared by header and cards, so a wider window shows more columns rather than wider ones. Empty board values are 140px strips above dashed drop lanes; populated columns keep their tracks when switching card density. Cards fill an auto-fill grid with a 260px minimum. +**Reading and data surfaces.** A note is a capped reading surface: a centred 540px column for prose, properties, and body blocks, while the note's control row runs edge to edge with the panel gutter, as an HTML note's does. The built-in views are capped and centred on wide screens: Briefing in one centred column of about 1320px and Overview in one of about 1520px, shared by the header, tabs, status line, and body so all four start on the same edge. Search reads as a list of excerpts, so it caps at 960. Data surfaces fill the width with bounded columns: tables stretch, and board columns are fixed tracks of 260–360px shared by header and cards, so a wider window shows more columns rather than wider ones. Empty board values are 140px strips above dashed drop lanes; populated columns keep their tracks when switching card density. Cards fill an auto-fill grid with a 260px minimum. **Note rhythm.** Sections separate by space, not rules: 28px above an H2 and 24px above an H3, 8px below any heading, and paragraphs 0.75em apart (about 11px), well under the section gap. The note's lead line of links reads as 13px muted metadata above the body. @@ -398,10 +288,12 @@ Rhizome is flat by default and layered by structure. Depth comes from the chrome - **Low Lift** (`--shadow-sm`, `0 1px 2px rgba(42, 39, 36, 0.06)`): compact controls that need tactile definition. - **Overlay Lift** (`--shadow`, `0 1px 3px rgba(42, 39, 36, 0.08), 0 2px 6px rgba(42, 39, 36, 0.04)`): menus, popovers, and editor autocomplete. - **Command Lift** (`--shadow-lg`, `0 10px 28px rgba(42, 39, 36, 0.1)`): the ⌘P finder, the Appearance panel, and the right pane when it overlays the content below 1200px. -- **Scrim** (`--scrim`, ink at 32% in light and black at 55% in dark): behind the ⌘P finder. The desktop ⌘O and ⇧⌘O finders use it at 65% strength so the page stays readable beneath. +- **Scrim** (`--scrim`, ink at 40% in light and black at 60% in dark): behind the ⌘P finder. The desktop ⌘O and ⇧⌘O finders use it at 65% strength so the page stays readable beneath. In dark appearance every shadow switches to black at 30–60% through `light-dark()`. +Hairlines span the view's column: capped views cap their rules, while full-width tables run full width. Empty values everywhere, including the Record pane, show "—" in muted ink. + ### Named Rules **The Flat Workbench Rule.** Working surfaces are flat at rest. Use the chrome, spacing, hairlines, or the tint for hierarchy before shadow. @@ -455,7 +347,9 @@ The classes live in `base.css`; use them rather than restyling a button per scre ### Collections and the View Header -A configured view is one result set with presentations chosen from text tabs (Briefing, Table, Cards, Board, and saved views); switching presentation never resets search, filters, or sort. The title row shows the 18/700 title, a 14px muted count, a 13px muted description that truncates first, the type or interface identity ("Interface: Effort") in the header's info tooltip, which links to its Ontology detail, then Find in view, Filter, and View. View opens a popover with Group by, Sort, Rows, Columns, Reset to shared (only while the view holds personal settings), and Save view. Active filters appear as removable chips in a tinted band under the header only while a filter is active. The footer is a status line: row count, collapsed groups, and any columns moved to the Record pane. +A configured view is one result set with presentations chosen from text tabs (Briefing, Table, Cards, Board, and saved views); switching presentation never resets search, filters, or sort. The title row shows the 18/700 title, a 14px muted count, a 13px muted description that truncates first, the type or interface identity ("Interface: Effort") in the header's info tooltip, which links to its Ontology detail, then Find in view, Filter, and View. View opens a popover with Group by, Sort, Rows, Columns, Reset to shared (only while the view holds personal settings), and Save view. Active filters appear as removable chips in a tinted band under the header only while a filter is active. The footer is a status line: counts appear only where the header has none, followed by collapsed groups and any columns moved to the Record pane. + +Trace uses a two-line header band: column identity above coverage and relation labels. ### Tables @@ -463,7 +357,7 @@ Column heads are sticky, 34px, 13/500 muted, with an ink sort arrow. Rows are 36 ### Board and Cards -Board columns are tinted bands without a border (6px corners) holding flat white bordered cards, in schema enum order. Empty values are 140px horizontal headers above visible dashed drop lanes at least 160px tall. Populated columns stay open; the per-column chevron switches card density and is labelled "Compact cards" or "Full cards". Columns with more than 24 cards default to compact cards. Staleness is a muted header line ("12 unchanged 30+ days") and a plain age on each card, never a gold pill or a clock on ages, and relation values on cards are muted secondary links (`.link-secondary`), so card titles lead. A move stages an edit until commit or discard, and every drag has a keyboard equivalent. Cards are for low-cardinality types: dense hairline cards in aligned rows of a 260px auto-fill grid, with summaries clamped to three lines. A group header is the label followed by its count ("Proposed 16"). +Board columns are tinted bands without a border (6px corners) holding flat white bordered cards, in schema enum order. Empty values are 140px horizontal headers above visible dashed drop lanes at least 160px tall. Populated columns stay open; one Board density setting in Display switches every column between compact and full cards. Staleness is a muted header line ("12 unchanged 30+ days") and a plain age on each card, never a gold pill or a clock on ages, and relation values on cards are muted secondary links (`.link-secondary`), so card titles lead. A move stages an edit until commit or discard, and every drag has a keyboard equivalent. Cards are for low-cardinality types: dense hairline cards in aligned rows of a 260px auto-fill grid, with a fixed line budget: a one-line title shows four summary lines, and a two-line title leaves three. A group header is the label followed by its count ("Proposed 16"). ### Status Marks @@ -473,19 +367,21 @@ Status is a 9px shape plus a label driven by the schema tone: hollow ring for ne ### Banners -A condition that affects a whole screen (a new task, a paused queue, unavailable search sources, a refused ref) is one `.banner`: a 36px band on the content gutter with 6px corners, a status mark with its label, concise 13px text (`.banner__text`, `.banner__aside` for a muted time), and an optional 28px `.button` action at the right (`.banner__actions` for two). Tones: neutral tint by default, `.banner--warning` (warning-soft, gold border), and `.banner--risk` (red soft, red line). Repeated conditions merge into one banner whose details sit behind a disclosure; never stack several bands. A banner is never louder than the failure it sits above. On Tasks a failed run is told by its row: the risk mark in Last run, and in the Inbox cell one quiet action, "Review failed run", the only label a failed run's action ever takes. The risk banner is reserved for an aggregate, two or more failed tasks ("2 tasks failed" and their names); one failure never repeats in a banner. A new task's notice is no banner: the row's secondary line, after the task id, carries the neutral "New" chip (as `.type-chip`, never info blue) and a muted "What it does" disclosure (muted ink with the shared chevron, never teal) that opens the schedule and purpose, with Dismiss, in a full-width row below; the failed run's action stays the row's prominent one. The Tasks header's description is a plain scheduling summary ("Next run in 6 days · 1 failed run", "A task is due now", or "Paused"); the primary ref, commit, when the repository last fetched ("Fetched 2m ago"), and where each task's mode comes from (its task default or set here) sit behind Details. The Mode column names the mode alone. +A condition that affects a whole screen (a new task, a paused queue, unavailable search sources, a refused ref) is one `.banner`: a 36px band on the content gutter with 6px corners, a status mark with its label, concise 13px text (`.banner__text`, `.banner__aside` for a muted time), and an optional 28px `.button` action at the right (`.banner__actions` for two). Tones: neutral tint by default, `.banner--warning` (warning-soft, gold border), and `.banner--risk` (red soft, red line). Repeated conditions merge into one banner whose details sit behind a disclosure; never stack several bands. A banner is never louder than the failure it sits above. On Tasks a failed run is told by its row: the risk mark in Last run, and in the Action cell one quiet action, "Review failed run", the only label a failed run's action ever takes. The risk banner is reserved for an aggregate, two or more failed tasks ("2 tasks failed" and their names); one failure never repeats in a banner. A new task's notice is no banner: the row's secondary line, after the task id, carries the neutral "New" chip (as `.type-chip`, never info blue) and a muted "What it does" disclosure (muted ink with the shared chevron, never teal) that opens the schedule and purpose, with Dismiss, in a full-width row below; the failed run's action stays the row's prominent one. The Tasks header's description is a plain scheduling summary ("Next run in 6 days · 1 failed run", "A task is due now", or "Paused"); the primary ref, commit, when the repository last fetched ("Fetched 2m ago"), and where each task's mode comes from (its task default or set here) sit behind Details. The Mode column names the mode alone. ### Right Pane -The pane has a 40px header with its 15/600 title or Info / Outline / Graph tabs (13/500, ink underline when selected) and a close button. Record shows the row's 16/600 title, a muted summary, and 30px field rows with 13/500 muted labels in a 120px column. The id sits on its own 12px mono line under the title with Open at the right, and an empty value reads "Not set" in muted ink with its edit control on hover or focus. Below the fields, Record shows the same Relations and Linked notes blocks as the note Info rail, without repeating the note identity. At 1100px the collection overlay still starts below its toolbar. +The pane has a 40px header with its 15/600 title or Info / Outline / Graph tabs (13/500, ink underline when selected) and a close button. Record shows the row's 16/600 title, a muted summary, and 30px field rows with 13/500 muted labels in a 120px column. The id sits on its own 12px mono line under the title with Open at the right, and an empty value reads "—" in muted ink with its edit control on hover or focus. Below the fields, Record shows the same Relations and Linked notes blocks as the note Info rail, without repeating the note identity. At 1100px the collection overlay still starts below its toolbar. + +Relations and Linked notes share 16px lucide arrow-left, arrow-right, and arrow-left-right icons at 1.5 stroke in faint ink, including their legends and the Record pane. ### Note Reader -A note opens in a centred 540px column. Above it, an edge-to-edge control row holds the type chip, the mono path (which truncates before any control does), the note's presentations (Structure, Markdown, and any saved view) as a segmented control with no default-view dot (the tooltip names the default), and Copy link as a ghost button with a link icon. The title is Merriweather 24/900. Properties sit directly under the identity line with no visible label (an sr-only heading keeps the landmark), capped at the 540px prose measure so their edges line up with the body, as a two-column grid with a 120px column of 13/500 muted labels and 14px values in 30px rows; a long text value (such as Summary) runs full width beneath its label, showing up to six lines in read mode; only overflow offers "Show full summary", followed by "Show less" when open. Edit mode shows the full field editor. There is no rule on every row; empty properties wait behind a "Show N empty fields" toggle, and a `border-faint` hairline closes the block. Body headings are Inter 600 with more space above than below; a collapsible section's 14px chevron sits in the gutter and shows on hover, on focus, and while collapsed. Prose is 15/1.6 at the 540px measure. Inline code and code blocks use the tint and mono. +A note opens in a centred 540px column. Above it, an edge-to-edge control row holds the type chip, the mono path (which truncates before any control does), the note's presentations (Structure, Markdown, and any saved view) as a segmented control with no default-view dot (the tooltip names the default), and Copy link as a ghost button with a link icon. The title is Merriweather 24/900. Properties sit directly under the identity line with no visible label (an sr-only heading keeps the landmark), capped at the 540px prose measure so their edges line up with the body, as a two-column grid with a 120px column of 13/500 muted labels and 14px values in 30px rows; a long text value (such as Summary) runs full width beneath its label, showing up to six lines in read mode; only overflow offers "Show full summary", followed by "Show less" when open. Edit mode shows the full field editor. There is no rule on every row; empty properties wait behind a "Show N empty fields" toggle, and a `border-faint` hairline closes the block. Body headings are Inter 600 with more space above than below; a collapsible section's 14px chevron sits in the gutter and shows on hover, on focus, and while collapsed. Prose is 15/1.6 at the 540px measure. Inline code and code blocks use the tint and mono; prose inline code has 2px horizontal padding. ### Section Editor -In edit mode each section body becomes an editor in the same place, with read mode's typography and measure, so toggling Edit does not move the text. It has no box at rest, takes the tint on hover, and draws the red focus ring (1px border plus 1px ring) only while focused. Its padding bleeds outward through negative margins. A changed block turns warning-soft with a gold border. Empty properties stay behind "Show N empty fields" in edit mode too, unless a field has staged changes or an issue, and identifier guidance sits behind an info mark, so entering edit mode barely moves the body. Dates are edited as ISO text (`2026-10-26`) with a calendar button for the native picker. +In edit mode each section body becomes an editor in the same place, with read mode's typography and measure, so toggling Edit does not move the text. It has no box at rest, takes the tint on hover, and draws the red focus ring (1px border plus 1px ring) only while focused. Its padding bleeds outward through negative margins. A changed block turns warning-soft with a gold border. Empty properties stay behind "Show N empty fields" in edit mode too, unless a field has staged changes or an issue, and identifier guidance sits behind an info mark, so entering edit mode barely moves the body. Dates stay in words at rest in edit mode; focus reveals the ISO field (`2026-10-26`) and calendar button, and leaving the field restores words. ### HTML Notes @@ -511,7 +407,7 @@ Rhizome Desktop's 38px toolbar is the theme's `--chrome-top`, which the overlay ### Agent -The Agent screen uses the shared view header: the session title, its message count, and the harness and its state ("Claude · Ready") as the description. The harness version and account are diagnostics behind a ghost "Details" disclosure at the right of the title row. Harness settings sit at the foot of the sidebar as one labelled 28px chrome-tinted select per row at full sidebar width: Harness and Model always show, and Reasoning effort and Permission mode sit under a compact "Session settings" disclosure (the shared chevron, 13/500 label) whose summary still names the active permission at its right. The conversation and the composer share one centred 760px column (`--agent-column`), so a wide window never stretches the thread. The composer is one framed field (`border-strong`, 10px corners, no resize grip) whose message grows with its content up to 240px, then scrolls, above a bar with the send hint, or, when no harness can take a turn, the reason and next step (install, or log in with a copyable command), beside a 28px primary Send. The sidebar's 28px "New session" button is chrome-tinted like the selects. An empty thread that can take a turn shows "Try asking" (the section label) and three example questions directly above the composer, as quiet 32px action rows with a 16px arrow in faint ink 8px after the question, that fill the composer and focus it. The questions and the composer move together to about 40% of the panel's height (the free space splits 2 above to 3 below), so the panel never opens on a void; the composer's placeholder ("Ask Rhizome…") is its only label. The empty thread never invites a question that cannot be sent. +The Agent screen uses the shared view header: the session title, its message count, and the harness and its state ("Claude · Ready") as the description. The harness version and account are diagnostics behind a ghost "Details" disclosure at the right of the title row. Harness settings sit at the foot of the sidebar as one labelled 28px chrome-tinted select per row at full sidebar width: Harness and Model always show, and Reasoning effort and Permission mode sit under a compact "Settings" disclosure (the shared chevron, 13/500 label) whose summary still names the active permission at its right. The conversation and the composer share one centred 760px column (`--agent-column`), so a wide window never stretches the thread. The composer is one framed field (`border-strong`, 10px corners, no resize grip) whose message grows with its content up to 240px, then scrolls, above a bar with the send hint, or, when no harness can take a turn, the reason and next step (install, or log in with a copyable command), beside a 28px primary Send. The sidebar's 28px "New session" button is chrome-tinted like the selects. An empty thread that can take a turn shows "Try asking" (the section label) and three example questions directly above the composer, as quiet 32px action rows with a 16px arrow in faint ink 8px after the question, that fill the composer and focus it. The questions and the composer move together to about 40% of the panel's height (the free space splits 2 above to 3 below), so the panel never opens on a void; the composer's placeholder ("Ask Rhizome…") is its only label. The empty thread never invites a question that cannot be sent. ### GraphQL diff --git a/docs/efforts/2026-11-04-15-30-workbench-design-hill-climb.md b/docs/efforts/2026-11-04-15-30-workbench-design-hill-climb.md index ff3064fa4..967ea8805 100644 --- a/docs/efforts/2026-11-04-15-30-workbench-design-hill-climb.md +++ b/docs/efforts/2026-11-04-15-30-workbench-design-hill-climb.md @@ -174,10 +174,12 @@ The rubric, fixed-vault capture, and before/after comparisons are reusable. The ## Follow-ups -- [ ] Open a graph redesign effort for Explorer, Overview maps, and Atlas. #action-item +- [x] Open a graph redesign effort for Explorer, Overview maps, and Atlas. #action-item Base the redesign on mock-ups. Explorer should choose a smart initial view, expand a node on click, give an overview of everything Rhizome knows, and aggregate rather than truncate. + Delivered in [[docs/efforts/2026-11-05-17-11-parallel-design-hill-climb|EFF-2026-11-05-17-11]], under Drew's revised direction: the existing Explorer was rebuilt, and Atlas was left as it is. assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] -- [ ] Fix the backend action-item embedded-title 80-byte cut. #action-item +- [x] Fix the backend action-item embedded-title 80-byte cut. #action-item + Delivered in [[docs/efforts/2026-11-05-17-11-parallel-design-hill-climb|EFF-2026-11-05-17-11]]: Action Items show the full title through `display_label`, and the parser title and embedding text stay capped, as Drew decided. assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] - [ ] Resolve SPEC-0117's 176 versus 177 record count. #action-item Investigate ambiguous-note counting under [[docs/specs/experience/scope-overview|SPEC-0117]]. diff --git a/docs/efforts/2026-11-05-17-11-parallel-design-hill-climb.md b/docs/efforts/2026-11-05-17-11-parallel-design-hill-climb.md new file mode 100644 index 000000000..fde36539a --- /dev/null +++ b/docs/efforts/2026-11-05-17-11-parallel-design-hill-climb.md @@ -0,0 +1,180 @@ +--- +type: EffortNote +id: EFF-2026-11-05-17-11 +aliases: [EFF-2026-11-05-17-11] +name: "Parallel design hill climb" +created-at: "2026-11-05T22:11:38Z" +status: complete +plan-approved-by: "[[docs/people/Drew Colthorp|Drew Colthorp]]" +summary: "Retroactive closure of the 2026-11-04/05 divide-and-conquer design push: three slice leads (Collections, Notes and tools, Graphs), a shared integration pass, a rebuilt whole-vault Explorer, and full Action Item titles, closed after a saturated 7.83 council." +governing-specs: + - "[[docs/specs/experience/workbench-redesign]]" + - "[[docs/specs/technical/design-system-parity]]" + - "[[docs/specs/technical/group-views-and-view-platform]]" + - "[[docs/specs/technical/type-collection-views]]" + - "[[docs/specs/experience/scope-overview]]" + - "[[docs/specs/experience/search-workspace]]" + - "[[docs/specs/experience/schema-guided-note-editing]]" +--- + +# Parallel design hill climb + +## Scope + +Record the parallel design hill climb that [[docs/people/Drew Colthorp|Drew Colthorp]] directed on 2026-11-04 and 2026-11-05, after [[docs/efforts/2026-11-04-15-30-workbench-design-hill-climb|EFF-2026-11-04-15-30]] closed in [PR #91](https://github.com/atomicobject/rhizome/pull/91). That effort is a historical record, and this push is new effort-driven work, so it gets its own effort. No effort was opened before the work. Like its predecessor, this one was opened at closure and identifies the delivered slice retrospectively. + +The delivered change is `7e576548..4801ad49` on `t3/parallel-hill-climb-1`: 143 commits and 264 files, almost all under `web/`. The backend part is small: an Action Item display label in `pkg/ontology` and `pkg/embedindex`, with catalog materialization version 17. Atlas (the ontology view) was deliberately left out. This record closes the banked design slice. It does not certify the score target or PR merge readiness. + +## Spec Set (Frozen) + +Selected at closure against delivery head `4801ad49` (base `7e576548`). These note-level links are the retrospective contract boundary, not evidence of a freeze before implementation. The same seven notes appear in `governing-specs`. + +- [[docs/specs/experience/workbench-redesign]] +- [[docs/specs/technical/design-system-parity]] +- [[docs/specs/technical/group-views-and-view-platform]] +- [[docs/specs/technical/type-collection-views]] +- [[docs/specs/experience/scope-overview]] +- [[docs/specs/experience/search-workspace]] +- [[docs/specs/experience/schema-guided-note-editing]] + +No spec owns Explorer's behaviour: aggregation, expanding in place, layout stability, or code and note links. The delivered Explorer is described under Actual Delivered, and an owning contract is a follow-up. + +## Stories In Scope (Frozen) + +No stories or acceptance criteria were selected before execution. At closure, the delivered concerns map to these existing story targets. Only the visual and navigation slice described here is included, not every obligation in each story: + +- [[docs/specs/experience/workbench-redesign#^SPEC-0126-US3|SPEC-0126 US3]], [[docs/specs/experience/workbench-redesign#^SPEC-0126-US7|US7]], and [[docs/specs/experience/workbench-redesign#^SPEC-0126-US11|US11]]: collection headers, wide-screen composition, and note reading and editing presentation. +- [[docs/specs/experience/scope-overview#^SPEC-0117-US1|SPEC-0117 US1]] and [[docs/specs/experience/scope-overview#^SPEC-0117-US3|US3]]: group and All notes Overview maps, legends, and link coverage. +- [[docs/specs/experience/search-workspace#^SPEC-0098-US1|SPEC-0098 US1]] and [[docs/specs/experience/search-workspace#^SPEC-0098-US2|US2]]: the search results column and its excerpts. +- [[docs/specs/experience/schema-guided-note-editing#^SPEC-0099-US4|SPEC-0099 US4]] and [[docs/specs/experience/schema-guided-note-editing#^SPEC-0099-US6|US6]]: Discard confirmation and the editing layout. + +The technical specs' selected obligations are their type palette, status mark, Board and Cards layout, and bundled Briefing, Trace, and Sections presentation requirements. No new story IDs were invented. + +## Spec Coverage Checklist + +- [x] Type colours: one token per type across the sidebar, Finder, Atlas, ontology pages, chips, Explorer, and Overview legends, through `web/src/lib/typePalette.ts`, which the kit also uses. SPEC-0125 and SPEC-0126 now say that an interface shares its leading implementor's token. +- [x] Status marks: each status word keeps one mark everywhere (`235fb766`, with Relation chips and Record reverse links in `9d9f1660`). SPEC-0111's lifecycle-mark rule now says so. +- [x] Collections and group views: Board, Cards, Record, Action Items, Briefing, Trace, and Sections received Lead A's and the integration presentation changes; DESIGN.md records the conventions. +- [x] Notes, search, and tools: the note reading and editing presentation, Search at 960px with 720px excerpts (already the SPEC-0098 contract), and Discard confirming drafts as SPEC-0099 US4 requires. +- [x] Overview maps: legends, labels, and link coverage. "106 not linked" sits beside the Link coverage heading. +- [x] Explorer: rebuilt within the existing folder-containment concept. No spec owns it; see Follow-ups. +- [x] The score target shortfall is explicit in Actual Delivered and Deviations. This checklist accounts for the banked slice and does not mark whole governing specs satisfied. + +## Plan + +Retrospective account of Drew's in-session direction, which he approved on 2026-11-04: + +1. Divide the whole-app loop, which plateaued at 7.93 after round 7, into three slices with their own hill climbs, each run by an Opus 5.5 lead: A Collections, B Notes and tools, C Graphs. An integrator owns the shared design system (tokens, base styles, kit, shell, DESIGN.md) and merges the leads. +2. In each slice, GPT-6.1 Sol implements, and Sol, GPT-6 Astra, and Opus 5.5 review fresh each round against the shared rubric. The goal is 9 or more from every reviewer in every category on every screen. A lead stops at that target, at a plateau (two rounds rising less than 0.15), or after five rounds. +3. Graphs follow Drew's revised direction. Keep the folder-containment Explorer and make it smarter: aggregate and never truncate, keep the layout stable when a folder expands, make code first-class, and use the vivid palette. Atlas stays untouched. +4. Integrate the shared items the leads hand over, run a whole-app council, fix its findings, then review code quality with sol-loop, pass local gates, and open a PR. + +The shared lead brief (`LEAD-BRIEF.md`), the three slice tasks (`task-a.md`, `task-b.md`, `task-c.md`), and `INTEGRATION-TODO.md` in `web/scripts/design-loop/rounds/parallel-1/` are the contemporary instructions. That folder is ignored by Git. This account was written at closure and is not a new historical plan revision. + +## Plan Approval + +[[docs/people/Drew Colthorp|Drew Colthorp]] approved the divide-and-conquer plan in-session on 2026-11-04, including the revised Graphs direction. On 2026-11-05 he approved each lead's judge picks and decided the integration questions listed under Execution Notes. The closing task supplies this approval evidence and authorizes the retrospective effort. The original messages' exact times are unavailable, so no timestamped approval event is fabricated. + +## Original Intended Delivery + +Every reviewer scores 9 or more in every rubric category on every screen of every slice, and the integrated app keeps those gains in a whole-app council. The rubric's categories are typography, hierarchy, spacing and density, colour and contrast, iconography, consistency and polish, clarity, and overall quality. + +## Actual Delivered + +- **Explorer (Lead C):** the folder-containment root graph now covers the whole vault. It counts all 655 notes and 4,572 code files and aggregates instead of truncating. Folders expand in place with a stable layout that follows containment. Code is first-class, with its own colour and code and note links drawn, and the vivid type palette is retained. Capture states show an expanded folder, a deep folder after two expansions, and a focused file. +- **Overview maps (Lead C and integration):** clearer legends, labels, rings, and member tables on the group and All notes Overviews. "106 not linked" sits beside Link coverage. +- **Collections (Lead A):** Board density is one Display setting; cards keep a fixed line budget; empty values show "—" everywhere; the Trace header is a two-line band; status-strip counts appear only where the header has none; the collection, Briefing, Trace, and Sections layouts are refined. +- **Notes and tools (Lead B):** a calmer note reader and editor, Search, Finder, Agent, Tasks, and Problems. +- **Shared system (integration):** one colour per type; one mark per status word; dark-mode panel and card edges; the Finder scrim; edit-mode dates that show words at rest and the ISO field only while focused; ages in hours up to 23h, then days; 2px inline-code padding; 16px lucide arrows in rails and legends; and DESIGN.md conventions for these. Search is capped at 960px with 720px excerpts. +- **Behaviour fixes Drew decided on 2026-11-05:** Discard confirms before dropping local drafts as well as staged edits. Action Items show the full title through a new catalog `display_label` (`pkg/ontology/display_title.go`), and `firstLineTitle` and `ITEM_SUMMARY`, the embedding text, are unchanged, so nothing is re-embedded. The three tests that failed only in shuffled order are fixed. + +Slice results, as the mean across the slice's screens of Sol, Astra, and Opus scores: + +| Slice | Baseline | Final | Rounds | Stop | +| --- | --- | --- | --- | --- | +| A Collections | 7.64 (a-0) | 8.04 (a-4) | 4 | Plateau rule and round limit | +| B Notes and tools | 8.20 (b-0) | 8.23 (b-2), peak 8.33 at b-1 | 2 | Plateau | +| C Graphs | 5.73 (c-0) | 7.37 (c-5) | 5 | Round limit | + +Lead C's root Explorer screen rose from 7.00 to 7.40. + +The whole-app council after integration: + +| Round | Sol | Astra | Opus | Mean | +| --- | --- | --- | --- | --- | +| Round 7 (PR #91) | 8.20 | 8.00 | 7.60 | 7.93 | +| int-1 | 8.20 | 8.10 | 7.00 | 7.77 | +| int-2 | 8.10 | 8.10 | 7.30 | 7.83 | + +A Fable 5.1 plateau judge found the council saturated. Most int-2 consensus findings were regressions from int-1 fixes or reversals of them, because fresh reviewers never see earlier ledgers. One unscored regression-repair round followed (int-3), and int-4 carried out Drew's decisions. These are screenshot judgments, not a usability-study result. + +## Execution Notes + +- 2026-11-05T22:11:38Z: Opened this effort retroactively at closure. Read the closure and setup rules, release policy, the closed EFF-2026-11-04-15-30 record, the lead brief, the three tasks, `INTEGRATION-TODO.md`, and the round ledgers, then checked the governing specs against `git diff 7e576548`. All the history in this note is a retrospective summary of the supplied evidence and those ignored local files. +- Evidence locations, all under `web/scripts/design-loop/rounds/` and ignored by Git: `a-0`…`a-4` and `a-final`; `b-0`…`b-2` and `b-final`; `lead-c/c-0`…`lead-c/c-5` and `lead-c/final`. Each scored lead round has `LEDGER.md`, `DECLINED.md`, and `scores/`. Integration: `int-1` (with `DECLINED.md` and `WORKER-COMMON.md`), `int-2` (`LEDGER.md` and `scores/`; it has no `DECLINED.md`), and the `int-2-*`, `int-3-*`, and `int-4-*` worker folders, some with `REPORT.md` or `DECLINED.md`. These are not committed release evidence; the tables above keep their results. +- Drew's decisions on 2026-11-05: one colour per type; Search capped narrower, at 960px; and "whatever is recommended is fine", which covered Discard confirming before dropping drafts, full Action Item titles through `display_label` under his never-re-embed rule, and fixing the shuffle-order tests. He left "106 not linked" to the integrator, who placed it beside Link coverage. He had already approved the leads' judge picks: cards keep a fixed line budget, the Board gets one Display setting for card density, and empty values show "—". +- Code review: sol-loop, three rounds with GPT-6.1 Sol at high effort, verdict approved. Its one `should` finding was that Relation chips and Record reverse links bypassed the status-word mapping. That was fixed in `9d9f1660`, with a regression test. +- Local gates, as reported by the integrator: `make check` passed (Go lint, vet, 142 Go packages, web lint, both typechecks, and 1,911 web unit tests). The full Playwright suite had three failures in `app.spec.ts`, all stale tests. They were fixed in `802a16f3`, and a rerun passed 121 of 121. One later commit, `4801ad49` (staged cards marked with a dot), landed after those runs. The integrator reruns both suites before the PR, and the Greptile CLI runs after the PR opens. +- 2026-11-06, PR review: the Greptile CLI ran eleven passes on PR #96. It scored 4, 5, 4, 3, 4, 4, 4, 5, 4, 4 and 4, and every pass after the second reported new real bugs. Most were in the rebuilt Explorer; others were in Cards, Board, Record, Tasks, Sections and the file panel. All P1 findings and every P2 that touched a stated rule were fixed with regression tests. Separately, an independent GPT-6.1 Sol sweep of the Explorer found eleven more issues (E1–E11): layout stability, silent truncation, and unbounded or quadratic work on large repositories. All eleven were fixed, and a second Sol pass confirmed each one resolved. During the review, an Explorer label fix regressed the opened-folder fan, with labels displaced and overlapping. That was caught in the captures and restored in `a537f5fd`, against Lead C's final shots. +- 2026-11-06, flaky tests: the repository rule now requires diagnosing and fixing a flake before merging. Every test that flaked during this effort was reproduced under load, with its failure rate recorded before and after, and fixed at its cause. That covers: process cleanup in the harness (`c2bffaf4`, `51e1d450`, `2eee25c6`), the validate repair-priority wait (`54c3f001`), the agentcode request deadline (`8a4a696e`), prepared-query readiness (`830a5426`), Explorer renderer teardown (`6d9b4fcc`), group-view preference persistence (`062d1e0c`), the compounding client's EPIPE on early stdin close (`2843919e`), and `TestDevStack`, which drained the streamed response before repeating its idempotency key (`3cd98166`: 15/500 failures before, 0/500 after). `TestRunLiveDoesNotReadUnselectedRecipeSources`, `TestDerivedRestartRetriesActiveDebtWithoutFilesystemEvents` and the editor textbox tests didn't reproduce in at least 200 runs each under load, so they were left unchanged. The reports are in the ignored `web/scripts/design-loop/rounds/flake-diagnosis/`. +- Reconciled contradicted spec statements on this branch: SPEC-0126 and SPEC-0125 said interfaces and code use the neutral type slot. They now say that an interface shares the token of its implementor with the most records and that Explorer gives code its own colour. SPEC-0111 said lifecycle marks always encode position and tone. It now says that a recognized status word keeps one mark everywhere. The SPEC-0098 960px cap and the SPEC-0099 US4 discard decision already matched the delivery. +- Completed two of EFF-2026-11-04-15-30's follow-ups that this branch delivers, by checking each box and adding one line that cites this effort, with no other change to the closed record: the graph redesign (delivered here under Drew's revised direction, which keeps Explorer's concept and leaves Atlas as it is) and the action-item title cut (resolved by `display_label`; Drew decided to keep the parser title and embedding text capped). Its other follow-ups remain open. Of its six oversized web files, only `web/src/lib/ontologyGraph.ts` (931 lines) is still over 500. +- 2026-11-05: `RZM_RUNTIME_AUTOSTART=0 RZM_SKIP_REPO_DELEGATE=1 ./bin/darwin/rzm agent code execute --session-id y7Qc57ecjG_4o5G1` ran `validate default` scoped to each changed file: this note, EFF-2026-11-04-15-30, SPEC-0111, SPEC-0125, SPEC-0126, and `CHANGELOG.md`. Ontology, identifiers, and broken-links all passed with zero findings. Repository-wide `frozen-scope-drift` found nothing. `closure-drift-pack` resolved this EffortNote, its approver, and its seven frozen specs. `action-items-in-note` read back nine open follow-ups here and the two completed items in EFF-2026-11-04-15-30, all assigned to a resolved `Person`. + +## Deviations + +1. **Opened retroactively.** The effort and frozen links were created at closure, not before the work. No fictional timeline or earlier freeze is asserted. +2. **Score target not reached.** No slice reached 9 in every category, and the integrated council ended at 7.83, below round 7's 7.93. The Fable judge found the council saturated: fresh reviewers reversed earlier fixes. The work was banked after one regression-repair round. +3. **"Pilot active" pill unchanged.** `INTEGRATION-TODO.md` planned to move the red "Pilot active" pill to the shared Active mark. The pill is authored content in a closed effort note, so it was left unchanged. +4. **Catalog reindex required.** Catalog materialization version 17 refreshes Action Item display labels, so each repository rematerializes its catalog once after upgrading. Embedding text is unchanged, and nothing is re-embedded. +5. **Gates predate the last commit.** The recorded `make check` and Playwright runs predate `4801ad49`. The integrator reruns them before the PR. + +## Closure Checklist + +- [x] Rhizome default validation (ontology, identifiers, broken-links) passed with zero findings on the six changed files, and `frozen-scope-drift` found none. +- [x] Alignment checked against `git diff 7e576548`, DESIGN.md, the lead and integration ledgers, and the lead brief and tasks. The target shortfall and the gates' timing are explicit. +- [x] Contradicted statements in SPEC-0111, SPEC-0125, and SPEC-0126 reconciled on this branch. +- [x] The closed effort's delivered follow-ups completed, and new follow-ups triaged and assigned below. +- [x] Changelog line added under `## [Unreleased]`, including the catalog refresh. +- [x] PR handoff recorded: [PR #96](https://github.com/atomicobject/rhizome/pull/96) carries the delivery, the review and flake fixes, and this closure record. Local gates passed on the final head, with current `main` merged in: `make check` (Go lint and vet, all Go packages, the Team API check, web lint, both typechecks, 1,956 web unit tests) and the full Playwright suite (121 of 121). CI runs on the PR. +- [x] Local gates and sol-loop review passed on the branch (Execution Notes). The integrator reruns gates before the PR; Greptile and CI run on the PR. + +## Compounding Follow-ups + +Parallel slice leads worked: each slice climbed on its own, and Lead C moved the weakest screens most. The integrated council then saturated, because reviewers who never see earlier ledgers reverse fixes that other reviewers asked for. The Fable judge's lesson for the loop: give reviewers the earlier ledger, or require three votes to reverse a fix. + +## Follow-ups + +- [ ] Split `web/src/ontology.css` (5,361 lines) by surface. #action-item + It holds rules for other surfaces, such as the note edit bar (`.ontology-edit-bar`). Fold the `note-reader.css` edit-bar override and the Notes Info toggle rule back into their owning rules. + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [ ] Refresh the stale `.impeccable/design.json` sidecar with `impeccable document`. #action-item + This carries forward the still-open sidecar item in EFF-2026-11-04-15-30. + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [ ] Reconcile the top bar's "346 typed notes" with the 655 All notes count. #action-item + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [ ] Decide whether Explorer collapses context around an opened folder. #action-item + Lead C declined it because it conflicts with the rule that outside nodes never move. Drew's call. + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [ ] Re-measure Explorer's folder-click redraw time. #action-item + It measured 193 ms at c-5, against 76–79 ms at c-3 and c-4. + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [x] Check whether `TestGeneratedClientBoundsUnresponsiveServer` is flaky. #action-item + It was: 1 failure in 200 runs under load. Fixed in `8a4a696e` by isolating the dispatched request's deadline from queue time. + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [ ] Reinstall Rhizome Dev from `main` after merge with `make desktop-install-dev`. #action-item + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [ ] Give design-loop reviewers the earlier ledger, or require three votes to reverse a fix. #action-item + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [ ] Give Explorer an owning spec for aggregation, in-place expansion, layout stability, and code and note links. #action-item + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [ ] Tighten placement for dimmed labels outside an opened branch in Explorer. #action-item + In folder focus, a few dimmed labels outside the opened branch, such as `rhizome-md-templates`, still sit slightly away from their nodes. Opened-branch and overflow labels stay attached. + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] +- [ ] Let Explorer expand modules the server collapsed. #action-item + Above the 200,000-node graph limit, the server collapses large modules. Explorer now keeps them with their counts, but it can't load their contents. + assignee:: [[docs/people/Drew Colthorp|Drew Colthorp]] + +## Status + +Complete. Opened retroactively at closure and closed for the banked design slice. The 9 target is unmet; the council saturated, and the work was banked. Delivered in [PR #96](https://github.com/atomicobject/rhizome/pull/96), which carries this closure record; CI runs on the PR. diff --git a/docs/reference/subsystems/ontology.md b/docs/reference/subsystems/ontology.md index b1e8a329a..a66001981 100644 --- a/docs/reference/subsystems/ontology.md +++ b/docs/reference/subsystems/ontology.md @@ -1,7 +1,7 @@ --- summary: "Design constraints, invariants, and review checklist for the ontology core: schema compile, projection, node catalog, sync, policy, sections, and identifier allocation under pkg/ontology." reference-kind: guide -last-verified: 2026-11-01 +last-verified: 2026-11-05 code-paths: - pkg/ontology - pkg/ontology/schema @@ -32,6 +32,8 @@ The ontology core owns Rhizome's typed note contract: compile GraphQL SDL from ` ## Design constraints +- **Embedded display labels are independent of embedding inputs.** Catalog display labels and workspace titles use the complete item headline, with metadata removed. The parser title and `ITEM_SUMMARY` keep their existing capped values. Materialization version 17 refreshes display labels without adding embedding text. + - **Presentation and workspace membership are schema declarations.** Type-level `@display(group:, parent:)` organizes navigation. Field-level `@display(role:, importance:, hover:)` controls compact presentation and inherits through implemented interfaces. Field capabilities expose effective importance with NORMAL as the zero-value behavior; `hover: false` applies only to hover previews. These hints do not change membership, queries, or counts. `@workspaceMember` is valid only on explicit concrete-type link fields and identifies owner-selected workspace members; interfaces cannot declare it because navigation resolves the concrete owner's schema. Directory proximity and type presentation never establish instance membership. - **Section summaries retain structural identity.** A singular heading-backed `@contains` field may declare `@display(role: SUMMARY)`, including importance and hover hints. Typed queries keep the section selection (`summary { content }`); materialization version 14 additionally stores whitespace-normalized body text for compact indexed reads. Section bindings retain their canonical refs and source spans. Missing nullable sections remain retrievable. Native tables/cards expose display text without claiming scalar editing or filtering; edit the section in its workspace. diff --git a/docs/specs/experience/workbench-redesign.md b/docs/specs/experience/workbench-redesign.md index 8419175a2..268fe71ec 100644 --- a/docs/specs/experience/workbench-redesign.md +++ b/docs/specs/experience/workbench-redesign.md @@ -4,8 +4,8 @@ id: SPEC-0126 aliases: [SPEC-0126, Workbench redesign] summary: "Redesigns the Rhizome workbench in the browser and in Rhizome Desktop: selectable chrome themes with light and dark appearance, an Inter type scale and neutral surfaces, a calmer view header with progressive disclosure, a table column policy that keeps titles readable, resizable side panels with one right pane, and fuzzy finders for notes and files (⌘P), repositories (⌘O), and worktrees (⇧⌘O)." spec-status: active -last-updated: 2026-11-04 -last-verified: 2026-11-04 # Round 7 +last-updated: 2026-11-05 +last-verified: 2026-11-05 # Parallel hill climb --- # Workbench redesign @@ -213,7 +213,7 @@ This spec governs the Notes workspace shell, configured views, bundled group vie ### Workspace navigation and type colours - MUST retain note tabs while a collection, saved view, Problems, Changes, or search replaces the current page. Only one such page is retained at a time; the note-tab strip is visible only while at least one note is open. -- MUST use one twelve-hue type palette across the finder, type dots, maps, Explorer, Atlas, and bundled views. Assign concrete types by name, types with records first; interfaces, collapsed groups, code, and untyped notes use the neutral slot. Unknown types fall back to a name hash. Hues repeat after twelve types. +- MUST use one twelve-hue type palette across the finder, type dots, maps, Explorer, Atlas, and bundled views. Assign concrete types by name, types with records first, and give each type one colour on every surface. An interface shares the colour of its implementor with the most records (name order breaks ties); one without implementors uses the name hash. Collapsed groups and untyped notes use the neutral slot, and Explorer gives code its own colour. Unknown types fall back to a name hash. Hues repeat after twelve types. ### Desktop diff --git a/docs/specs/technical/design-system-parity.md b/docs/specs/technical/design-system-parity.md index 04b571432..310f9f944 100644 --- a/docs/specs/technical/design-system-parity.md +++ b/docs/specs/technical/design-system-parity.md @@ -4,8 +4,8 @@ id: SPEC-0125 aliases: [SPEC-0125, Design system parity] summary: "One design system across the host web UI, the custom-view kit, bundled views, and agent guidance: shared tokens with a dark theme, kit defaults and primitives that match DESIGN.md, AA contrast, calmer collection toolbars, designed loading states, and render performance on large vaults." spec-status: active -last-updated: 2026-11-04 -last-verified: 2026-11-04 # Round 7 +last-updated: 2026-11-05 +last-verified: 2026-11-05 # Parallel hill climb --- # Design system parity @@ -41,7 +41,7 @@ Amended by [[workbench-redesign|SPEC-0126]] on 2026-10-25: - `web/src/base.css` remains the single token source. The kit build includes every theme block from it, not only the first `:root`. - Dark values live beside light ones and apply under `@media (prefers-color-scheme: dark)`; `color-scheme: light dark` is declared. The desktop shell (`desktop/src`) and GraphiQL follow the same tokens. - Add semantic tokens the audit found missing: filled primary (`#c8313a` light, AA with white text), text on ink, success and info soft/ink, overlay scrim, and syntax-highlight roles. Define or remove the 11 undefined tokens (`--line`, `--r-full`, `--ink`, `--accent-danger`, `--accent-warning`, `--warning-line`, `--text-default`, `--surface-1`, `--surface-2`, `--radius` in host CSS, and similar) and delete Tailwind fallbacks that hide undefined tokens. -- A shared twelve-hue categorical palette uses `--type-1..13`, reserving `--type-8` for neutral interfaces, code, collapsed groups, and untyped notes. Concrete types are assigned in name order with types having records first; unknown names use a hash fallback. Host and kit use the same assignment, and hues repeat after twelve types. Ink variants retain the 4.5:1 text-contrast requirement. It excludes AO red and connection teal. A chart series palette `--series-1..8` is neutral-first, excludes red, and reserves teal for "linked/connected". +- A shared twelve-hue categorical palette uses `--type-1..13`, reserving `--type-8` for collapsed groups and untyped notes. Concrete types are assigned in name order with types having records first; an interface shares the token of its implementor with the most records (name order breaks ties), and unknown names use a hash fallback. Explorer gives code its own colour. Host and kit use the same assignment, and hues repeat after twelve types. Ink variants retain the 4.5:1 text-contrast requirement. It excludes AO red and connection teal. A chart series palette `--series-1..8` is neutral-first, excludes red, and reserves teal for "linked/connected". - The kit's shadcn variable names must not collide with host tokens (`--muted` becomes a kit-private name). - Fonts are self-hosted woff2 with `font-display: swap`, served by the binary for the host and every custom-view frame; all currently requested weights remain available. License notices are generated. diff --git a/docs/specs/technical/group-views-and-view-platform.md b/docs/specs/technical/group-views-and-view-platform.md index ddc22d48b..b9077fc36 100644 --- a/docs/specs/technical/group-views-and-view-platform.md +++ b/docs/specs/technical/group-views-and-view-platform.md @@ -4,8 +4,8 @@ id: SPEC-0111 aliases: [SPEC-0111, Group views and view platform] summary: "Rhizome ships Briefing, Trace, and Sections display-group views as ordinary kit views, and closes the custom-view platform gaps those views expose so a repository can build views of the same complexity." spec-status: active -last-updated: 2026-11-04 -last-verified: 2026-11-04 # Round 7 +last-updated: 2026-11-05 +last-verified: 2026-11-05 # Parallel hill climb --- # Group views and view platform @@ -48,7 +48,7 @@ This extends [[unified-view-contract|SPEC-0110]], which reserved a bundled gener ### Shared derivations - A member type's lifecycle field, each value's stage, and its gap fields come from the type profile and enum value stages in type documentation ([[type-collection-views|SPEC-0112]]); the views MUST NOT derive them from field names or tones. -- Lifecycle values MUST render with a status mark whose fill encodes the value's position among non-terminal values and whose color encodes its tone, paired with the value's label. Values in the `done` or `dropped` stage are terminal. +- Lifecycle values MUST render with a status mark paired with the value's label. A recognized status word keeps one mark everywhere (for example, Active is always the blue half circle), whatever its schema tone or position; other values use a fill that encodes their position among non-terminal values and a color that encodes their tone. Values in the `done` or `dropped` stage are terminal. - When every member's plural label starts with the same word, views MAY drop that word inside the group page. Record labels MUST otherwise use schema labels. - Links are the forward `@link` fields among member types, excluding links from a type to itself and links whose declared target is outside the group's roots. A member type that links to no other member type is a reference type. diff --git a/pkg/app/agentcode/agentcode_test.go b/pkg/app/agentcode/agentcode_test.go index f0f787068..dc423614b 100644 --- a/pkg/app/agentcode/agentcode_test.go +++ b/pkg/app/agentcode/agentcode_test.go @@ -142,7 +142,11 @@ await client.close();`, "FAKE_HANG_INIT=1") call := runNode(t, artifact.ModulePath, warmFake, vault, ` const client = createClient({executablePath, vaultPath}); await client.files({warmup:true}); +// Freeze queue elapsed time so this exercises the dispatched request's timer. +const now = Date.now; +Date.now = () => 0; try { await client.files({inputs:["a.go"]}, {timeoutMs:10}); } catch (error) { console.log(JSON.stringify({code:error.code, mayHaveExecuted:error.details.mayHaveExecuted})); } +finally { Date.now = now; } await client.close();`) require.Equal(t, "deadline_exceeded", call["code"]) require.True(t, call["mayHaveExecuted"].(bool)) diff --git a/pkg/app/cli/init/templates/starters/compounding/module/scripts/lib/calls.mjs b/pkg/app/cli/init/templates/starters/compounding/module/scripts/lib/calls.mjs index b40393ac5..6e5a4533b 100644 --- a/pkg/app/cli/init/templates/starters/compounding/module/scripts/lib/calls.mjs +++ b/pkg/app/cli/init/templates/starters/compounding/module/scripts/lib/calls.mjs @@ -33,8 +33,16 @@ export function costOf(model, usage = {}) { if (!p) return usage.costUsd || null; const read = usage.cachedInputTokens ?? 0; const write = usage.cacheWriteInputTokens ?? 0; - const fresh = inputIncludesReads(model) ? (usage.inputTokens ?? 0) - read : usage.inputTokens ?? 0; - return (fresh * p.input + write * (p.write5m ?? p.input) + read * p.read + (usage.outputTokens ?? 0) * p.output) / 1e6; + const fresh = inputIncludesReads(model) + ? (usage.inputTokens ?? 0) - read + : (usage.inputTokens ?? 0); + return ( + (fresh * p.input + + write * (p.write5m ?? p.input) + + read * p.read + + (usage.outputTokens ?? 0) * p.output) / + 1e6 + ); } // Codex structured output needs strict schemas: every property required and @@ -58,7 +66,16 @@ export function strictSchema(s) { return out; } -export const dropNulls = (v) => (Array.isArray(v) ? v.map(dropNulls) : v && typeof v === "object" ? Object.fromEntries(Object.entries(v).filter(([, x]) => x !== null).map(([k, x]) => [k, dropNulls(x)])) : v); +export const dropNulls = (v) => + Array.isArray(v) + ? v.map(dropNulls) + : v && typeof v === "object" + ? Object.fromEntries( + Object.entries(v) + .filter(([, x]) => x !== null) + .map(([k, x]) => [k, dropNulls(x)]), + ) + : v; const CALL_TIMEOUT_MS = 60 * 60 * 1000; @@ -69,14 +86,27 @@ export function rzmClients(rzm = "rzm", { cwd } = {}) { const child = spawn(rzm, args, { cwd: dir, stdio: ["pipe", "pipe", "pipe"] }); let out = ""; let err = ""; + let inputError; // A hung CLI would hold the run's lock forever. const timer = setTimeout(() => child.kill("SIGKILL"), CALL_TIMEOUT_MS); child.stdout.on("data", (d) => (out += d)); child.stderr.on("data", (d) => (err += d)); child.on("error", fail); + child.stdin.on("error", (error) => { + // The CLI closed its input early: EPIPE on POSIX, EOF on Windows. Its reply still counts. + if (error.code === "EPIPE" || error.code === "EOF") return; + inputError = error; + child.kill("SIGKILL"); + }); child.on("close", (code) => { clearTimeout(timer); - done({ code, out, err: code === null ? `timed out after ${CALL_TIMEOUT_MS / 60000} minutes` : err }); + // A CLI may reply before input drains; keep its final status and diagnostic. + if (inputError) return fail(inputError); + done({ + code, + out, + err: code === null ? `timed out after ${CALL_TIMEOUT_MS / 60000} minutes` : err, + }); }); child.stdin.end(input); }); @@ -86,12 +116,19 @@ export function rzmClients(rzm = "rzm", { cwd } = {}) { try { detail = JSON.parse(detail.split("\n").pop()).error ?? detail; } catch {} - throw new Error(`${what}: ${typeof detail === "string" ? detail.slice(-500) : JSON.stringify(detail).slice(0, 500)}`); + throw new Error( + `${what}: ${typeof detail === "string" ? detail.slice(-500) : JSON.stringify(detail).slice(0, 500)}`, + ); }; return { async generate({ provider, model, effort, prompt, schema }) { const args = ["agent", "generate"]; - for (const [flag, v] of [["--provider", provider], ["--model", model], ["--effort", effort]]) if (v) args.push(flag, v); + for (const [flag, v] of [ + ["--provider", provider], + ["--model", model], + ["--effort", effort], + ]) + if (v) args.push(flag, v); const dir = schema ? mkdtempSync(join(tmpdir(), "sm-schema-")) : null; try { if (dir) { @@ -103,13 +140,17 @@ export function rzmClients(rzm = "rzm", { cwd } = {}) { if (dir) rmSync(dir, { recursive: true, force: true }); } }, - evaluateBatch: async (request) => parse(await run(["agent", "evaluate-batch"], JSON.stringify(request)), "evaluate-batch"), + evaluateBatch: async (request) => + parse(await run(["agent", "evaluate-batch"], JSON.stringify(request)), "evaluate-batch"), harnessStatus: async () => parse(await run(["harness", "status"]), "harness status"), - configuredHarness: async () => (parse(await run(["harness", "status", "--configured"]), "configured harness")).harness, + configuredHarness: async () => + parse(await run(["harness", "status", "--configured"]), "configured harness").harness, // Rhizome search for verification evidence; a failure is evidence too. async search(args, { cwd: dir } = {}) { const r = await run(["search", ...args], "", dir ?? cwd); - return r.code === 0 ? r.out : `(failed: ${(r.err || r.out).trim().split("\n")[0].slice(0, 200)})`; + return r.code === 0 + ? r.out + : `(failed: ${(r.err || r.out).trim().split("\n")[0].slice(0, 200)})`; }, }; } @@ -122,14 +163,25 @@ export class Stop extends Error { } // Cache keys: stage, prompt version, input content, and model binding. -export const callKey = ({ stage, binding: b, prompt, schema }) => sha({ stage, version: PROMPT_VERSION, provider: b.provider, model: b.model, effort: b.effort, prompt, schema }); -export const itemKey = ({ stage, model, item }) => sha({ stage, version: PROMPT_VERSION, model, state: item.state, questions: item.questions }); +export const callKey = ({ stage, binding: b, prompt, schema }) => + sha({ + stage, + version: PROMPT_VERSION, + provider: b.provider, + model: b.model, + effort: b.effort, + prompt, + schema, + }); +export const itemKey = ({ stage, model, item }) => + sha({ stage, version: PROMPT_VERSION, model, state: item.state, questions: item.questions }); // Rebuilds a run's spend from its ledger, so a resumed run counts what the // killed one paid for. export function spendFrom(entries, run) { const spend = { usd: 0, byRole: {} }; - for (const e of entries) if (e.run === run && (e.ok || e.usd)) account(spend, e.role, e.usage, e.usd, e.model); + for (const e of entries) + if (e.run === run && (e.ok || e.usd)) account(spend, e.role, e.usage, e.usd, e.model); return spend; } @@ -137,9 +189,18 @@ const FATAL = /harness (not installed|not logged in|unsupported)/; const JEV_ITEMS = 128; function account(spend, role, usage, usd, model) { - const r = (spend.byRole[role] ??= { calls: 0, cached: 0, inputTokens: 0, outputTokens: 0, usd: 0 }); + const r = (spend.byRole[role] ??= { + calls: 0, + cached: 0, + inputTokens: 0, + outputTokens: 0, + usd: 0, + }); r.calls++; - r.inputTokens += (usage?.inputTokens ?? 0) + (inputIncludesReads(model) ? 0 : usage?.cachedInputTokens ?? 0) + (usage?.cacheWriteInputTokens ?? 0); + r.inputTokens += + (usage?.inputTokens ?? 0) + + (inputIncludesReads(model) ? 0 : (usage?.cachedInputTokens ?? 0)) + + (usage?.cacheWriteInputTokens ?? 0); r.outputTokens += usage?.outputTokens ?? 0; r.usd += usd ?? 0; spend.usd += usd ?? 0; @@ -150,19 +211,30 @@ function account(spend, role, usage, usd, model) { export function makeCaller({ clients, store, run, bindings, budget = null, spend, onResult }) { let reserved = 0; const reserve = (usd) => { - if (budget !== null && spend.usd + reserved + usd > budget) throw new Stop("budget", `budget $${budget} reached ($${spend.usd.toFixed(4)} spent)`); + if (budget !== null && spend.usd + reserved + usd > budget) + throw new Stop("budget", `budget $${budget} reached ($${spend.usd.toFixed(4)} spent)`); reserved += usd; }; // `effort` overrides the binding's for cheap follow-ups such as repairs. - async function generate({ role, stage, prompt, schema, estimate = 0, effort, tally, bypassCache = false }) { + async function generate({ + role, + stage, + prompt, + schema, + estimate = 0, + effort, + tally, + bypassCache = false, + }) { const b = bindings[role]; if (!b) throw new Stop("binding", `no binding for ${role}`); effort ??= b.effort; const key = callKey({ stage, binding: { ...b, effort }, prompt, schema }); const hit = bypassCache ? null : store.cacheGet(key); if (hit) { - (spend.byRole[role] ??= { calls: 0, cached: 0, inputTokens: 0, outputTokens: 0, usd: 0 }).cached++; + (spend.byRole[role] ??= { calls: 0, cached: 0, inputTokens: 0, outputTokens: 0, usd: 0 }) + .cached++; if (tally) tally.cached++; onResult?.({ ...hit, role, cached: true }); return hit.output; @@ -173,24 +245,64 @@ export function makeCaller({ clients, store, run, bindings, budget = null, spend let r; const started = Date.now(); try { - r = await clients.generate({ provider: b.provider, model: b.model, effort, prompt, schema: b.provider === "codex" && schema ? strictSchema(schema) : schema }); + r = await clients.generate({ + provider: b.provider, + model: b.model, + effort, + prompt, + schema: b.provider === "codex" && schema ? strictSchema(schema) : schema, + }); } catch (err) { if (err instanceof Stop) throw err; - store.ledger({ run, stage, role, key, attempt, ok: false, error: String(err.message).slice(0, 500) }); - if (FATAL.test(err.message)) throw new Stop("binding", `${role} binding ${b.provider}:${b.model} is unavailable: ${err.message}`); + store.ledger({ + run, + stage, + role, + key, + attempt, + ok: false, + error: String(err.message).slice(0, 500), + }); + if (FATAL.test(err.message)) + throw new Stop( + "binding", + `${role} binding ${b.provider}:${b.model} is unavailable: ${err.message}`, + ); continue; } // A frozen model that now resolves to another is unavailable, not a substitute. if (r.model && b.model && r.model !== b.model) { const paid = Math.max(costOf(r.model, r.usage) ?? 0, r.usage?.costUsd ?? 0); - store.ledger({ run, stage, role, key, attempt, ok: false, model: r.model, usage: r.usage, usd: paid, error: `model ${r.model} ran instead of ${b.model}` }); + store.ledger({ + run, + stage, + role, + key, + attempt, + ok: false, + model: r.model, + usage: r.usage, + usd: paid, + error: `model ${r.model} ran instead of ${b.model}`, + }); account(spend, role, r.usage, paid, r.model); - throw new Stop("binding", `${role} is frozen to ${b.model} but ${r.model} ran; resume when ${b.model} is available`); + throw new Stop( + "binding", + `${role} is frozen to ${b.model} but ${r.model} ran; resume when ${b.model} is available`, + ); } // Token prices can miss requests a reply needed; Claude's own total covers them. const usd = Math.max(costOf(r.model || b.model, r.usage) ?? 0, r.usage?.costUsd ?? 0); const output = b.provider === "codex" ? dropNulls(r.output) : r.output; - const result = { stage, role, model: r.model || b.model, output, usage: r.usage, usd, ms: Date.now() - started }; + const result = { + stage, + role, + model: r.model || b.model, + output, + usage: r.usage, + usd, + ms: Date.now() - started, + }; store.ledger({ run, key, attempt, ok: true, ...result, output: undefined }); store.cachePut(key, result); account(spend, role, r.usage, usd, r.model || b.model); @@ -216,7 +328,13 @@ export function makeCaller({ clients, store, run, bindings, budget = null, spend if (hit) out.set(item.id, hit.answers); else todo.push({ ...item, key }); } - (spend.byRole.decide ??= { calls: 0, cached: 0, inputTokens: 0, outputTokens: 0, usd: 0 }).cached += items.length - todo.length; + (spend.byRole.decide ??= { + calls: 0, + cached: 0, + inputTokens: 0, + outputTokens: 0, + usd: 0, + }).cached += items.length - todo.length; for (let attempt = 1; attempt <= 2 && todo.some((t) => !out.has(t.id)); attempt++) { const pending = todo.filter((t) => !out.has(t.id)); for (let k = 0; k < pending.length; k += JEV_ITEMS) { @@ -225,16 +343,41 @@ export function makeCaller({ clients, store, run, bindings, budget = null, spend reserve(est); let res; try { - res = await clients.evaluateBatch({ items: chunk.map((t) => ({ id: t.id, model: b.model, state: t.state, questions: t.questions })), concurrency: 8, budgetMs: 60000 }); + res = await clients.evaluateBatch({ + items: chunk.map((t) => ({ + id: t.id, + model: b.model, + state: t.state, + questions: t.questions, + })), + concurrency: 8, + budgetMs: 60000, + }); } catch (err) { - if (/\b40[13]\b|credential|api key|TYPESAFE/i.test(err.message)) throw new Stop("credential", `Jev is unavailable (${err.message.slice(0, 200)}); set up the TypeSafe key and resume, or pass --abandon and start an unscreened run (--unscreened) over a small window`); + if (/\b40[13]\b|credential|api key|TYPESAFE/i.test(err.message)) + throw new Stop( + "credential", + `Jev is unavailable (${err.message.slice(0, 200)}); set up the TypeSafe key and resume, or pass --abandon and start an unscreened run (--unscreened) over a small window`, + ); res = { items: [], error: err.message }; } finally { reserved -= est; } - const usage = { inputTokens: res.usage?.input_tokens ?? 0, outputTokens: res.usage?.output_tokens ?? 0 }; + const usage = { + inputTokens: res.usage?.input_tokens ?? 0, + outputTokens: res.usage?.output_tokens ?? 0, + }; const usd = costOf(b.model, usage); - store.ledger({ run, stage, role: "decide", attempt, ok: true, items: chunk.length, usage, usd }); + store.ledger({ + run, + stage, + role: "decide", + attempt, + ok: true, + items: chunk.length, + usage, + usd, + }); account(spend, "decide", usage, usd); const byId = new Map((res.items ?? []).map((it) => [it.id, it])); for (const t of chunk) { @@ -244,8 +387,21 @@ export function makeCaller({ clients, store, run, bindings, budget = null, spend store.cachePut(t.key, { stage, answers: it.response.answers }); continue; } - store.ledger({ run, stage, role: "decide", key: t.key, attempt, ok: false, status: it?.status ?? "missing", error: String(it?.error ?? res.error ?? "").slice(0, 300) }); - if ([401, 402, 403].includes(it?.statusCode)) throw new Stop("credential", `TypeSafe returned HTTP ${it.statusCode}; set up the TypeSafe key and resume, or pass --abandon and start an unscreened run (--unscreened) over a small window`); + store.ledger({ + run, + stage, + role: "decide", + key: t.key, + attempt, + ok: false, + status: it?.status ?? "missing", + error: String(it?.error ?? res.error ?? "").slice(0, 300), + }); + if ([401, 402, 403].includes(it?.statusCode)) + throw new Stop( + "credential", + `TypeSafe returned HTTP ${it.statusCode}; set up the TypeSafe key and resume, or pass --abandon and start an unscreened run (--unscreened) over a small window`, + ); } } } @@ -261,7 +417,8 @@ function addTally(t, usage, usd, ms) { t.calls++; t.usd += usd ?? 0; t.ms += ms; - for (const [k, v] of Object.entries(usage ?? {})) if (typeof v === "number") t.usage[k] = (t.usage[k] ?? 0) + v; + for (const [k, v] of Object.entries(usage ?? {})) + if (typeof v === "number") t.usage[k] = (t.usage[k] ?? 0) + v; } const SEVERITY = { failed: 1, budget: 2, binding: 3, credential: 3, error: 4 }; @@ -281,7 +438,8 @@ export async function pool(items, n, fn) { await fn(items[k], k); } catch (err) { const reason = err instanceof Stop ? err.reason : "error"; - if (!stop || SEVERITY[reason] > SEVERITY[stop instanceof Stop ? stop.reason : "error"]) stop = err; + if (!stop || SEVERITY[reason] > SEVERITY[stop instanceof Stop ? stop.reason : "error"]) + stop = err; if (reason !== "failed") halted = true; } } diff --git a/pkg/app/cli/init/testdata/compounding/clients.test.mjs b/pkg/app/cli/init/testdata/compounding/clients.test.mjs new file mode 100644 index 000000000..2f580e74e --- /dev/null +++ b/pkg/app/cli/init/testdata/compounding/clients.test.mjs @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; + +const { rzmClients } = await import( + new URL("../../templates/starters/compounding/module/scripts/lib/calls.mjs", import.meta.url) +); + +function earlyExitClient(t, code, output) { + const dir = mkdtempSync(join(tmpdir(), "sm-client-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + // Node runs this extensionless CommonJS fixture as `node agent evaluate-batch`. + writeFileSync( + join(dir, "agent"), + ` +const { closeSync } = require("node:fs"); +closeSync(0); +process.${code ? "stderr" : "stdout"}.write(${JSON.stringify(output + "\n")}, () => process.exit(${code})); +`, + ); + return rzmClients(process.execPath, { cwd: dir }); +} + +// Exceed the pipe capacity so closing stdin deterministically interrupts a write. +const request = { text: "x".repeat(2 << 20) }; + +test("an early CLI rejection retains its stderr while request input is pending", async (t) => { + const client = earlyExitClient( + t, + 1, + JSON.stringify({ error: "TypeSafe request failed: HTTP 401 unauthorized" }), + ); + await assert.rejects( + client.evaluateBatch(request), + /evaluate-batch: TypeSafe request failed: HTTP 401 unauthorized/, + ); +}); + +test("an early successful CLI reply retains its result while request input is pending", async (t) => { + const client = earlyExitClient(t, 0, JSON.stringify({ results: [] })); + assert.deepEqual(await client.evaluateBatch(request), { results: [] }); +}); diff --git a/pkg/app/cli/init/testdata/compounding/task.test.mjs b/pkg/app/cli/init/testdata/compounding/task.test.mjs index eccac90c9..031afec68 100644 --- a/pkg/app/cli/init/testdata/compounding/task.test.mjs +++ b/pkg/app/cli/init/testdata/compounding/task.test.mjs @@ -8,7 +8,15 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { test } from "node:test"; -import { SESSIONS, fakeClients, fakeDiscover, session, statuses, tempRepo, turn } from "./fakes.mjs"; +import { + SESSIONS, + fakeClients, + fakeDiscover, + session, + statuses, + tempRepo, + turn, +} from "./fakes.mjs"; const scripts = new URL("../../templates/starters/compounding/module/scripts/", import.meta.url); const { repoMatcher } = await import(new URL("sessions.mjs", scripts)); @@ -16,7 +24,9 @@ const { mine } = await import(new URL("mine.mjs", scripts)); const { check, MIN_EPISODES } = await import(new URL("task-check.mjs", scripts)); const { episodesFor } = await import(new URL("lib/episodes.mjs", scripts)); const tmp = (prefix) => mkdtempSync(join(tmpdir(), prefix)); -const noWindows = { skip: process.platform === "win32" && "the fake rzm is a script with a shebang" }; +const noWindows = { + skip: process.platform === "win32" && "the fake rzm is a script with a shebang", +}; test("discovery skips sessions run under .rhizome/task-state, even when the remote matches", () => { const root = tempRepo(); @@ -25,22 +35,44 @@ test("discovery skips sessions run under .rhizome/task-state, even when the remo const remote = "https://github.com/example/app"; assert.ok(m.matches(join(root, "pkg"), null)); assert.ok(m.matches("/elsewhere/clone", remote)); - for (const cwd of [join(root, ".rhizome/task-state/worktrees/compounding_mine-1"), join(root, ".rhizome/task-state/checkout"), "/home/me/.config/rhizome/task-state/0123abcd/worktrees/x"]) { + for (const cwd of [ + join(root, ".rhizome/task-state/worktrees/compounding_mine-1"), + join(root, ".rhizome/task-state/checkout"), + "/home/me/.config/rhizome/task-state/0123abcd/worktrees/x", + ]) { assert.equal(m.matches(cwd, null), false, cwd); assert.equal(m.matches(cwd, remote), false, cwd); } }); // Each fake dry run is what mine.mjs returns in that situation. -const credentials = (configured) => async () => ({ configured, source: configured ? "direct" : "none" }); -const stoppedRun = (reason) => ({ status: "estimate", episodes: 9, open: { run: "r1", status: "stopped", stoppedReason: reason, stoppedMessage: `${reason} message` } }); +const credentials = (configured) => async () => ({ + configured, + source: configured ? "direct" : "none", +}); +const stoppedRun = (reason) => ({ + status: "estimate", + episodes: 9, + open: { + run: "r1", + status: "stopped", + stoppedReason: reason, + stoppedMessage: `${reason} message`, + }, +}); test("the check reports, in order: no credential, a blocked run, a run to resume, new episodes", async () => { let dryRuns = 0; const dry = (r) => async () => (dryRuns++, r); - await assert.rejects(check({ credentials: credentials(false), dryRun: dry(stoppedRun("budget")) }), /no TypeSafe credential/); + await assert.rejects( + check({ credentials: credentials(false), dryRun: dry(stoppedRun("budget")) }), + /no TypeSafe credential/, + ); assert.equal(dryRuns, 0, "a missing credential is reported before state is read"); - await assert.rejects(check({ credentials: credentials(true), dryRun: dry(stoppedRun("budget")) }), /run r1 stopped \(budget\): budget message; .*--abandon/); + await assert.rejects( + check({ credentials: credentials(true), dryRun: dry(stoppedRun("budget")) }), + /run r1 stopped \(budget\): budget message; .*--abandon/, + ); // A run stopped for a credential or a binding that is available again // resumes rather than waiting on a person. for (const reason of ["credential", "binding"]) { @@ -48,39 +80,93 @@ test("the check reports, in order: no credential, a blocked run, a run to resume assert.deepEqual([r.needed, r.summary], [true, "resume mining run r1"], reason); } // A resumed run whose frozen binding is gone comes back as a dry-run stop. - await assert.rejects(check({ credentials: credentials(true), dryRun: dry({ status: "stopped", reason: "binding", message: "verify: claude is not signed in", run: "r2" }) }), /run r2 stopped \(binding\)/); - for (const open of [{ run: "r3", status: "open" }, { run: "r3", status: "stopped", stoppedReason: "failed", stoppedMessage: "verify k1: bad" }]) { - const r = await check({ credentials: credentials(true), dryRun: dry({ status: "estimate", episodes: 0, open }) }); + await assert.rejects( + check({ + credentials: credentials(true), + dryRun: dry({ + status: "stopped", + reason: "binding", + message: "verify: claude is not signed in", + run: "r2", + }), + }), + /run r2 stopped \(binding\)/, + ); + for (const open of [ + { run: "r3", status: "open" }, + { run: "r3", status: "stopped", stoppedReason: "failed", stoppedMessage: "verify k1: bad" }, + ]) { + const r = await check({ + credentials: credentials(true), + dryRun: dry({ status: "estimate", episodes: 0, open }), + }); assert.deepEqual([r.needed, r.summary], [true, "resume mining run r3"]); } - const fresh = await check({ credentials: credentials(true), dryRun: dry({ status: "estimate", episodes: MIN_EPISODES, discovery: { inWindow: 2 } }) }); - assert.deepEqual([fresh.needed, fresh.summary], [true, `${MIN_EPISODES} new session episodes to mine`]); - assert.equal((await check({ credentials: credentials(true), dryRun: dry({ status: "estimate", episodes: MIN_EPISODES - 1 }) })).needed, false); - assert.equal((await check({ credentials: credentials(true), dryRun: dry({ status: "nothing-new" }) })).needed, false); + const fresh = await check({ + credentials: credentials(true), + dryRun: dry({ status: "estimate", episodes: MIN_EPISODES, discovery: { inWindow: 2 } }), + }); + assert.deepEqual( + [fresh.needed, fresh.summary], + [true, `${MIN_EPISODES} new session episodes to mine`], + ); + assert.equal( + ( + await check({ + credentials: credentials(true), + dryRun: dry({ status: "estimate", episodes: MIN_EPISODES - 1 }), + }) + ).needed, + false, + ); + assert.equal( + (await check({ credentials: credentials(true), dryRun: dry({ status: "nothing-new" }) })) + .needed, + false, + ); }); test("the task check resumes a real count-deferred pool without new episodes", async () => { const root = tempRepo(); const state = tmp("sm-state-"); - const opts = { root, state, harness: "claude", discover: fakeDiscover([SESSIONS.s1]), log: () => {} }; + const opts = { + root, + state, + harness: "claude", + discover: fakeDiscover([SESSIONS.s1]), + log: () => {}, + }; const deferred = await mine({ ...opts, budget: 5, verifyBudget: 0 }, fakeClients()); assert.equal(deferred.status, "deferred"); for (const harness of ["claude", undefined]) { const clients = fakeClients({ status: [statuses()[0], { ...statuses()[0], kind: "codex" }] }); const dryRun = await mine({ ...opts, harness, budget: null }, clients); assert.equal(dryRun.episodes, 0); - if (!harness) assert.equal(dryRun.estimate, null, "both signed-in harnesses leave the estimate unbound"); + if (!harness) + assert.equal(dryRun.estimate, null, "both signed-in harnesses leave the estimate unbound"); assert.ok(dryRun.verification?.pending > 0, "unbound discovery must still report the backlog"); const result = await check({ credentials: credentials(true), dryRun: async () => dryRun }); - assert.deepEqual([result.needed, result.summary], [true, `${dryRun.verification.pending} clusters await evidence verification`]); - assert.equal(clients.calls.generate + clients.calls.evaluate, 0, "the task check spends nothing"); + assert.deepEqual( + [result.needed, result.summary], + [true, `${dryRun.verification.pending} clusters await evidence verification`], + ); + assert.equal( + clients.calls.generate + clients.calls.evaluate, + 0, + "the task check spends nothing", + ); } }); test("a dry run names an open run and why it stopped, and counts episodes without a harness", async () => { const repo = tempRepo(); const state = tmp("sm-state-"); - const opts = { root: repo, state, discover: fakeDiscover([SESSIONS.s1, SESSIONS.s2]), log: () => {} }; + const opts = { + root: repo, + state, + discover: fakeDiscover([SESSIONS.s1, SESSIONS.s2]), + log: () => {}, + }; // Both CLIs signed in and no --harness: still a count, and no model call. const both = fakeClients({ status: [statuses()[0], { ...statuses()[0], kind: "codex" }] }); const unbound = await mine({ ...opts, budget: null }, both); @@ -92,12 +178,23 @@ test("a dry run names an open run and why it stopped, and counts episodes withou const stopped = await mine({ ...opts, harness: "claude", budget: 0.03 }, fakeClients()); assert.deepEqual([stopped.status, stopped.reason], ["stopped", "budget"]); const dry = await mine({ ...opts, harness: "claude", budget: null }, fakeClients()); - assert.deepEqual(dry.open, { run: stopped.run, status: "stopped", stoppedReason: "budget", stoppedMessage: stopped.message }); + assert.deepEqual(dry.open, { + run: stopped.run, + status: "stopped", + stoppedReason: "budget", + stoppedMessage: stopped.message, + }); // A task run's worktree is gone by the time the run resumes: the resume // verifies in the checkout it runs from. const manifest = join(state, "runs", stopped.run, "manifest.json"); - writeFileSync(manifest, JSON.stringify({ ...JSON.parse(readFileSync(manifest, "utf8")), checkout: join(tmp("sm-gone-"), "removed-worktree") })); + writeFileSync( + manifest, + JSON.stringify({ + ...JSON.parse(readFileSync(manifest, "utf8")), + checkout: join(tmp("sm-gone-"), "removed-worktree"), + }), + ); await mine({ ...opts, harness: "claude", budget: 0.03 }, fakeClients()); assert.equal(JSON.parse(readFileSync(manifest, "utf8")).checkout, repo); }); @@ -129,7 +226,10 @@ function sandbox() { const home = join(dir, "home"); mkdirSync(home); // Discovery reads these homes, so the real ones are never read. - return { dir, env: { ...process.env, RZM: fakeRzm(dir), CLAUDE_CONFIG_DIR: home, CODEX_HOME: home } }; + return { + dir, + env: { ...process.env, RZM: fakeRzm(dir), CLAUDE_CONFIG_DIR: home, CODEX_HOME: home }, + }; } test("--task-mode needs a budget, and a credential stop exits 4 with its reason", noWindows, () => { @@ -137,8 +237,27 @@ test("--task-mode needs a budget, and a credential stop exits 4 with its reason" const repo = tempRepo(); const file = join(dir, "episodes.jsonl"); const s = session("t1", [turn(1, "alpha"), turn(2, "beta")], "2026-10-10T10:00:00Z"); - writeFileSync(file, episodesFor(s, s.family, { through: s.completeThrough }).episodes.map((e) => JSON.stringify(e) + "\n").join("")); - const mineCli = (...args) => spawnSync(process.execPath, [fileURLToPath(new URL("mine.mjs", scripts)), "--harness", "claude", "--state", join(dir, "state"), "--episodes", file, ...args], { cwd: repo, encoding: "utf8", env }); + writeFileSync( + file, + episodesFor(s, s.family, { through: s.completeThrough }) + .episodes.map((e) => JSON.stringify(e) + "\n") + .join(""), + ); + const mineCli = (...args) => + spawnSync( + process.execPath, + [ + fileURLToPath(new URL("mine.mjs", scripts)), + "--harness", + "claude", + "--state", + join(dir, "state"), + "--episodes", + file, + ...args, + ], + { cwd: repo, encoding: "utf8", env }, + ); const unbudgeted = mineCli("--task-mode"); assert.notEqual(unbudgeted.status, 0); @@ -149,19 +268,32 @@ test("--task-mode needs a budget, and a credential stop exits 4 with its reason" assert.match(r.stderr, /mining stopped \(credential\): Jev is unavailable/); assert.equal(JSON.parse(r.stdout).reason, "credential"); // Outside task mode the same stop keeps exit 3. - assert.equal(mineCli("--budget", "1").status, 3); + const result = mineCli("--budget", "1"); + assert.equal(result.status, 3, result.stderr); }); -test("the check script prints its JSON, and exits 1 with the reason when Jev has no credential", noWindows, () => { - const { env } = sandbox(); - const repo = tempRepo(); - writeFileSync(join(repo, ".gitignore"), ".rhizome/\n"); - const checkCli = (source) => spawnSync(process.execPath, [fileURLToPath(new URL("task-check.mjs", scripts))], { cwd: repo, encoding: "utf8", env: { ...env, FAKE_TYPESAFE_SOURCE: source } }); - const missing = checkCli("none"); - assert.equal(missing.status, 1); - assert.equal(missing.stdout, ""); - assert.match(missing.stderr, /no TypeSafe credential/); - const quiet = checkCli("team"); - assert.equal(quiet.status, 0, quiet.stderr); - assert.deepEqual(JSON.parse(quiet.stdout), { needed: false, summary: "no new session episodes" }); -}); +test( + "the check script prints its JSON, and exits 1 with the reason when Jev has no credential", + noWindows, + () => { + const { env } = sandbox(); + const repo = tempRepo(); + writeFileSync(join(repo, ".gitignore"), ".rhizome/\n"); + const checkCli = (source) => + spawnSync(process.execPath, [fileURLToPath(new URL("task-check.mjs", scripts))], { + cwd: repo, + encoding: "utf8", + env: { ...env, FAKE_TYPESAFE_SOURCE: source }, + }); + const missing = checkCli("none"); + assert.equal(missing.status, 1); + assert.equal(missing.stdout, ""); + assert.match(missing.stderr, /no TypeSafe credential/); + const quiet = checkCli("team"); + assert.equal(quiet.status, 0, quiet.stderr); + assert.deepEqual(JSON.parse(quiet.stdout), { + needed: false, + summary: "no new session episodes", + }); + }, +); diff --git a/pkg/app/tasks/runner_unix_test.go b/pkg/app/tasks/runner_unix_test.go index ace95ae0f..8f78c4e2d 100644 --- a/pkg/app/tasks/runner_unix_test.go +++ b/pkg/app/tasks/runner_unix_test.go @@ -4,14 +4,18 @@ package tasks import ( "context" + "io" "os" "os/exec" "path/filepath" "strconv" "strings" + "sync" "syscall" "testing" "time" + + "github.com/stretchr/testify/require" ) func TestCheckTimeoutKillsTheWholeTree(t *testing.T) { @@ -57,26 +61,75 @@ func TestCheckTimeoutWithAnEscapedDescendantReleasesTheLock(t *testing.T) { } } -// A check that starts a child in a session of its own just before its -// timeout must not leave that child running. -func TestCheckTimeoutKillsALateOwnSessionChild(t *testing.T) { - shellAvailable(t) - if _, err := exec.LookPath("python3"); err != nil { - t.Skip("needs python3 to call setsid") +// Drive deadline expiry after readiness; the configured elapsed timeout is +// covered by TestCheckTimeoutKillsTheWholeTree. +type checkDeadlineContext struct { + context.Context + waiting chan struct{} + expired chan struct{} + once sync.Once +} + +func (c *checkDeadlineContext) Done() <-chan struct{} { + c.once.Do(func() { close(c.waiting) }) + return c.expired +} + +func (c *checkDeadlineContext) Err() error { + select { + case <-c.expired: + return context.DeadlineExceeded + default: + return nil } +} + +func TestCheckTimeoutKillsALateOwnSessionChild(t *testing.T) { + python, err := exec.LookPath("python3") + require.NoError(t, err) pidFile := filepath.Join(t.TempDir(), "pid") - check := "name: Late\nevery: 1d\ntimeout: 1s\ncheck:\n command: [sh, -c, 'sleep 0.5; python3 -c \"import os,subprocess; p=subprocess.Popen([\\\"sleep\\\",\\\"300\\\"], start_new_session=True); open(\\\"" + pidFile + "\\\",\\\"w\\\").write(str(p.pid)); p.wait()\"']\nprompt: x\n" - dir := newRepo(t, map[string]string{"late.yml": check}) - svc := newService(t, dir, &fakeAgent{}, "auto") - s, _ := svc.RunDue(context.Background()) - if len(s.Outcomes) != 1 || s.Outcomes[0].Outcome != OutcomeFailed { - t.Fatalf("expected the check to time out: %+v", s) + input, trigger, err := os.Pipe() + require.NoError(t, err) + defer input.Close() + defer trigger.Close() + cmd := exec.Command(python, "-c", `import subprocess, sys +sys.stdin.readline() +p = subprocess.Popen(["sleep", "300"], start_new_session=True) +with open(sys.argv[1], "w") as f: + f.write(str(p.pid)) +p.wait() +`, pidFile) + cmd.Stdin = input + ctx := &checkDeadlineContext{Context: context.Background(), waiting: make(chan struct{}), expired: make(chan struct{})} + expire := sync.OnceFunc(func() { close(ctx.expired) }) + done := make(chan struct{}) + var runErr error + go func() { + _, runErr = runBounded(ctx, cmd, io.Discard) + close(done) + }() + t.Cleanup(func() { expire(); <-done }) + // Run observes cancellation only after its initial process-tree snapshot. + select { + case <-ctx.waiting: + case <-done: + t.Fatalf("check exited before waiting for its deadline: %v", runErr) } - data, err := os.ReadFile(pidFile) - if err != nil { - t.Fatal(err) - } - pid, _ := strconv.Atoi(strings.TrimSpace(string(data))) + _, err = trigger.Write([]byte("\n")) + require.NoError(t, err) + var pid int + require.Eventually(t, func() bool { + data, err := os.ReadFile(pidFile) + if err != nil { + return false + } + pid, err = strconv.Atoi(string(data)) + return err == nil && pid > 0 + }, 5*time.Second, time.Millisecond, "fixture did not publish its own-session child") + require.NoError(t, syscall.Kill(pid, 0), "child must exist before the deadline") + expire() + <-done + require.ErrorIs(t, runErr, context.DeadlineExceeded) deadline := time.Now().Add(3 * time.Second) for syscall.Kill(pid, 0) == nil { if time.Now().After(deadline) { diff --git a/pkg/app/web/assets/dist/index.html b/pkg/app/web/assets/dist/index.html index 3f48c8e04..9e7e24b13 100644 --- a/pkg/app/web/assets/dist/index.html +++ b/pkg/app/web/assets/dist/index.html @@ -38,12 +38,15 @@ } catch (error) {} })(); - + - + + + + - +
diff --git a/pkg/app/web/file_tree.go b/pkg/app/web/file_tree.go index 04750260c..d6d253021 100644 --- a/pkg/app/web/file_tree.go +++ b/pkg/app/web/file_tree.go @@ -57,10 +57,6 @@ func (s *Server) listTree(ctx context.Context, rel string, limit int) (TreeRespo Lang: lang, HasChildren: candidate.isDir && s.dirHasChildren(entryRel), }) - if len(out.Entries) >= limit { - out.Truncated = true - break - } } sort.SliceStable(out.Entries, func(i, j int) bool { @@ -69,6 +65,11 @@ func (s *Server) listTree(ctx context.Context, rel string, limit int) (TreeRespo } return out.Entries[i].Name < out.Entries[j].Name }) + if len(out.Entries) > limit { + out.Omitted = len(out.Entries) - limit + out.Truncated = true + out.Entries = out.Entries[:limit] + } return out, nil } diff --git a/pkg/app/web/file_tree_overflow_test.go b/pkg/app/web/file_tree_overflow_test.go new file mode 100644 index 000000000..9017c7b87 --- /dev/null +++ b/pkg/app/web/file_tree_overflow_test.go @@ -0,0 +1,34 @@ +package web + +import ( + "fmt" + "github.com/atomicobject/rhizome/internal/testkit" + "github.com/atomicobject/rhizome/pkg/vault/obsidian" + "github.com/stretchr/testify/require" + "os" + "path/filepath" + "testing" +) + +func TestTreeCountsEligibleOmissions(t *testing.T) { + root := t.TempDir() + catalog, err := NewFileCatalog(obsidian.VaultDefinition{Path: root}, nil, testkit.NoteMetadataIndexer(t)) + require.NoError(t, err) + s := &Server{cfg: Config{VaultPath: root}, catalog: catalog} + for i := 0; i < 201; i++ { + require.NoError(t, os.WriteFile(filepath.Join(root, fmt.Sprintf("file%03d.go", i)), nil, 0600)) + } + page, err := s.listTree(t.Context(), "", 200) + require.NoError(t, err) + require.Len(t, page.Entries, 200) + require.True(t, page.Truncated) + require.Equal(t, 1, page.Omitted) + all, err := s.listTree(t.Context(), "", 400) + require.NoError(t, err) + require.Len(t, all.Entries, 201) + require.False(t, all.Truncated) + require.Zero(t, all.Omitted) + exact, err := s.listTree(t.Context(), "", 201) + require.NoError(t, err) + require.False(t, exact.Truncated) +} diff --git a/pkg/app/web/graph.go b/pkg/app/web/graph.go index 41e9e216e..774ff110d 100644 --- a/pkg/app/web/graph.go +++ b/pkg/app/web/graph.go @@ -327,6 +327,8 @@ func (s *Server) buildLocalGraphRefUncached(ctx context.Context, ref ontology.No } nodes, edgeList, graphDiagnostics, err := s.buildGraphWithNodeRead(ctx, noderead.GraphRequest{ Sources: []ontology.NodeRef{ref}, + NodeLimit: -1, + EdgeLimit: -1, Profile: profile, Limit: limit, IncludeCodeEdges: !notesOnly, @@ -350,7 +352,17 @@ func (s *Server) buildLocalGraphRefUncached(ctx context.Context, ref ontology.No resp := GraphResponse{CenterID: centerID, Diagnostics: graphDiagnostics} s.attachGraphScores(ctx, nodes) s.attachGraphTypes(ctx, nodes) - resp.Nodes, resp.Edges, resp.Truncated = finalizeGraph(nodes, edgeList, limit, notesOnly) + resp.Nodes, resp.Edges, resp.OmittedNodes, resp.OmittedEdges = limitLocalGraph(nodes, edgeList, centerID, limit) + retained := make(map[string]bool, len(resp.Nodes)) + for _, node := range resp.Nodes { + retained[node.ID] = true + } + for _, node := range sortedNodes(nodes) { + if !retained[node.ID] && len(resp.OmittedNodeIDs) < defaultLocalNodeLimit { + resp.OmittedNodeIDs = append(resp.OmittedNodeIDs, node.ID) + } + } + resp.Truncated = resp.OmittedNodes > 0 || resp.OmittedEdges > 0 return resp, nil } diff --git a/pkg/app/web/graph_local_limit.go b/pkg/app/web/graph_local_limit.go new file mode 100644 index 000000000..4b7f49243 --- /dev/null +++ b/pkg/app/web/graph_local_limit.go @@ -0,0 +1,39 @@ +package web + +// limitLocalGraph reserves the focus and admits neighbours in edge priority order. +func limitLocalGraph(nodes map[string]GraphNode, edges []GraphEdge, center string, limit int) ([]GraphNode, []GraphEdge, int, int) { + retained := map[string]GraphNode{} + if node, ok := nodes[center]; ok { + retained[center] = node + } + orderedEdges := sortedEdgeSlice(edges) + for _, edge := range orderedEdges { + needed := 0 + if _, ok := retained[edge.Source]; !ok { + needed++ + } + if _, ok := retained[edge.Target]; !ok { + needed++ + } + if len(retained)+needed > limit { + continue + } + retained[edge.Source] = nodes[edge.Source] + retained[edge.Target] = nodes[edge.Target] + } + for _, node := range sortedNodes(nodes) { + if len(retained) >= limit { + break + } + retained[node.ID] = node + } + outEdges := make([]GraphEdge, 0, len(edges)) + for _, edge := range orderedEdges { + _, sourceOK := retained[edge.Source] + _, targetOK := retained[edge.Target] + if sourceOK && targetOK { + outEdges = append(outEdges, edge) + } + } + return sortedNodes(retained), outEdges, len(nodes) - len(retained), len(edges) - len(outEdges) +} diff --git a/pkg/app/web/graph_overflow_test.go b/pkg/app/web/graph_overflow_test.go new file mode 100644 index 000000000..4bc220a06 --- /dev/null +++ b/pkg/app/web/graph_overflow_test.go @@ -0,0 +1,47 @@ +package web + +import ( + "encoding/json" + "fmt" + "path/filepath" + "testing" + + "github.com/atomicobject/rhizome/internal/testkit" + codeanchor "github.com/atomicobject/rhizome/pkg/anchors" + "github.com/atomicobject/rhizome/pkg/ontology" + semdb "github.com/atomicobject/rhizome/pkg/store" + "github.com/atomicobject/rhizome/pkg/vault/obsidian" + "github.com/stretchr/testify/require" +) + +func TestLocalGraphCountsThousandNeighbours(t *testing.T) { + root := t.TempDir() + store, err := semdb.Open(filepath.Join(root, "db.sqlite")) + require.NoError(t, err) + t.Cleanup(func() { _ = store.Close() }) + ctx := t.Context() + anchor := func(id, path string) []codeanchor.IntelAnchor { + return []codeanchor.IntelAnchor{{AnchorID: id, Path: path, Lang: codeanchor.LangGo, Kind: "function", Symbol: id, FQN: id, Fingerprint: id}} + } + require.NoError(t, store.ReplaceIntelCodeFile(ctx, "center.go", anchor("center", "center.go"), nil, nil)) + for i := 0; i < 1000; i++ { + id := fmt.Sprintf("neighbour%03d", i) + path := id + ".go" + require.NoError(t, store.ReplaceIntelCodeFile(ctx, path, anchor(id, path), []codeanchor.IntelEdge{{SrcID: id, DstID: "center", Kind: "calls"}}, nil)) + } + runtime := &Runtime{} + runtime.SetIntelStore(store) + s := &Server{runtime: runtime, cfg: Config{VaultPath: root, VaultDef: obsidian.VaultDefinition{Path: root}}, noteMetadata: testkit.NoteMetadataIndexer(t)} + graph, err := s.buildLocalGraphRefMode(ctx, ontology.NodeRef{NotePath: "center.go", Kind: ontology.NodeKind("code")}, 200, 1, false, false) + require.NoError(t, err) + require.True(t, graph.Truncated) + require.Len(t, graph.Nodes, 200) + require.Equal(t, 801, graph.OmittedNodes) + require.Equal(t, 801, graph.OmittedEdges) + require.Len(t, graph.Edges, 199) + require.Len(t, graph.OmittedNodeIDs, 200) + payload, err := json.Marshal(graph) + require.NoError(t, err) + require.NotContains(t, string(payload), `"omittedLinks"`) + requireGraphNode(t, graph, "code:center.go", "code") +} diff --git a/pkg/app/web/openapi.yaml b/pkg/app/web/openapi.yaml index 5cb036a7b..5b111f956 100644 --- a/pkg/app/web/openapi.yaml +++ b/pkg/app/web/openapi.yaml @@ -2446,6 +2446,7 @@ components: items: $ref: "#/components/schemas/TreeEntry" truncated: { type: boolean } + omitted: { type: integer } RelatedNote: type: object required: [path] @@ -2602,6 +2603,12 @@ components: items: $ref: "#/components/schemas/GraphEdge" truncated: { type: boolean } + omittedNodeIDs: + type: array + maxItems: 200 + items: { type: string } + omittedNodes: { type: integer } + omittedEdges: { type: integer } centerID: { type: string } needsIndex: { type: boolean } diagnostics: diff --git a/pkg/app/web/query_recipe_gate_test.go b/pkg/app/web/query_recipe_gate_test.go new file mode 100644 index 000000000..ce893e6db --- /dev/null +++ b/pkg/app/web/query_recipe_gate_test.go @@ -0,0 +1,75 @@ +package web + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/atomicobject/rhizome/pkg/ontology/queryrecipe" + "github.com/stretchr/testify/require" +) + +func TestPublicQueryRecipeExecutionChoosesPreparedQueryGate(t *testing.T) { + fixture := prepareOntologyFixtureVault(t) + recipeDir := filepath.Join(fixture.root, ".rhizome", "query-recipes") + require.NoError(t, os.MkdirAll(recipeDir, 0o755)) + writeRecipe := func(name, id, selection string) { + t.Helper() + body := fmt.Sprintf(`apiVersion: rhizome.query-recipe.v1 +id: %s +name: %s +problem: Verify prepared-query readiness routing. +inputSpec: + mode: required_anchor + primaryInput: path + inputs: + - name: path + required: true + kind: path +query: + graphQL: | + query RecipeRead($path: String!) { + note(path: $path) { %s } + } +outputContract: + expectedPaths: [note.path] + empty: No note found. +adaptationGuidance: + summary: Use the selected note. +`, id, name, selection) + require.NoError(t, os.WriteFile(filepath.Join(recipeDir, id+".yaml"), []byte(body), 0o644)) + } + writeRecipe("Exact note recipe", "exact-note-recipe", "path title") + writeRecipe("Type-dependent note recipe", "typed-note-recipe", "__typename path") + + runtime := &Runtime{IntelStore: fixture.intelStore} + runtime.EnableIndexGate() + // An unavailable gate fails immediately; this test checks routing, not elapsed time. + runtime.indexReady = nil + runtime.MarkNoteReadReady() + srv := newFixtureServer(t, fixture, runtime) + require.False(t, runtime.IndexReady()) + + exactReq := newApplicationRequest(http.MethodPost, "/api/v1/query-recipes/exact-note-recipe/execute", bytes.NewBufferString(`{"inputs":{"path":"specs/100-demo/plan.md"}}`)) + exactReq.Header.Set("Content-Type", "application/json") + exactRes := httptest.NewRecorder() + srv.Handler().ServeHTTP(exactRes, exactReq) + require.Equal(t, http.StatusOK, exactRes.Code) + var exactRun queryrecipe.RunResult + require.NoError(t, json.Unmarshal(exactRes.Body.Bytes(), &exactRun)) + require.Empty(t, exactRun.Result.Errors) + require.Equal(t, "specs/100-demo/plan.md", exactRun.Result.Data["note"].(map[string]any)["path"]) + + typedReq := newApplicationRequest(http.MethodPost, "/api/v1/query-recipes/typed-note-recipe/execute", bytes.NewBufferString(`{"inputs":{"path":"specs/100-demo/plan.md"}}`)) + typedReq.Header.Set("Content-Type", "application/json") + typedRes := httptest.NewRecorder() + srv.Handler().ServeHTTP(typedRes, typedReq) + require.Equal(t, http.StatusServiceUnavailable, typedRes.Code) + require.Equal(t, "5", typedRes.Header().Get("Retry-After")) + require.Contains(t, typedRes.Body.String(), PublicErrorIndexInitializing) +} diff --git a/pkg/app/web/server_integration_test.go b/pkg/app/web/server_integration_test.go index 5c593ed1c..a57fec625 100644 --- a/pkg/app/web/server_integration_test.go +++ b/pkg/app/web/server_integration_test.go @@ -41,7 +41,6 @@ import ( "sync" "testing" "testing/fstest" - "testing/synctest" "time" ) @@ -292,69 +291,6 @@ adaptationGuidance: require.NotEmpty(t, details["issues"]) } -func TestPublicQueryRecipeExecutionChoosesPreparedQueryGate(t *testing.T) { - fixture := prepareOntologyFixtureVault(t) - recipeDir := filepath.Join(fixture.root, ".rhizome", "query-recipes") - require.NoError(t, os.MkdirAll(recipeDir, 0o755)) - writeRecipe := func(name, id, selection string) { - t.Helper() - body := fmt.Sprintf(`apiVersion: rhizome.query-recipe.v1 -id: %s -name: %s -problem: Verify prepared-query readiness routing. -inputSpec: - mode: required_anchor - primaryInput: path - inputs: - - name: path - required: true - kind: path -query: - graphQL: | - query RecipeRead($path: String!) { - note(path: $path) { %s } - } -outputContract: - expectedPaths: [note.path] - empty: No note found. -adaptationGuidance: - summary: Use the selected note. -`, id, name, selection) - require.NoError(t, os.WriteFile(filepath.Join(recipeDir, id+".yaml"), []byte(body), 0o644)) - } - writeRecipe("Exact note recipe", "exact-note-recipe", "path title") - writeRecipe("Type-dependent note recipe", "typed-note-recipe", "__typename path") - - // Advance the deadline only once the selected readiness gate blocks. - synctest.Test(t, func(t *testing.T) { - runtime := &Runtime{IntelStore: fixture.intelStore} - runtime.EnableIndexGate() - runtime.MarkNoteReadReady() - srv := newFixtureServer(t, fixture, runtime) - require.False(t, runtime.IndexReady()) - - exactReq := newApplicationRequest(http.MethodPost, "/api/v1/query-recipes/exact-note-recipe/execute", bytes.NewBufferString(`{"inputs":{"path":"specs/100-demo/plan.md"}}`)) - exactReq.Header.Set("Content-Type", "application/json") - exactRes := httptest.NewRecorder() - srv.Handler().ServeHTTP(exactRes, exactReq) - require.Equal(t, http.StatusOK, exactRes.Code) - var exactRun queryrecipe.RunResult - require.NoError(t, json.Unmarshal(exactRes.Body.Bytes(), &exactRun)) - require.Empty(t, exactRun.Result.Errors) - require.Equal(t, "specs/100-demo/plan.md", exactRun.Result.Data["note"].(map[string]any)["path"]) - - typedReq := newApplicationRequest(http.MethodPost, "/api/v1/query-recipes/typed-note-recipe/execute", bytes.NewBufferString(`{"inputs":{"path":"specs/100-demo/plan.md"}}`)) - typedReq.Header.Set("Content-Type", "application/json") - typedCtx, typedCancel := context.WithTimeout(typedReq.Context(), 10*time.Millisecond) - defer typedCancel() - typedRes := httptest.NewRecorder() - srv.Handler().ServeHTTP(typedRes, typedReq.WithContext(typedCtx)) - require.Equal(t, http.StatusServiceUnavailable, typedRes.Code) - require.Equal(t, "5", typedRes.Header().Get("Retry-After")) - require.Contains(t, typedRes.Body.String(), PublicErrorIndexInitializing) - }) -} - func TestPublicConfiguredViews(t *testing.T) { t.Parallel() diff --git a/pkg/app/web/types.go b/pkg/app/web/types.go index c089443b7..4daea35f1 100644 --- a/pkg/app/web/types.go +++ b/pkg/app/web/types.go @@ -225,12 +225,15 @@ type SearchMatch struct { // GraphResponse provides nodes/edges for visualization. type GraphResponse struct { - Nodes []GraphNode `json:"nodes"` - Edges []GraphEdge `json:"edges"` - Truncated bool `json:"truncated,omitempty"` - CenterID string `json:"centerID,omitempty"` - NeedsIndex bool `json:"needsIndex,omitempty"` - Diagnostics *noderead.GraphDiagnostics `json:"diagnostics,omitempty"` + OmittedNodeIDs []string `json:"omittedNodeIDs,omitempty"` + OmittedNodes int `json:"omittedNodes,omitempty"` + OmittedEdges int `json:"omittedEdges,omitempty"` + Nodes []GraphNode `json:"nodes"` + Edges []GraphEdge `json:"edges"` + Truncated bool `json:"truncated,omitempty"` + CenterID string `json:"centerID,omitempty"` + NeedsIndex bool `json:"needsIndex,omitempty"` + Diagnostics *noderead.GraphDiagnostics `json:"diagnostics,omitempty"` } // GraphNode represents a graph node (note, code, or module). @@ -273,6 +276,7 @@ type GraphEdge struct { // TreeResponse provides children for a directory. type TreeResponse struct { + Omitted int `json:"omitted,omitempty"` Path string `json:"path"` Entries []TreeEntry `json:"entries"` Truncated bool `json:"truncated,omitempty"` diff --git a/pkg/embedindex/display_title_test.go b/pkg/embedindex/display_title_test.go new file mode 100644 index 000000000..da9211ab5 --- /dev/null +++ b/pkg/embedindex/display_title_test.go @@ -0,0 +1,29 @@ +package embedindex + +import ( + "strings" + "testing" + "time" + + "github.com/atomicobject/rhizome/pkg/ontology" + "github.com/stretchr/testify/require" +) + +func TestFullDisplayLabelDoesNotChangeEmbeddingText(t *testing.T) { + title := "Review the complete native desktop workflow " + strings.Repeat("including its keyboard shortcuts ", 5) + content := "- [ ] " + title + " #action-item\n" + snapshot, err := ontology.BuildDocumentSnapshot("meeting.md", content, time.Time{}) + require.NoError(t, err) + span := ontology.ParseMarkdownListSourceSpans("meeting.md", content)[0] + projection := &ontology.NodeProjection{Snapshot: snapshot, Ref: ontology.NodeRef{NotePath: "meeting.md", NodeID: span.ID, Kind: ontology.NodeKindEmbedded}} + current, err := ontology.IntelOntologyNodeForProjection(nil, projection, nil, 1) + require.NoError(t, err) + require.Equal(t, strings.TrimSpace(title), current.DisplayLabel) + previous := current + previous.DisplayLabel = span.Title + chunker := ontologyNodeChunker{} + before := chunker.nodeBodyText(projection, previous, nil, content, false) + after := chunker.nodeBodyText(projection, current, nil, content, false) + require.Equal(t, before, after) + require.Equal(t, 1, strings.Count(after, title)) +} diff --git a/pkg/harness/internal/jsonstdio/transport_test.go b/pkg/harness/internal/jsonstdio/transport_test.go index ef2b3e5a5..a44327864 100644 --- a/pkg/harness/internal/jsonstdio/transport_test.go +++ b/pkg/harness/internal/jsonstdio/transport_test.go @@ -54,32 +54,37 @@ func TestProtocolFailureReturnsWhileChildKeepsStderrOpen(t *testing.T) { } } +type startedWriter struct { + io.Writer + started chan struct{} +} + +func (w startedWriter) Write(p []byte) (int, error) { + close(w.started) + return w.Writer.Write(p) +} + func TestCloseInterruptsBlockedWriteAndReapsChild(t *testing.T) { connection, _ := startChild(t, "blocked-write") ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _, err := connection.Recv(ctx) require.NoError(t, err) + started := make(chan struct{}) + connection.stdin = startedWriter{Writer: connection.stdin, started: started} written := make(chan error, 1) go func() { written <- connection.Send(context.Background(), json.RawMessage(`"`+strings.Repeat("x", 1<<20)+`"`)) }() + <-started select { case err := <-written: t.Fatalf("fixture accepted the oversized write: %v", err) - case <-time.After(20 * time.Millisecond): - } - ctx, cancelClose := context.WithTimeout(context.Background(), 300*time.Millisecond) - defer cancelClose() - started := time.Now() - require.NoError(t, connection.Close(ctx)) - require.Less(t, time.Since(started), 450*time.Millisecond) - select { - case err := <-written: - require.Error(t, err) - case <-time.After(time.Second): - t.Fatal("blocked write survived Close") + default: } + // Check interruption and reaping, independently of process enumeration speed. + require.NoError(t, connection.Close(context.Background())) + require.Error(t, <-written) select { case <-connection.Exited(): default: @@ -116,9 +121,9 @@ func TestImmediateDecodeFailureHasInitializedProcessIdentity(t *testing.T) { _, err := connection.Recv(ctx) cancel() require.ErrorIs(t, err, harness.ErrDecode) - closeCtx, cancelClose := context.WithTimeout(context.Background(), 300*time.Millisecond) - require.NoError(t, connection.Close(closeCtx)) - cancelClose() + // This checks identity initialization; process enumeration is not a latency contract. + require.NoError(t, connection.process.Kill()) + require.NoError(t, connection.Close(context.Background())) } } diff --git a/pkg/harness/internal/jsonstdio/transport_unix_test.go b/pkg/harness/internal/jsonstdio/transport_unix_test.go index 587769410..a601fa1fb 100644 --- a/pkg/harness/internal/jsonstdio/transport_unix_test.go +++ b/pkg/harness/internal/jsonstdio/transport_unix_test.go @@ -40,9 +40,8 @@ func TestCloseKillsGrandchildren(t *testing.T) { }, time.Second, time.Millisecond) require.NoError(t, syscall.Kill(pid, 0), "grandchild should be running before Close") - closeCtx, cancelClose := context.WithTimeout(context.Background(), 300*time.Millisecond) - defer cancelClose() - require.NoError(t, connection.Close(closeCtx)) + // Verify descendant cleanup without imposing a process-enumeration deadline. + require.NoError(t, connection.Close(context.Background())) require.Eventually(t, func() bool { return errors.Is(syscall.Kill(pid, 0), syscall.ESRCH) }, 2*time.Second, 10*time.Millisecond, "grandchild %d survived Close", pid) diff --git a/pkg/ontology/display_title.go b/pkg/ontology/display_title.go new file mode 100644 index 000000000..000791ddf --- /dev/null +++ b/pkg/ontology/display_title.go @@ -0,0 +1,30 @@ +package ontology + +import ( + ontoschema "github.com/atomicobject/rhizome/pkg/ontology/schema" + "strings" +) + +// Display titles are independent of the capped titles and ITEM_SUMMARY used by embeddings. +func sourceSpanDisplayTitle(content string, span *MarkdownSourceSpan) string { + if span.Shape != ontoschema.EmbeddedSourceShapeListItem && span.Shape != ontoschema.EmbeddedSourceShapeCheckboxItem { + return strings.TrimSpace(span.Title) + } + headline := sourceSpanItemHeadline(content, span.ContentRange, span.Markers) + if title, _, ok := splitTitledItemHeadline(headline); ok { + return title + } + if headline != "" { + return headline + } + return strings.TrimSpace(span.Title) +} + +func nodeCatalogDisplayLabel(projection *NodeProjection) string { + if projection != nil && projection.Snapshot != nil && projection.Ref.Kind == NodeKindEmbedded { + if span := projection.Snapshot.SourceSpansByID[projection.Ref.NodeID]; span != nil { + return sourceSpanDisplayTitle(projection.Snapshot.Content, span) + } + } + return nodeCatalogTitle(projection) +} diff --git a/pkg/ontology/display_title_test.go b/pkg/ontology/display_title_test.go new file mode 100644 index 000000000..f9877ebe7 --- /dev/null +++ b/pkg/ontology/display_title_test.go @@ -0,0 +1,37 @@ +package ontology + +import ( + "github.com/stretchr/testify/require" + "strings" + "testing" + "time" +) + +func TestDisplayTitlePreservesEmbeddingInputs(t *testing.T) { + title := "Review the complete native desktop workflow " + strings.Repeat("and its keyboard shortcuts ", 5) + "before publishing" + content := "- [ ] " + title + " #action-item\n assignee:: Drew\n" + spans := ParseMarkdownListSourceSpans("meeting.md", content) + require.Len(t, spans, 1) + span := spans[0] + require.Equal(t, strings.TrimSpace(title[:80]), span.Title) + require.Equal(t, title, sourceSpanDisplayTitle(content, span)) + itemTitle, summary, detail := sourceSpanItemParts(content, span) + require.Empty(t, itemTitle) + require.Equal(t, strings.TrimSpace(title[:80]), summary) + require.Empty(t, detail) + require.Equal(t, content, span.Content) + snapshot, err := BuildDocumentSnapshot("meeting.md", content, time.Time{}) + require.NoError(t, err) + projection := &NodeProjection{Snapshot: snapshot, Ref: NodeRef{NotePath: "meeting.md", NodeID: span.ID, Kind: NodeKindEmbedded}} + row, err := IntelOntologyNodeForProjection(nil, projection, nil, 1) + require.NoError(t, err) + require.Equal(t, span.Title, row.Title) + require.Equal(t, title, row.DisplayLabel) + require.Equal(t, title, nodeProjectionTitle(projection)) +} + +func TestDisplayTitlePreservesHeadingLabel(t *testing.T) { + snapshot, err := BuildDocumentSnapshot("meeting.md", "### Validation story\n\nBody\n", time.Time{}) + require.NoError(t, err) + require.Equal(t, "Validation story", sourceSpanDisplayTitle(snapshot.Content, snapshot.SourceSpans[0])) +} diff --git a/pkg/ontology/materialization.go b/pkg/ontology/materialization.go index cad498da7..2f6a5a235 100644 --- a/pkg/ontology/materialization.go +++ b/pkg/ontology/materialization.go @@ -30,7 +30,8 @@ import ( // type resolution; scalar and metadata-link normalization use one contract. // Alias retirement invalidates unresolved dependencies before old aliases vanish. // v16: note titles derived from an H1 drop a trailing Obsidian block ID. -const OntologyMaterializationVersion = 16 +// v17: embedded display labels retain the full headline without changing indexed titles or fields. +const OntologyMaterializationVersion = 17 // ErrFutureOntologyMaterialization means the persisted ontology projection was // produced by a newer materializer than this binary understands. diff --git a/pkg/ontology/node_catalog.go b/pkg/ontology/node_catalog.go index 2c0b1066e..dc1e5091f 100644 --- a/pkg/ontology/node_catalog.go +++ b/pkg/ontology/node_catalog.go @@ -232,7 +232,7 @@ func IntelOntologyNodeForProjection(schema *ontoschema.Schema, projection *NodeP TypeName: ref.TypeName, ParentNodeID: parentID, ParentTypeName: parentType, - Title: displayLabel, + Title: nodeCatalogTitle(projection), SourceLocator: sourceLocator, Fragment: fragment, BlockID: blockID, @@ -403,7 +403,7 @@ func nodeCatalogFragments(projection *NodeProjection) (string, string) { return fragment, blockID } -func nodeCatalogDisplayLabel(projection *NodeProjection) string { +func nodeCatalogTitle(projection *NodeProjection) string { if projection == nil { return "" } diff --git a/pkg/ontology/node_workspace.go b/pkg/ontology/node_workspace.go index 5af665d7a..eaf5ebe46 100644 --- a/pkg/ontology/node_workspace.go +++ b/pkg/ontology/node_workspace.go @@ -355,7 +355,7 @@ func nodeProjectionTitle(projection *NodeProjection) string { // already extracted by the parser; surface it here so views and // workspaces don't fall through to the host file's basename. if span := projection.Snapshot.SourceSpansByID[projection.Ref.NodeID]; span != nil { - return strings.TrimSpace(span.Title) + return sourceSpanDisplayTitle(projection.Snapshot.Content, span) } } return "" diff --git a/pkg/validate/repair_lock_wait_test.go b/pkg/validate/repair_lock_wait_test.go index a4da1b690..32a4f0a66 100644 --- a/pkg/validate/repair_lock_wait_test.go +++ b/pkg/validate/repair_lock_wait_test.go @@ -4,6 +4,7 @@ import ( "context" "os" "path/filepath" + "strings" "testing" "time" @@ -53,7 +54,8 @@ func TestRepairWaiterRecoversExpiredPriority(t *testing.T) { return false } for _, request := range requests { - if request.Name() == entries[0].Name() { + // Wait for the final request, not its temporary publication file. + if request.Name() == entries[0].Name() || !strings.HasSuffix(request.Name(), ".json") { return false } } diff --git a/services/team-api/cmd/team-api/stack_test.go b/services/team-api/cmd/team-api/stack_test.go index 5bf9b0940..362370e79 100644 --- a/services/team-api/cmd/team-api/stack_test.go +++ b/services/team-api/cmd/team-api/stack_test.go @@ -52,6 +52,10 @@ func TestDevStack(t *testing.T) { if err := json.NewDecoder(resp.Body).Decode(&out); err != nil || resp.StatusCode != http.StatusOK { t.Fatalf("embed: status %d, %v", resp.StatusCode, err) } + // JSON can arrive before settlement; HTTP EOF follows the handler's return. + if _, err := io.Copy(io.Discard, resp.Body); err != nil { + t.Fatalf("finish embed response: %v", err) + } resp.Body.Close() if len(out.Data) != 2 || len(out.Data[0].Embedding) != 1024 || out.Usage.TotalTokens == 0 { t.Fatalf("embed response: %d vectors, %d dims, %d tokens", len(out.Data), len(out.Data[0].Embedding), out.Usage.TotalTokens) diff --git a/services/team-api/internal/traffic/settlement_test.go b/services/team-api/internal/traffic/settlement_test.go new file mode 100644 index 000000000..ec6760bfb --- /dev/null +++ b/services/team-api/internal/traffic/settlement_test.go @@ -0,0 +1,57 @@ +package traffic + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/atomicobject/rhizome/pkg/teamapi/wire" + "github.com/atomicobject/rhizome/services/team-api/internal/ledger" +) + +type pausedSettlement struct { + ledger.Ledger + entered, release chan struct{} +} + +func (l *pausedSettlement) Settle(ctx context.Context, sub, key string, outcome ledger.Outcome, credits int64, dollars ...int64) error { + close(l.entered) + <-l.release + return l.Ledger.Settle(ctx, sub, key, outcome, credits, dollars...) +} + +func TestStreamSettlementCompletesBeforeEOF(t *testing.T) { + // Larger than the HTTP write buffer, so JSON reaches the client before + // the handler returns. Settlement is held by an event, never a sleep. + h := newHarness(t, opts{voyage: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"data":"`+strings.Repeat("x", 32<<10)+`","usage":{"total_tokens":10}}`) + })}) + l := &pausedSettlement{Ledger: h.tr.ledger, entered: make(chan struct{}), release: make(chan struct{})} + h.tr.ledger = l + var release sync.Once + unblock := func() { release.Do(func() { close(l.release) }) } + defer unblock() + req, err := http.NewRequest(http.MethodPost, h.gw.URL+wire.RouteVoyageEmbed, strings.NewReader(voyageBody("x"))) + require.NoError(t, err) + req.Header.Set("X-Test-Sub", "alice") + req.Header.Set(wire.HeaderIdempotencyKey, key(1)) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer resp.Body.Close() + require.Equal(t, http.StatusOK, resp.StatusCode) + var body json.RawMessage + require.NoError(t, json.NewDecoder(resp.Body).Decode(&body)) + <-l.entered + // Decoding JSON alone does not wait for settlement. + require.Equal(t, wire.CodeInProgress, h.voyage("alice", key(1), voyageBody("x")).code()) + unblock() + _, err = io.Copy(io.Discard, resp.Body) + require.NoError(t, err) + require.Equal(t, wire.CodeResultLost, h.voyage("alice", key(1), voyageBody("x")).code()) +} diff --git a/web/CONTEXT.md b/web/CONTEXT.md index 5c4e41e2d..a5dc262fb 100644 --- a/web/CONTEXT.md +++ b/web/CONTEXT.md @@ -78,7 +78,7 @@ Reconciled on 2026-11-04 with [[docs/efforts/2026-11-04-15-30-workbench-design-h ## Theme and fonts -- Colors come from `src/tokens.css` (light plus `prefers-color-scheme: dark`). Canvas renderers (Sigma graphs) cannot read CSS variables, so they resolve token values through `resolveCssColor` and repaint on `subscribeColorScheme` (`lib/themeColors.ts`) without re-running layout; never put color literals in renderer code. Type colours use one twelve-hue assignment (`lib/typePalette.ts`, consumed by `lib/typeAccent.ts` and the kit): concrete types in name order, types with records first; interfaces, code, collapsed groups, and untyped notes use `--type-8`. Unknown names fall back to a hash. +- Colors come from `src/tokens.css` (light plus `prefers-color-scheme: dark`). Canvas renderers (Sigma graphs) cannot read CSS variables, so they resolve token values through `resolveCssColor` and repaint on `subscribeColorScheme` (`lib/themeColors.ts`) without re-running layout; never put color literals in renderer code. Type colours use one twelve-hue assignment (`lib/typePalette.ts`, consumed by `lib/typeAccent.ts` and the kit): concrete types in name order, types with records first; interfaces share their most represented implementor; untyped notes and collapsed groups use `--type-8`; code retains its separate graph colour. Unknown names fall back to a hash. - GraphiQL takes HSL copies of the tokens in `base.css`; change them with the tokens. Syntax highlighting (highlight.js and the editor) maps onto `--syntax-*`. - `src/fonts.css` declares the self-hosted families from `public/fonts`; the kit theme embeds the same file, so custom-view frames make no third-party font requests. - `formatTypeName` is for URL slugs only; display text uses `useTypeLabel` or `humanizeName`. diff --git a/web/bundled-views/group/briefing-activity.tsx b/web/bundled-views/group/briefing-activity.tsx index 86f51b104..3d5f163b6 100644 --- a/web/bundled-views/group/briefing-activity.tsx +++ b/web/bundled-views/group/briefing-activity.tsx @@ -6,6 +6,7 @@ import { Fragment, useMemo, useState, type ReactNode } from "react"; import { recentChanges, type Boundary, type ChangeMoment, type MotionEntry } from "./activity.ts"; import { Block, MoreToggle, counted, lower, memberOf, plural } from "./briefing-parts.tsx"; +import { commonMotionMetadata } from "./briefing-motion.tsx"; import { RecordMark, openRecord } from "./components.tsx"; import { useRememberedOpen } from "./remembered.ts"; import { @@ -34,6 +35,8 @@ export function MotionList({ const expanded = useRememberedOpen("briefing.expanded"); const open = expanded.isOpen("in-motion", false); const shown = open ? entries : entries.slice(0, 8); + const metadata = useMotionMetadata(model, entries); + const lines = shown.map(({ record }) => recordLine(model, record)); const mixed = new Set( @@ -47,13 +50,23 @@ export function MotionList({ return ( <>