@lysyi3m/sidecar 1.7.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -84,8 +84,15 @@ export function applyItemEvent(items, e, askOf) {
84
84
  item.status = decisionState(e) === "planned" ? "planned" : "addressed";
85
85
  }
86
86
  }
87
- /** An item's status under a review budget: a decision past the budget is left for the user. */
88
- export const itemStatus = (item, budget) => item.status === "addressed" && item.reviewTurns >= budget ? "exhausted" : item.status;
87
+ /**
88
+ * An item's status under a review budget. A point awaiting review or reopened once its reviews are
89
+ * spent is left for the user: no further review can settle it.
90
+ */
91
+ export const itemStatus = (item, budget) => (item.status === "addressed" || item.status === "reopened") && item.reviewTurns >= budget
92
+ ? "exhausted"
93
+ : item.status;
94
+ /** Whether a point's reviews are spent: a decision on it now is never reviewed. */
95
+ export const reviewsSpent = (item, budget) => item.reviewTurns >= budget;
89
96
  /** Items whose latest decision awaits the navigator's review, oldest decision first. */
90
97
  export function awaitingReview(items, budget) {
91
98
  return [...items.values()]
@@ -132,6 +132,10 @@ const BRAND_MARK = raw('<svg viewBox="0 0 18 18" class="brand-mark" aria-hidden=
132
132
  const SIDEBAR_ICON = raw('<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M2.5 3.5h11v9h-11zM6 3.5v9"/></svg>');
133
133
  /** A tray with an arrow into it: save. */
134
134
  const EXPORT_ICON = raw('<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2.5v7.5M5 7l3 3 3-3M2.5 10.5v2.5h11v-2.5"/></svg>');
135
+ /** The sidebar's sections, in the order they appear. */
136
+ export const SECTIONS = ["active", "closed"];
137
+ /** The sections a browser that has never toggled one sees collapsed. */
138
+ export const DEFAULT_COLLAPSED = new Set(["closed"]);
135
139
  /** The page around its content: the sidebar with the case list, and the main column. */
136
140
  function shell(opts) {
137
141
  return html `<!doctype html>
@@ -148,7 +152,7 @@ function shell(opts) {
148
152
  <div class="shell${opts.chrome.collapsed ? " is-collapsed" : ""}">
149
153
  <aside class="sidebar">
150
154
  <div class="sidebar-head"><a class="brand" href="/">${BRAND_MARK}sidecar</a><span class="brand-version">v${SIDECAR_VERSION}</span></div>
151
- ${sideList(opts.cases, opts.activeCase)}
155
+ ${sideList(opts.cases, opts.activeCase, opts.chrome.sections)}
152
156
  </aside>
153
157
  <main class="main"><div class="page">
154
158
  <div class="topbar"><button class="icon-button sidebar-toggle" type="button" aria-label="Toggle the case list" data-toggle-sidebar>${SIDEBAR_ICON}</button><div class="crumbs">${opts.crumbs}</div>${opts.actions ? html `<div class="topbar-actions">${opts.actions}</div>` : ""}</div>
@@ -159,8 +163,11 @@ ${opts.content}
159
163
  </html>`;
160
164
  }
161
165
  const isUnreadable = (c) => c.state === "unreadable";
162
- /** The sidebar's case list. The page refreshes it from /fragments/sidebar. */
163
- export function sideList(cases, activeCase) {
166
+ /**
167
+ * The sidebar's case list. The page refreshes it from /fragments/sidebar. A section in `collapsed`
168
+ * renders closed, unless it holds the open case.
169
+ */
170
+ export function sideList(cases, activeCase, collapsed = DEFAULT_COLLAPSED) {
164
171
  const open = cases.filter((c) => c.state === "open");
165
172
  // An unreadable case is listed with the closed ones, never hidden.
166
173
  const closed = cases.filter((c) => c.state === "closed" || isUnreadable(c));
@@ -168,27 +175,40 @@ export function sideList(cases, activeCase) {
168
175
  const item = (c) => isUnreadable(c)
169
176
  ? html `<a class="side-case" href="/cases/${c.case_id}"${current(c)}>
170
177
  <div class="side-title">${c.case_id}</div>
171
- <div class="side-meta"><span class="mono">${c.case_id}</span><span class="side-tag">unreadable</span></div>
178
+ <div class="side-meta"><span class="side-tag">unreadable</span></div>
172
179
  </a>`
173
180
  : html `<a class="side-case" href="/cases/${c.case_id}"${current(c)}>
174
181
  <div class="side-title">${c.title || c.case_id}</div>
175
- <div class="side-meta"><span class="mono">${c.case_id}</span><span>${ago(c.updated)}</span>${
176
- // The section heading already says active or closed; only a state worth noticing gets a tag.
177
- c.in_flight ? html `<span class="side-tag is-accent">asking</span>` : ""}</div>
182
+ <div class="side-meta"><span>${ago(c.updated)}</span></div>${
183
+ // A running turn shows as motion, not words: a line sweeps under the entry.
184
+ c.in_flight
185
+ ? html `<span class="side-live" role="img" aria-label="navigator answering"></span>`
186
+ : ""}
178
187
  </a>`;
188
+ const section = (name, label, members) => {
189
+ if (!members.length)
190
+ return "";
191
+ const expanded = !collapsed.has(name) || members.some((c) => c.case_id === activeCase) ? "true" : "false";
192
+ return html `<section class="side-group" data-section="${name}">
193
+ <button class="side-section label" type="button" data-section="${name}" aria-expanded="${expanded}" aria-label="${label}, ${String(members.length)} ${members.length === 1 ? "case" : "cases"}"><span class="chevron" aria-hidden="true"></span>${label}<span class="side-count" aria-hidden="true">${String(members.length)}</span></button>
194
+ <div class="side-group-body">${members.map(item)}</div>
195
+ </section>`;
196
+ };
179
197
  const query = activeCase ? `?active=${activeCase}` : "";
180
- return html `<nav class="side-list" id="side-list" aria-label="Cases" data-refresh="/fragments/sidebar${query}">${cases.length === 0 ? html `<div class="side-empty">No cases yet.</div>` : ""}${open.length ? [html `<div class="side-section label">Active</div>`, ...open.map(item)] : ""}${closed.length ? [html `<div class="side-section label">Closed</div>`, ...closed.map(item)] : ""}</nav>`;
198
+ return html `<nav class="side-list" id="side-list" aria-label="Cases" data-refresh="/fragments/sidebar${query}">${cases.length === 0 ? html `<div class="side-empty">No cases yet.</div>` : ""}${section("active", "Active", open)}${section("closed", "Closed", closed)}</nav>`;
181
199
  }
182
200
  /* ---------------------------------------------------------------- index */
183
- const FILTERS = ["all", "open", "closed"];
201
+ /** The index's state filters, by the case state each shows, with the label the sidebar uses. */
202
+ const FILTERS = ["open", "closed"];
203
+ const FILTER_LABELS = { open: "active", closed: "closed" };
184
204
  export function indexPage(cases, query, chrome = { collapsed: false }) {
185
- const filter = FILTERS.find((f) => f === query.state) ?? "all";
205
+ const filter = FILTERS.find((f) => f === query.state) ?? "open";
186
206
  const content = html `<div class="toolbar">
187
- <div class="segmented" role="group" aria-label="Case state">${FILTERS.map((name) => html `<button type="button" class="label" data-filter="${name}" aria-pressed="${String(filter === name)}">${name} <span data-count></span></button>`)}</div>
207
+ <div class="segmented" role="group" aria-label="Case state">${FILTERS.map((name) => html `<button type="button" class="label" data-filter="${name}" aria-pressed="${String(filter === name)}">${FILTER_LABELS[name]} <span data-count></span></button>`)}</div>
188
208
  <div class="search-group"><input type="search" data-search placeholder="Filter by title, id or directory…" aria-label="Filter cases" value="${query.search ?? ""}"><span class="result-count" data-result-count></span></div>
189
209
  </div>
190
210
  <div class="table-scroll"><table data-cases data-filter-state="${filter}">
191
- <thead><tr><th>Case</th><th class="col-state">State</th><th>Driver</th><th>Navigator</th><th>Last activity</th></tr></thead>
211
+ <thead><tr><th>Case</th><th>Driver</th><th>Navigator</th><th>Last activity</th></tr></thead>
192
212
  ${caseRows(cases)}
193
213
  </table></div>
194
214
  <p class="message" data-message hidden></p>`;
@@ -206,15 +226,15 @@ ${caseRows(cases)}
206
226
  export function caseRows(cases) {
207
227
  return html `<tbody id="case-rows" data-refresh="/fragments/cases">${cases.map((c) => {
208
228
  if (isUnreadable(c)) {
209
- return html `<tr data-href="/cases/${c.case_id}" data-state="unreadable" data-haystack="${c.case_id}">
210
- <td><span class="case-title">${c.case_id}</span><div class="case-sub mono">${c.error}</div></td>
211
- <td class="col-state">${stateChip("unreadable")}</td><td></td><td></td><td></td>
229
+ // Listed under the closed filter, as the sidebar lists it with the closed cases.
230
+ return html `<tr data-href="/cases/${c.case_id}" data-state="closed" data-haystack="${c.case_id}">
231
+ <td><span class="case-title">${c.case_id}</span> ${stateChip("unreadable")}<div class="case-sub mono">${c.error}</div></td>
232
+ <td></td><td></td><td></td>
212
233
  </tr>`;
213
234
  }
214
235
  const haystack = [c.title, c.case_id, c.workspace].join(" ").toLowerCase();
215
236
  return html `<tr data-href="/cases/${c.case_id}" data-state="${c.state}" data-haystack="${haystack}">
216
237
  <td><a class="case-title" href="/cases/${c.case_id}">${c.title || c.case_id}</a><div class="case-sub case-where mono"><span>${c.case_id}</span><span>·</span>${pathLine(c.workspace)}</div></td>
217
- <td class="col-state">${stateChip(c.state)}</td>
218
238
  <td>${driverLine(c.driver, c.driver_model, c.driver_effort)}</td>
219
239
  <td>${agentLine(c.navigator, c.model, c.effort)}</td>
220
240
  <td><div>${ago(c.updated)}</div><div class="case-sub mono">${time(c.updated, "stamp")}</div></td>
@@ -245,25 +265,51 @@ function caseHead(model) {
245
265
  const { state, status, items, caseId } = model;
246
266
  const { opened } = state;
247
267
  const views = [...items.values()];
248
- const flagCount = views.filter((v) => v.item.kind === "flag").length;
249
- const unsettledCount = views.filter((v) => v.status !== "confirmed").length;
250
- const held = views.filter((v) => v.status === "held").length;
251
- // Amber asks for action while the case is in progress; a closed case keeps its counts, plain.
252
- const alert = status === "closed" ? "stat" : "stat is-alert";
253
268
  const opinions = [...state.asks.values()].filter((a) => a.terminal?.kind === "opinion").length;
269
+ const flags = views.filter((v) => v.item.kind === "flag").length;
270
+ const unsettled = views.filter((v) => v.status !== "confirmed").length;
271
+ // Points the agents could not settle between them: the user decides each one.
272
+ const standing = views
273
+ .filter((v) => v.status === "held" || v.status === "exhausted")
274
+ .sort((a, b) => a.item.raisedN - b.item.raisedN)
275
+ .map((v) => v.item.ref);
276
+ const standingRow = standing.length > 0
277
+ ? html `<div class="standing"><span class="label">${standing.length} ${standing.length > 1 ? "standing disagreements" : "standing disagreement"}</span>${standing.map((ref) => refFor(ref, model))}</div>`
278
+ : "";
254
279
  const fact = (name, value) => html `<div class="fact"><dt class="label">${name}</dt><dd>${value}</dd></div>`;
255
280
  return html `<header class="case-head" id="case-head">
256
- <div class="title-row"><span class="case-id mono">${caseId}</span><h1 class="title">${opened.title}</h1>${stateChip(status)}</div>
257
- <div class="case-path mono">${pathLine(opened.workspace)}</div>
258
- <dl class="facts">${[
281
+ <h1 class="title">${opened.title}</h1>
282
+ <div class="case-meta">${stateChip(status)}<div class="case-path case-where mono"><span>${caseId}</span><span>·</span>${pathLine(opened.workspace)}</div></div>
283
+ <dl class="facts${state.inFlight ? " is-live" : ""}">${[
259
284
  fact("Driver", driverLine(opened.driver, state.driverModel, state.driverEffort)),
260
285
  fact("Navigator", agentLine(opened.navigator, opened.model, opened.effort)),
261
286
  fact("Opened", html `<span class="mono">${time(opened.ts, "zoned")}</span>`),
262
287
  fact("Last activity", ago(model.events.at(-1)?.ts)),
263
- ]}</dl>
264
- <div class="stats"><span class="stat"><b>${state.asks.size}</b>asks</span><span class="stat"><b>${opinions}</b>opinions</span><span class="stat"><b>${flagCount}</b>raised flags</span>${unsettledCount > 0 ? html `<span class="${alert}"><b>${unsettledCount}</b>unsettled</span>` : ""}${held > 0 ? html `<span class="${alert}"><b>${held}</b>standing disagreement${held > 1 ? "s" : ""}</span>` : ""}${state.inFlight ? html `<span class="stat"><b>1</b>ask in flight</span>` : ""}</div>
288
+ ]}</dl>${
289
+ // A running turn sweeps along the facts' top rule (app.css); a screen reader hears it instead.
290
+ state.inFlight ? html `<span class="sr-only">Navigator answering</span>` : ""}
291
+ ${shows([
292
+ ["ask", "Asks", state.asks.size],
293
+ ["opinion", "Opinions", opinions],
294
+ ["flag", "Flags", flags],
295
+ // Red, open or closed case alike: the case is not in order until every point is settled.
296
+ ["unsettled", "Unsettled", unsettled],
297
+ ])}
298
+ ${standingRow}
265
299
  </header>`;
266
300
  }
301
+ /**
302
+ * The timeline's filters, with the count each shows, styled as the index's state filters. A filter
303
+ * with nothing to show is left out, and with nothing to filter, so is the control. The page
304
+ * (static/app.js) keeps which one is pressed; the server renders "all", as a page just loaded is.
305
+ */
306
+ function shows(filters) {
307
+ const present = filters.filter(([, , n]) => n > 0);
308
+ if (present.length === 0)
309
+ return "";
310
+ const button = (tag, label) => html `<button type="button" class="label${tag === "unsettled" ? " is-unsettled" : ""}" data-show="${tag}" aria-pressed="${String(tag === "all")}">${label}</button>`;
311
+ return html `<div class="segmented shows" role="group" aria-label="Show in the timeline">${button("all", "All")}${present.map(([tag, label, n]) => button(tag, `${label} ${n}`))}</div>`;
312
+ }
267
313
  function brief(model) {
268
314
  const e = model.state.brief;
269
315
  if (!e)
@@ -323,7 +369,7 @@ function itemState(id, model) {
323
369
  : ""}`;
324
370
  }
325
371
  function entry(e, opts, body) {
326
- return html `<article class="entry${opts.service ? " service" : ""}${opts.notable ? " notable" : ""}" id="${opts.id}">
372
+ return html `<article class="entry${opts.service ? " service" : ""}${opts.notable ? " notable" : ""}" id="${opts.id}"${opts.tags?.length ? html ` data-tags="${opts.tags.join(" ")}"` : ""}>
327
373
  <div class="entry-time mono">${time(e.ts, "clock")}</div>
328
374
  <div class="entry-rail"><span class="marker ${opts.marker}"></span></div>
329
375
  <div class="entry-body">${body}</div>
@@ -356,7 +402,7 @@ function askEntry(e, model) {
356
402
  else {
357
403
  foot = html `<div class="card-foot">${ask?.attempts.length ? "the navigator is working…" : "queued"}</div>`;
358
404
  }
359
- return entry(e, { id: `ask-${String(e.askId)}`, marker: "driver" }, html `<div class="card">
405
+ return entry(e, { id: `ask-${String(e.askId)}`, marker: "driver", tags: ["ask"] }, html `<div class="card">
360
406
  ${cardHead("Driver", model.state.opened.driver, e.review ? "Review request" : "Ask", [html `<span class="mono">${e.askId}</span>`])}
361
407
  <div class="card-text">${e.review
362
408
  ? html `The navigator reviews the decisions awaiting it${targets.length ? html `: ${targets.map((t, i) => html `${i ? ", " : ""}${refFor(t.ref, model)}`)}` : ""}.`
@@ -367,14 +413,21 @@ ${foot}
367
413
  function opinionEntry(e, model) {
368
414
  const askId = String(e.askId);
369
415
  const isReview = model.state.asks.get(askId)?.event.review === true;
370
- const flags = flagsOf(e).map((flag) => html `<div class="flag" id="flag-${flag.id}"><span class="flag-id">${flag.id}</span><div class="flag-text">${prose(flag.body)}</div><div class="flag-status">${severityChip(flag.severity)}${itemState(flag.id, model)}</div></div>`);
416
+ const settled = (id) => model.items.get(id)?.status === "confirmed";
417
+ const points = [...flagsOf(e).map((f) => f.id), ...(model.items.has(askId) ? [askId] : [])];
418
+ const tags = [
419
+ "opinion",
420
+ ...(flagsOf(e).length ? ["flag"] : []),
421
+ ...(points.some((id) => !settled(id)) ? ["unsettled"] : []),
422
+ ];
423
+ const flags = flagsOf(e).map((flag) => html `<div class="flag" id="flag-${flag.id}"${settled(flag.id) ? raw(" data-settled") : ""}><span class="flag-id">${flag.id}</span><div class="flag-text">${prose(flag.body)}</div><div class="flag-status">${severityChip(flag.severity)}${itemState(flag.id, model)}</div></div>`);
371
424
  const limits = Array.isArray(e.limits) ? e.limits : [];
372
425
  const reviews = reviewsOf(e).map((r) => {
373
426
  // A review of a decision since replaced is history: it says nothing about the point now.
374
427
  const applied = model.items.get(r.ref)?.item.reviews.find((h) => h.opinionN === e.n)?.applied ?? false;
375
428
  return html `<div class="flag"><span class="flag-id">${refFor(r.ref, model)}</span><div class="flag-text">${prose(r.body)}</div><div class="flag-status"><span class="chip ${!applied ? "is-quiet" : r.status === "confirmed" ? "is-ok" : "is-alert"}">${r.status}</span>${applied ? "" : html `<span class="dim">of an earlier decision</span>`}</div></div>`;
376
429
  });
377
- return entry(e, { id: `ask-${askId}-opinion`, marker: "navigator" }, html `<div class="card navigator">
430
+ return entry(e, { id: `ask-${askId}-opinion`, marker: "navigator", tags }, html `<div class="card navigator">
378
431
  ${cardHead("Navigator", model.state.opened.navigator, isReview ? "Review" : "Opinion", [html `<span>re</span>`, ref(`#ask-${askId}`, e.askId)])}
379
432
  <div class="verdict"><span class="chip ${VERDICT_CLASS[String(e.verdict)] ?? ""}">${e.verdict}</span>${e.severity !== undefined ? severityChip(e.severity) : ""}${model.items.has(askId) ? itemState(askId, model) : ""}</div>
380
433
  <div class="card-text">${prose(e.body)}</div>
@@ -11,7 +11,7 @@ import { loadConfig } from "../config.js";
11
11
  import { CaseIndex, stampOf, unchanged } from "./cases.js";
12
12
  import { dashboardBase, isLoopbackHost } from "./links.js";
13
13
  import { MARKS } from "./marks.js";
14
- import { caseRows, casePage, caseUnits, indexPage, sideList } from "./pages.js";
14
+ import { caseRows, casePage, caseUnits, DEFAULT_COLLAPSED, indexPage, SECTIONS, sideList, } from "./pages.js";
15
15
  import { caseModel } from "./view.js";
16
16
  // The dashboard: a read-only web UI over the case store. Two pages — the case index at / and one
17
17
  // case at /cases/<id> — rendered on the server (pages.ts) from the view model (view.ts), styled by
@@ -50,6 +50,7 @@ const ASSETS = new Map(readdirSync(STATIC)
50
50
  const COOKIE = "sidecar_token";
51
51
  /** A cookie that keeps UI state is named `sidecar_ui_<name>`. */
52
52
  const SIDEBAR_COOKIE = "sidecar_ui_sidebar";
53
+ const SECTIONS_COOKIE = "sidecar_ui_sections";
53
54
  /** A client's address; a dual-stack listener reports an IPv4 client in its IPv4-mapped form. */
54
55
  const isLoopbackAddress = (address) => isLoopbackHost(address.replace(/^::ffff:(?=[\d.]+$)/i, ""));
55
56
  export async function startDashboard(store, opts = {}) {
@@ -136,6 +137,21 @@ const cookieValue = (header, name) => {
136
137
  * only a script can read: the server renders it, so a page never paints the sidebar open first.
137
138
  */
138
139
  const sidebarCollapsed = (header) => cookieValue(header, SIDEBAR_COOKIE) === "collapsed";
140
+ /**
141
+ * The sidebar sections this browser keeps collapsed: their names joined with `|`. An unknown name
142
+ * is skipped. Without the cookie, the default applies; an empty value collapses none.
143
+ */
144
+ const collapsedSections = (header) => {
145
+ const value = cookieValue(header, SECTIONS_COOKIE);
146
+ if (value === undefined)
147
+ return DEFAULT_COLLAPSED;
148
+ const names = new Set(value.split("|"));
149
+ return new Set(SECTIONS.filter((s) => names.has(s)));
150
+ };
151
+ const chromeOf = (header) => ({
152
+ collapsed: sidebarCollapsed(header),
153
+ sections: collapsedSections(header),
154
+ });
139
155
  /** Constant-time comparison, so response timing does not leak the token. */
140
156
  function same(a, b) {
141
157
  const x = Buffer.from(a);
@@ -192,16 +208,16 @@ function app(store, port, token, limits) {
192
208
  // the stream reports that reason as a `problem` event.
193
209
  const exists = (caseId) => isCaseId(caseId) && existsSync(store.logPath(caseId));
194
210
  const NO_CASE = "no such case";
195
- web.get("/", async (c) => htmlResponse(indexPage((await cases.list()).cases, { state: c.req.query("state"), search: c.req.query("search") }, { collapsed: sidebarCollapsed(c.req.header("cookie")) })));
211
+ web.get("/", async (c) => htmlResponse(indexPage((await cases.list()).cases, { state: c.req.query("state"), search: c.req.query("search") }, chromeOf(c.req.header("cookie")))));
196
212
  web.get("/cases/:id", async (c) => {
197
213
  const caseId = c.req.param("id");
198
214
  if (!exists(caseId))
199
215
  return c.text(NO_CASE, 404);
200
- return htmlResponse(casePage(caseModel(caseId, await store.read(caseId), reviewBudget(store)), (await cases.list()).cases, { collapsed: sidebarCollapsed(c.req.header("cookie")) }));
216
+ return htmlResponse(casePage(caseModel(caseId, await store.read(caseId), reviewBudget(store)), (await cases.list()).cases, chromeOf(c.req.header("cookie"))));
201
217
  });
202
218
  web.get("/fragments/sidebar", (c) => {
203
219
  const active = c.req.query("active");
204
- return fragmentResponse(c, (list) => sideList(list.cases, active && isCaseId(active) ? active : null));
220
+ return fragmentResponse(c, (list) => sideList(list.cases, active && isCaseId(active) ? active : null, collapsedSections(c.req.header("cookie"))));
205
221
  });
206
222
  web.get("/fragments/cases", (c) => fragmentResponse(c, (list) => caseRows(list.cases)));
207
223
  web.get("/assets/agents/:name{[a-z0-9-]+\\.svg}", (c) => {
@@ -15,8 +15,10 @@
15
15
  --ink-2: light-dark(#4e5766, #a3adbb);
16
16
  --ink-3: light-dark(#8b94a1, #6e7784);
17
17
  --accent: light-dark(#1f4fd8, #8aa6ff);
18
+ --accent-weak: light-dark(#e8eefc, #16203a);
18
19
  --alert: light-dark(#9a3412, #e0a165);
19
20
  --alert-weak: light-dark(#fdf3ec, #221a12);
21
+ --danger: light-dark(#b42318, #f08a80);
20
22
  --ok: light-dark(#2f6b3f, #8cc79c);
21
23
  --ok-weak: light-dark(#eef6f0, #121c16);
22
24
 
@@ -139,12 +141,55 @@ button {
139
141
  min-width: var(--sidebar);
140
142
  }
141
143
 
144
+ /* A section head is a button that reads like a label: a chevron, the name and the case count. */
142
145
  .side-section {
146
+ display: flex;
147
+ align-items: center;
148
+ gap: 6px;
149
+ width: 100%;
143
150
  padding: 14px 16px 6px;
151
+ border: 0;
152
+ border-radius: 0;
153
+ background: none;
144
154
  color: var(--ink-3);
155
+ text-align: left;
156
+
157
+ &:hover {
158
+ color: var(--ink-2);
159
+ }
160
+
161
+ &:focus-visible {
162
+ outline: 2px solid var(--accent);
163
+ outline-offset: -2px;
164
+ }
165
+
166
+ & .chevron {
167
+ flex: none;
168
+ width: 5px;
169
+ height: 5px;
170
+ margin: 0 3px 2px 1px;
171
+ border-right: 1.5px solid currentColor;
172
+ border-bottom: 1.5px solid currentColor;
173
+ rotate: 45deg;
174
+ }
175
+
176
+ &[aria-expanded="false"] .chevron {
177
+ rotate: -45deg;
178
+ margin-bottom: 0;
179
+ }
180
+
181
+ & .side-count {
182
+ font-weight: 400;
183
+ letter-spacing: 0;
184
+ }
185
+
186
+ &[aria-expanded="false"] + .side-group-body {
187
+ display: none;
188
+ }
145
189
  }
146
190
 
147
191
  .side-case {
192
+ position: relative;
148
193
  display: block;
149
194
  padding: 8px 16px 8px 14px;
150
195
  border-left: 2px solid transparent;
@@ -154,12 +199,23 @@ button {
154
199
  background: var(--hair);
155
200
  }
156
201
 
202
+ /* The open case: an accent bar and tint, and its meta line at full ink. */
157
203
  &[aria-current="page"] {
158
- background: var(--bg);
159
- border-left-color: var(--ink);
204
+ background: var(--accent-weak);
205
+ border-left-color: var(--accent);
206
+
207
+ & .side-meta {
208
+ color: var(--ink);
209
+ }
160
210
  }
161
211
  }
162
212
 
213
+ /* A link's text takes the accent on hover. A row that is a link colours its title. */
214
+ .side-case:hover .side-title,
215
+ tbody tr:hover .case-title {
216
+ color: var(--accent);
217
+ }
218
+
163
219
  .side-title {
164
220
  display: -webkit-box;
165
221
  -webkit-line-clamp: 2;
@@ -358,10 +414,6 @@ h1.title {
358
414
  letter-spacing: 0.06em;
359
415
  text-transform: uppercase;
360
416
  color: var(--ink-2);
361
-
362
- &.is-accent {
363
- color: var(--accent);
364
- }
365
417
  }
366
418
 
367
419
  /* ---------------------------------------------------------------- toolbar */
@@ -488,10 +540,6 @@ tbody tr {
488
540
  font-weight: 500;
489
541
  letter-spacing: -0.01em;
490
542
  text-decoration: none;
491
-
492
- &:hover {
493
- color: var(--accent);
494
- }
495
543
  }
496
544
 
497
545
  .case-sub {
@@ -500,11 +548,6 @@ tbody tr {
500
548
  color: var(--ink-3);
501
549
  }
502
550
 
503
- /* Under the open or closed filter every row has the same state, so the column says nothing. */
504
- table:not([data-filter-state="all"]) .col-state {
505
- display: none;
506
- }
507
-
508
551
  /* The case column takes the width the other columns leave. */
509
552
  tbody td:first-child {
510
553
  width: 100%;
@@ -582,25 +625,14 @@ tbody td:first-child {
582
625
  .case-head {
583
626
  display: flex;
584
627
  flex-direction: column;
585
- gap: 14px;
586
- }
587
-
588
- .title-row {
589
- display: flex;
590
- align-items: flex-start;
591
628
  gap: 12px;
592
629
 
593
- & .chip {
594
- margin-top: 6px;
630
+ /* The brief reads as the header's last row: the same gap, not the page's. */
631
+ & + .brief {
632
+ margin-top: calc(12px - var(--page-gap));
595
633
  }
596
634
  }
597
635
 
598
- .case-id {
599
- margin-top: 7px;
600
- font-size: 12px;
601
- color: var(--ink-3);
602
- }
603
-
604
636
  /* An agent's mark sits on the text baseline and takes the surrounding ink: its file is a mask over
605
637
  the text colour, so one cached file serves every theme. */
606
638
  .agent-mark {
@@ -620,17 +652,33 @@ tbody td:first-child {
620
652
  white-space: nowrap;
621
653
  }
622
654
 
623
- /* The working directory, under the title, on one line (see .path-line). */
624
- .case-path {
655
+ /* Under the title: the state chip, then the id and the working directory on one line (see
656
+ .case-where). The chip sits here, not beside the title: a balanced title keeps its full width,
657
+ so a chip beside it lands far from the text. */
658
+ .case-meta {
659
+ display: flex;
660
+ align-items: center;
661
+ gap: 10px;
625
662
  margin-top: -6px;
663
+
664
+ & .chip {
665
+ flex: none;
666
+ }
667
+ }
668
+
669
+ .case-path {
670
+ flex: 1;
671
+ min-width: 0;
626
672
  font-size: 12px;
627
673
  color: var(--ink-2);
628
674
  }
629
675
 
630
676
  .facts {
677
+ position: relative;
631
678
  display: grid;
632
679
  grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
633
680
  gap: 12px 26px;
681
+ margin: 0;
634
682
  padding: 14px 0;
635
683
  border-top: 1px solid var(--line);
636
684
  border-bottom: 1px solid var(--line);
@@ -651,40 +699,138 @@ tbody td:first-child {
651
699
  }
652
700
  }
653
701
 
654
- .stats {
702
+ /* The timeline's filters, each with its count: a segmented control, as the index's. "Unsettled" is
703
+ red while it shows. */
704
+ .shows {
705
+ align-self: flex-start;
706
+ max-width: 100%;
707
+
708
+ & .is-unsettled {
709
+ &,
710
+ &:not([aria-pressed="true"]):hover {
711
+ color: var(--danger);
712
+ }
713
+
714
+ &[aria-pressed="true"] {
715
+ color: var(--bg);
716
+ background: var(--danger);
717
+ }
718
+ }
719
+ }
720
+
721
+ /* Too wide for a phone in one row: the segments wrap, each row filled, ruled like a grid. The
722
+ negative margins tuck each segment's outer rules under the control's own border. */
723
+ @media (max-width: 760px) {
724
+ .shows {
725
+ flex-wrap: wrap;
726
+
727
+ & button {
728
+ flex: 1 0 auto;
729
+ margin: 0 -1px -1px 0;
730
+ border-bottom: 1px solid var(--line);
731
+ }
732
+ }
733
+ }
734
+
735
+ .timeline[data-show="ask"] > .entry:not([data-tags~="ask"]),
736
+ .timeline[data-show="opinion"] > .entry:not([data-tags~="opinion"]),
737
+ .timeline[data-show="flag"] > .entry:not([data-tags~="flag"]),
738
+ .timeline[data-show="unsettled"] > .entry:not([data-tags~="unsettled"]) {
739
+ display: none;
740
+ }
741
+
742
+ /* Under "unsettled", a card keeps its settled flags for context, faded. */
743
+ .timeline[data-show="unsettled"] .flag[data-settled] {
744
+ opacity: 0.45;
745
+ }
746
+
747
+ /* The points left for the user, each a link to where it is shown. */
748
+ .standing {
655
749
  display: flex;
656
750
  flex-wrap: wrap;
657
- gap: 8px;
751
+ align-items: baseline;
752
+ gap: 4px 10px;
753
+ padding: 8px 12px;
754
+ border-left: 2px solid var(--danger);
755
+ border-radius: 0 7px 7px 0;
756
+ background: color-mix(in srgb, var(--danger) 8%, var(--bg));
757
+ font-size: 12.5px;
758
+
759
+ & .label {
760
+ color: var(--danger);
761
+ }
762
+
763
+ & .ref {
764
+ font-size: 12px;
765
+ color: var(--danger);
766
+ border-bottom-color: currentColor;
767
+ }
658
768
  }
659
769
 
660
- .stat {
661
- display: inline-flex;
662
- align-items: baseline;
663
- gap: 6px;
664
- padding: 5px 10px;
665
- border: 1px solid var(--line);
666
- border-radius: 7px;
667
- font-size: 11.5px;
668
- color: var(--ink-2);
770
+ /*
771
+ * A running turn: a highlight sweeps along a rule, the facts' top one on the case page and a line
772
+ * under the entry in the sidebar. Motion, not words, so nothing reflows when a turn starts or ends.
773
+ */
774
+ @keyframes live-sweep {
775
+ from {
776
+ background-position: -30% 0;
777
+ }
669
778
 
670
- & b {
671
- font-family: var(--font-mono);
672
- font-size: 13px;
673
- font-weight: 600;
674
- color: var(--ink);
779
+ to {
780
+ background-position: 130% 0;
675
781
  }
782
+ }
676
783
 
677
- &.is-alert {
678
- border-color: var(--alert);
679
- background: var(--alert-weak);
680
- color: var(--alert);
784
+ .facts.is-live::before,
785
+ .side-live {
786
+ content: "";
787
+ position: absolute;
788
+ height: 2px;
789
+ border-radius: 2px;
790
+ background: linear-gradient(90deg, transparent, var(--accent), transparent) no-repeat;
791
+ background-size: 25% 100%;
792
+ animation: live-sweep 1.6s ease-in-out infinite;
793
+ }
681
794
 
682
- & b {
683
- color: var(--alert);
684
- }
795
+ .facts.is-live::before {
796
+ left: 0;
797
+ right: 0;
798
+ top: -1px;
799
+ }
800
+
801
+ .side-live {
802
+ left: 14px;
803
+ right: 16px;
804
+ bottom: 3px;
805
+ }
806
+
807
+ @media (prefers-reduced-motion: reduce) {
808
+ .facts.is-live::before,
809
+ .side-live {
810
+ animation: none;
811
+ background-position: 50% 0;
685
812
  }
686
813
  }
687
814
 
815
+ /* Forced colors drop background images: the rule shows whole, in the system's highlight colour. */
816
+ @media (forced-colors: active) {
817
+ .facts.is-live::before,
818
+ .side-live {
819
+ animation: none;
820
+ background: Highlight;
821
+ }
822
+ }
823
+
824
+ /* Text for screen readers only, where the page shows the same thing without words. */
825
+ .sr-only {
826
+ position: absolute;
827
+ width: 1px;
828
+ height: 1px;
829
+ overflow: hidden;
830
+ clip-path: inset(50%);
831
+ white-space: nowrap;
832
+ }
833
+
688
834
  /* ---------------------------------------------------------------- brief */
689
835
 
690
836
  .brief {
@@ -1138,10 +1284,6 @@ tbody td:first-child {
1138
1284
  grid-row: 1;
1139
1285
  }
1140
1286
 
1141
- .title-row {
1142
- flex-wrap: wrap;
1143
- }
1144
-
1145
1287
  h1.title {
1146
1288
  font-size: 20px;
1147
1289
  }
@@ -36,14 +36,83 @@ function times() {
36
36
  /* ---------------------------------------------------------------- live case */
37
37
 
38
38
  const timeline = document.getElementById("timeline");
39
+
40
+ /**
41
+ * The timeline filter the page shows. CSS hides the entries whose data-tags lack it, so streamed
42
+ * entries follow it too. A filter whose button is gone, such as "unsettled" once every point is
43
+ * settled, falls back to all.
44
+ */
45
+ let shown = "all";
46
+ function show(tag) {
47
+ const buttons = [...document.querySelectorAll("button[data-show]")];
48
+ shown = buttons.some((b) => b.dataset.show === tag) ? tag : "all";
49
+ for (const b of buttons) b.setAttribute("aria-pressed", String(b.dataset.show === shown));
50
+ if (shown === "all") delete timeline.dataset.show;
51
+ else timeline.dataset.show = shown;
52
+ }
53
+
54
+ /**
55
+ * Clears the URL's anchor, and with it the highlight of the entry it names: a filter change leaves
56
+ * that entry behind. replaceState alone keeps :target, so an empty fragment clears it first; it
57
+ * would scroll to the top, so the scroll position is put back.
58
+ */
59
+ function dropAnchor() {
60
+ if (!location.hash) return;
61
+ const y = scrollY;
62
+ location.replace("#");
63
+ scrollTo(scrollX, y);
64
+ history.replaceState(null, "", location.pathname + location.search);
65
+ }
66
+
67
+ /** The element a fragment names: its id as written, else percent-decoded, as the browser looks it up. */
68
+ function anchored(hash) {
69
+ const id = hash.slice(1);
70
+ if (!id) return null;
71
+ try {
72
+ return document.getElementById(id) ?? document.getElementById(decodeURIComponent(id));
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+
78
+ const hidden = (element) => element.getClientRects().length === 0;
79
+
80
+ /** Shows everything when the filter hides `target`; reports whether it did. */
81
+ function reveal(target) {
82
+ if (shown === "all" || !target || !hidden(target)) return false;
83
+ show("all");
84
+ return true;
85
+ }
86
+
39
87
  if (timeline) {
88
+ document.addEventListener("click", (event) => {
89
+ const button = event.target.closest("button[data-show]");
90
+ if (button) {
91
+ show(button.dataset.show);
92
+ dropAnchor();
93
+ }
94
+ // Before the browser follows the link, so it can scroll to the target.
95
+ const link = event.target.closest('a[href^="#"]');
96
+ if (link) reveal(anchored(link.hash));
97
+ });
98
+ // Back and Forward reach an anchor without a click: the browser found the target hidden, so the
99
+ // page scrolls to it once it shows.
100
+ addEventListener("hashchange", () => {
101
+ const target = anchored(location.hash);
102
+ if (reveal(target)) target.scrollIntoView();
103
+ });
104
+
40
105
  /** Near the bottom: the reader is following the case, not reading back. */
41
106
  const following = () => innerHeight + scrollY >= document.documentElement.scrollHeight - 160;
42
107
  const stream = new EventSource(timeline.dataset.stream);
43
108
  stream.addEventListener("patch", ({ data }) => {
44
109
  const follow = following();
45
110
  apply(data, timeline);
46
- if (follow) timeline.lastElementChild?.scrollIntoView({ behavior: "smooth", block: "end" });
111
+ // A patch may replace the header, and its filters with it.
112
+ show(shown);
113
+ // The last entry the filter shows, not the last one streamed.
114
+ const last = [...timeline.children].findLast((entry) => !hidden(entry));
115
+ if (follow) last?.scrollIntoView({ behavior: "smooth", block: "end" });
47
116
  });
48
117
  // While the case's log cannot be read, the page does not update: it says why. Empty data clears it.
49
118
  const problem = document.querySelector("[data-problem]");
@@ -77,6 +146,7 @@ for (const element of document.querySelectorAll("[data-refresh]")) {
77
146
  // Kept only once the list is applied: a body lost to the timeout must not earn a 304.
78
147
  const next = response.headers.get("etag");
79
148
  apply(await response.text());
149
+ keepSections();
80
150
  filterCases();
81
151
  etag = next;
82
152
  }
@@ -123,6 +193,10 @@ async function exportCase(caseId) {
123
193
  node.removeAttribute("data-stream");
124
194
  node.removeAttribute("data-refresh");
125
195
  }
196
+ // The file has no script to filter with: it keeps every entry, and its filters only count.
197
+ page.querySelector("#timeline")?.removeAttribute("data-show");
198
+ for (const b of page.querySelectorAll("button[data-show]"))
199
+ b.setAttribute("aria-pressed", String(b.dataset.show === "all"));
126
200
  for (const time of page.querySelectorAll("time[datetime]")) {
127
201
  time.textContent = utc(time.dateTime, time.dataset.format);
128
202
  time.removeAttribute("title");
@@ -194,42 +268,90 @@ document.querySelector("[data-export]")?.addEventListener("click", (event) => {
194
268
  // runs after the first paint, and applying the state here would flash the sidebar open.
195
269
  const shell = document.querySelector(".shell");
196
270
  const SIDEBAR_COOKIE = "sidecar_ui_sidebar";
271
+ const SECTIONS_COOKIE = "sidecar_ui_sections";
272
+ /** The sections collapsed while the cookie is absent; server.ts has the same default. */
273
+ const DEFAULT_COLLAPSED = ["closed"];
274
+
275
+ const readCookie = (name) => {
276
+ const prefix = `${name}=`;
277
+ return document.cookie
278
+ .split(";")
279
+ .map((c) => c.trim())
280
+ .find((c) => c.startsWith(prefix))
281
+ ?.slice(prefix.length);
282
+ };
283
+ const writeCookie = (name, value) => {
284
+ document.cookie = `${name}=${value}; Path=/; SameSite=Strict; Max-Age=31536000`;
285
+ };
197
286
 
198
287
  document.querySelector("[data-toggle-sidebar]")?.addEventListener("click", () => {
199
288
  const collapsed = shell.classList.toggle("is-collapsed");
200
- document.cookie = `${SIDEBAR_COOKIE}=${collapsed ? "collapsed" : "open"}; Path=/; SameSite=Strict; Max-Age=31536000`;
289
+ writeCookie(SIDEBAR_COOKIE, collapsed ? "collapsed" : "open");
290
+ });
291
+
292
+ const storedSections = () => {
293
+ const value = readCookie(SECTIONS_COOKIE);
294
+ return new Set(value === undefined ? DEFAULT_COLLAPSED : value.split("|").filter(Boolean));
295
+ };
296
+
297
+ /**
298
+ * Each section's state on this page. A refresh renders from the cookie, and the section that holds
299
+ * the open case renders open; the page's own state wins over both, so a refresh never undoes a click.
300
+ */
301
+ const sectionState = new Map();
302
+ const sectionHeads = () => document.querySelectorAll("button[data-section]");
303
+ const keepSections = () => {
304
+ for (const head of sectionHeads()) {
305
+ const expanded = sectionState.get(head.dataset.section);
306
+ if (expanded === undefined)
307
+ sectionState.set(head.dataset.section, head.getAttribute("aria-expanded") === "true");
308
+ else head.setAttribute("aria-expanded", String(expanded));
309
+ }
310
+ };
311
+ keepSections();
312
+
313
+ document.addEventListener("click", (event) => {
314
+ const head = event.target.closest("button[data-section]");
315
+ if (!head) return;
316
+ const name = head.dataset.section;
317
+ const expanded = head.getAttribute("aria-expanded") !== "true";
318
+ head.setAttribute("aria-expanded", String(expanded));
319
+ sectionState.set(name, expanded);
320
+ const collapsed = storedSections();
321
+ if (expanded) collapsed.delete(name);
322
+ else collapsed.add(name);
323
+ writeCookie(SECTIONS_COOKIE, [...collapsed].join("|"));
201
324
  });
202
325
 
203
326
  // A page restored from the back/forward cache keeps the state it was left in, though another page
204
- // may have toggled the sidebar since.
327
+ // may have toggled the sidebar or a section since.
205
328
  addEventListener("pageshow", (event) => {
206
329
  if (!event.persisted || !shell) return;
207
- const prefix = `${SIDEBAR_COOKIE}=`;
208
- const stored = document.cookie
209
- .split(";")
210
- .map((c) => c.trim())
211
- .find((c) => c.startsWith(prefix))
212
- ?.slice(prefix.length);
213
- shell.classList.toggle("is-collapsed", stored === "collapsed");
330
+ shell.classList.toggle("is-collapsed", readCookie(SIDEBAR_COOKIE) === "collapsed");
331
+ const collapsed = storedSections();
332
+ for (const head of sectionHeads()) {
333
+ const holdsCurrent = head.parentElement.querySelector('[aria-current="page"]') !== null;
334
+ const expanded = holdsCurrent || !collapsed.has(head.dataset.section);
335
+ head.setAttribute("aria-expanded", String(expanded));
336
+ sectionState.set(head.dataset.section, expanded);
337
+ }
214
338
  });
215
339
 
216
340
  /* ---------------------------------------------------------------- case index */
217
341
 
218
342
  const search = document.querySelector("[data-search]");
219
343
  // The server renders the filter the URL asks for, already checked.
220
- let filter = document.querySelector("[data-cases]")?.dataset.filterState ?? "all";
344
+ let filter = document.querySelector("[data-cases]")?.dataset.filterState ?? "open";
221
345
 
222
346
  /** Shows the rows that match the state filter and the search text, and keeps the URL in step. */
223
347
  function filterCases() {
224
348
  if (!search) return;
225
349
  const rows = [...document.querySelectorAll("#case-rows tr")];
350
+ const inState = rows.filter((r) => r.dataset.state === filter);
226
351
  const needle = search.value.trim().toLowerCase();
227
352
  let shown = 0;
228
353
  for (const row of rows) {
229
- row.hidden = !(
230
- (filter === "all" || row.dataset.state === filter) &&
231
- row.dataset.haystack.includes(needle)
232
- );
354
+ row.hidden = !(row.dataset.state === filter && row.dataset.haystack.includes(needle));
233
355
  if (!row.hidden) shown++;
234
356
  }
235
357
  document.querySelector("[data-cases]").dataset.filterState = filter;
@@ -237,16 +359,22 @@ function filterCases() {
237
359
  const name = button.dataset.filter;
238
360
  button.setAttribute("aria-pressed", String(name === filter));
239
361
  button.querySelector("[data-count]").textContent = rows.filter(
240
- (r) => name === "all" || r.dataset.state === name,
362
+ (r) => r.dataset.state === name,
241
363
  ).length;
242
364
  }
243
- document.querySelector("[data-result-count]").textContent = `${shown} / ${rows.length}`;
365
+ document.querySelector("[data-result-count]").textContent = `${shown} / ${inState.length}`;
244
366
  const message = document.querySelector("[data-message]");
245
367
  message.hidden = shown > 0;
246
- message.textContent = rows.length === 0 ? "No cases yet." : "No case matches this filter.";
368
+ message.textContent =
369
+ rows.length === 0
370
+ ? "No cases yet."
371
+ : inState.length === 0
372
+ ? `No ${filter === "open" ? "active" : "closed"} cases.`
373
+ : "No case matches this filter.";
247
374
 
248
375
  const url = new URL(location.href);
249
- if (filter === "all") url.searchParams.delete("state");
376
+ // Active is the default, so its URL names no state.
377
+ if (filter === "open") url.searchParams.delete("state");
250
378
  else url.searchParams.set("state", filter);
251
379
  if (needle) url.searchParams.set("search", search.value.trim());
252
380
  else url.searchParams.delete("search");
@@ -5,7 +5,7 @@ import { adapters, findAdapter, getNavigator, preferredNavigator, selectableNavi
5
5
  import { loadConfig } from "../config.js";
6
6
  import { processAlive, startTime } from "../lib/proc.js";
7
7
  import { SIDECAR_VERSION } from "../lib/version.js";
8
- import { awaitingReview, flagsOf, itemStatus, reviewsOf, reviewTargetsOf, unsettled, } from "../cases/items.js";
8
+ import { awaitingReview, flagsOf, itemStatus, reviewsOf, reviewsSpent, reviewTargetsOf, unsettled, } from "../cases/items.js";
9
9
  import { caseStatus, fold } from "../cases/state.js";
10
10
  import { Store } from "../cases/store.js";
11
11
  import { cancelTurn, dispatchAsk, reconcile, waitForOutcome, } from "../turns/dispatch.js";
@@ -301,13 +301,13 @@ export class SidecarServer {
301
301
  return;
302
302
  const reviewBudget = this.#reviewBudget();
303
303
  if (awaitingReview(s.items, reviewBudget).length === 0)
304
- throw new NothingToReview(this.#unsettled(s, reviewBudget));
304
+ throw new NothingToReview(this.#unsettled(s, reviewBudget), reviewBudget);
305
305
  });
306
306
  return { caseId, dispatched };
307
307
  }
308
308
  catch (err) {
309
309
  if (err instanceof NothingToReview)
310
- return { caseId, nothing: nothingToReview(err.unsettled) };
310
+ return { caseId, nothing: nothingToReview(err.unsettled, err.budget) };
311
311
  throw err;
312
312
  }
313
313
  });
@@ -354,9 +354,10 @@ export class SidecarServer {
354
354
  if (result.status === "failed" &&
355
355
  foundNothingToReview(e) &&
356
356
  state.asks.get(String(e.askId))?.event.review) {
357
+ const budget = this.#reviewBudget();
357
358
  return {
358
359
  case_id: caseId,
359
- ...nothingToReview(this.#unsettled(state)),
360
+ ...nothingToReview(this.#unsettled(state, budget), budget),
360
361
  ask_id: String(e.askId),
361
362
  };
362
363
  }
@@ -415,21 +416,19 @@ export class SidecarServer {
415
416
  const reviewBudget = this.#reviewBudget();
416
417
  const n = Array.isArray(input.ref) ? recorded.map((r) => r.n) : recorded[0].n;
417
418
  const many = (list, one, more) => (list.length > 1 ? more : one);
418
- if (input.state === "planned" && points.length > 0) {
419
- const planned = points.map((i) => i.ref);
420
- return {
421
- n,
422
- next: `${planned.join(", ")} ${many(planned, "is", "are")} planned: the navigator does not review ${many(planned, "it", "them")} until you record a ready decision on ${many(planned, "it", "them")}.`,
423
- };
419
+ const spent = points.filter((i) => reviewsSpent(i, reviewBudget)).map((i) => i.ref);
420
+ const next = [];
421
+ if (input.state === "planned") {
422
+ const planned = points.filter((i) => !reviewsSpent(i, reviewBudget)).map((i) => i.ref);
423
+ if (planned.length > 0)
424
+ next.push(`${planned.join(", ")} ${many(planned, "is", "are")} planned: the navigator does not review ${many(planned, "it", "them")} until you record a ready decision on ${many(planned, "it", "them")}.`);
425
+ if (spent.length > 0)
426
+ next.push(`${spent.join(", ")} ${many(spent, "has", "have")} used ${many(spent, "its", "their")} ${reviewCount(reviewBudget)}; the navigator will not review ${many(spent, "it", "them")} again. Once the change exists, tell the user ${many(spent, "it is", "they are")} left for them.`);
424
427
  }
425
- const spent = points.filter((i) => i.reviewTurns >= reviewBudget).map((i) => i.ref);
426
- if (spent.length > 0) {
427
- return {
428
- n,
429
- next: `${spent.join(", ")} ${many(spent, "has", "have")} used ${many(spent, "its", "their")} ${reviewBudget} reviews; the navigator will not review this decision. Tell the user ${many(spent, "it is", "they are")} left for them.`,
430
- };
428
+ else if (spent.length > 0) {
429
+ next.push(`${spent.join(", ")} ${many(spent, "has", "have")} used ${many(spent, "its", "their")} ${reviewCount(reviewBudget)}; the navigator will not review this decision. Tell the user ${many(spent, "it is", "they are")} left for them.`);
431
430
  }
432
- return { n };
431
+ return next.length > 0 ? { n, next: next.join(" ") } : { n };
433
432
  });
434
433
  }
435
434
  async read(input) {
@@ -722,32 +721,40 @@ function renderOpinion(e, state, budget) {
722
721
  for (const r of reviews.filter((r) => current(r) && r.status === "held")) {
723
722
  next.push(`Tell the user now: the navigator holds its point on ${r.ref} against your decision; its reason is in reviews. The user may decide.`);
724
723
  }
725
- for (const r of reviews.filter((r) => current(r) && r.status === "reopened")) {
726
- next.push(`The navigator reopened ${r.ref}; what is missing is in reviews. Record a new decision with ref=${r.ref}, or leave it for the user.`);
727
- }
728
- // A newer decision may have been recorded during the turn: say what each point awaits now.
724
+ // A reopened point with its reviews spent cannot be settled by another decision: it escalates.
729
725
  const now = (ref) => {
730
726
  const item = state.items.get(ref);
731
727
  return item ? itemStatus(item, budget) : undefined;
732
728
  };
729
+ for (const r of reviews.filter((r) => current(r) && r.status === "reopened")) {
730
+ next.push(now(r.ref) === "exhausted"
731
+ ? `The navigator reopened ${r.ref}, and it has used its ${reviewCount(budget)}: it is left for the user. Tell the user now, with both positions; do not decide it again.`
732
+ : `The navigator reopened ${r.ref}; what is missing is in reviews. Record a new decision with ref=${r.ref}, or leave it for the user.`);
733
+ }
734
+ // A newer decision may have been recorded during the turn: say what each point awaits now.
733
735
  const stale = reviews.filter((r) => !current(r)).map((r) => r.ref);
734
736
  if (stale.length > 0) {
735
- next.push(`The navigator reviewed an earlier decision on ${stale.join(", ")}, not your newer one; ${awaits(stale, now)}`);
737
+ next.push(`The navigator reviewed an earlier decision on ${stale.join(", ")}, not your newer one; ${awaits(stale, state, budget)}`);
736
738
  }
737
739
  const omitted = targets.map((t) => t.ref).filter((ref) => !reviews.some((r) => r.ref === ref));
738
740
  if (omitted.length > 0)
739
- next.push(`The navigator did not review ${omitted.join(", ")}; ${awaits(omitted, now)}`);
741
+ next.push(`The navigator did not review ${omitted.join(", ")}; ${awaits(omitted, state, budget)}`);
740
742
  // Without a decision that refs its id, an item stays open: on the dashboard and in a re-brief seed.
741
- if (!isReview) {
742
- const point = state.items.has(askId) ? [askId] : [];
743
- const refs = [...point, ...flagIds];
744
- next.push(refs.length > 0
745
- ? `Record a decision on each point with sidecar_record kind=decision (${refs.join(", ")}); one decision may name several refs when it settles them the same way. The navigator reviews each point.`
746
- : `Record your decision on the opinion with sidecar_record kind=decision ref=${askId}.`);
747
- }
748
- else if (flagIds.length > 0) {
749
- next.push(`Record a decision on each new point with sidecar_record kind=decision (${flagIds.join(", ")}).`);
750
- }
743
+ // A replayed result reads the current state: a point decided since needs no new decision, and one
744
+ // left for the user must not get one.
745
+ const raised = [...(!isReview && state.items.has(askId) ? [askId] : []), ...flagIds];
746
+ const toDecide = raised.filter((ref) => now(ref) === "open");
747
+ const left = raised.filter((ref) => now(ref) === "exhausted");
748
+ if (!isReview && raised.length === 0) {
749
+ next.push(`Record your decision on the opinion with sidecar_record kind=decision ref=${askId}.`);
750
+ }
751
+ else if (toDecide.length > 0) {
752
+ next.push(isReview
753
+ ? `Record a decision on each new point with sidecar_record kind=decision (${toDecide.join(", ")}).`
754
+ : `Record a decision on each point with sidecar_record kind=decision (${toDecide.join(", ")}); one decision may name several refs when it settles them the same way. The navigator reviews each point.`);
755
+ }
756
+ if (left.length > 0)
757
+ next.push(awaits(left, state, budget));
751
758
  const waiting = awaitingReview(state.items, budget).map((i) => i.ref);
752
759
  if (waiting.length > 0) {
753
760
  next.push(`Awaiting the navigator's review: ${waiting.join(", ")}. They ride along with your next ask, or call sidecar_review before sidecar_close.`);
@@ -764,37 +771,65 @@ function renderOpinion(e, state, budget) {
764
771
  next: next.join(" "),
765
772
  };
766
773
  }
774
+ const reviewCount = (budget) => `${budget} ${budget === 1 ? "review" : "reviews"}`;
767
775
  /** Where each point stands now, for a review that did not settle it. */
768
- function awaits(refs, now) {
776
+ function awaits(refs, state, budget) {
769
777
  return (refs
770
778
  .map((ref) => {
771
- const status = now(ref);
779
+ const item = state.items.get(ref);
780
+ const status = item ? itemStatus(item, budget) : undefined;
781
+ if (status === "exhausted")
782
+ return `${ref} has used its ${reviewCount(budget)} and is left for the user: tell the user now`;
772
783
  if (status === "addressed")
773
784
  return `${ref} still awaits review`;
774
785
  if (status === "planned")
775
- return `${ref} is planned: it is not reviewed until you record a ready decision on it`;
786
+ return reviewsSpent(item, budget)
787
+ ? `${ref} is planned and has used its ${reviewCount(budget)}: once the change exists, it is left for the user`
788
+ : `${ref} is planned: it is not reviewed until you record a ready decision on it`;
776
789
  return `${ref} is ${status ?? "unknown"}`;
777
790
  })
778
791
  .join("; ") + ".");
779
792
  }
780
- /** A review with nothing to do. Planned points are why, when there are some: the driver may not know. */
781
- function nothingToReview(left) {
782
- const planned = left.filter((i) => i.status === "planned").map((i) => i.ref);
793
+ /**
794
+ * A review with nothing to do, and why, when the driver may not know: points left for the user,
795
+ * which no review settles, and planned points, which wait for a ready decision.
796
+ */
797
+ function nothingToReview(left, budget) {
798
+ const exhausted = left.filter((i) => i.status === "exhausted").map((i) => i.ref);
799
+ const planned = left.filter((i) => i.status === "planned");
800
+ const reviewable = planned.filter((i) => i.reviews_used < budget).map((i) => i.ref);
801
+ const spent = planned.filter((i) => i.reviews_used >= budget).map((i) => i.ref);
802
+ const are = (refs) => (refs.length > 1 ? "are" : "is");
803
+ const next = [
804
+ ...(exhausted.length > 0
805
+ ? [
806
+ `${exhausted.join(", ")} ${are(exhausted)} left for the user: no review can settle ${exhausted.length > 1 ? "them" : "it"}. Tell the user now.`,
807
+ ]
808
+ : []),
809
+ ...(reviewable.length > 0
810
+ ? [
811
+ `${reviewable.join(", ")} ${are(reviewable)} planned: record a ready decision once the change exists, then review.`,
812
+ ]
813
+ : []),
814
+ ...(spent.length > 0
815
+ ? [
816
+ `${spent.join(", ")} ${are(spent)} planned with ${spent.length > 1 ? "their" : "its"} ${reviewCount(budget)} used: once the change exists, ${spent.length > 1 ? "they are" : "it is"} left for the user.`,
817
+ ]
818
+ : []),
819
+ ];
783
820
  return {
784
821
  status: "nothing-to-review",
785
822
  unsettled: left,
786
- ...(planned.length > 0
787
- ? {
788
- next: `${planned.join(", ")} ${planned.length > 1 ? "are" : "is"} planned: record a ready decision once the change exists, then review.`,
789
- }
790
- : {}),
823
+ ...(next.length > 0 ? { next: next.join(" ") } : {}),
791
824
  };
792
825
  }
793
826
  /** Thrown inside the dispatch transaction when a review turn would have nothing to review. */
794
827
  class NothingToReview extends Error {
795
828
  unsettled;
796
- constructor(unsettled) {
829
+ budget;
830
+ constructor(unsettled, budget) {
797
831
  super("nothing awaits review");
798
832
  this.unsettled = unsettled;
833
+ this.budget = budget;
799
834
  }
800
835
  }
@@ -22,14 +22,15 @@ When to use it
22
22
  The loop
23
23
  1. sidecar_open with a brief that stands alone. Share the dashboard link with the user once.
24
24
  2. sidecar_ask one question at a time. Do not act on it until the outcome arrives.
25
- 3. Decide every point the result's next names, with sidecar_record kind=decision: what you accept, reject or defer, and why. Never drop a point silently. Before you accept a point that matters, read the cited lines yourself.
26
- 4. The navigator reviews your decisions with your next ask, or with sidecar_review when no ask is coming. A point is settled only when the navigator confirms your decision. On reopened, decide again or leave the point for the user.
25
+ 3. Decide every point the result's next asks you to decide, with sidecar_record kind=decision: what you accept, reject or defer, and why. Never drop a point silently. Before you accept a point that matters, read the cited lines yourself.
26
+ 4. The navigator reviews your decisions with your next ask, or with sidecar_review when no ask is coming. A point is settled only when the navigator confirms your decision. On reopened, decide again or leave the point for the user. Each point gets a limited number of reviews; a point that used them unsettled is left for the user: do not decide it again.
27
27
  5. Close the case with sidecar_close when the work is done; before that, call sidecar_review if decisions still await the navigator. When the same work continues later, a review round on the same PR included, sidecar_attach the case again, closed or not; a new problem gets a new case.
28
28
 
29
29
  Tell the user
30
30
  - On failed: "navigator unavailable: <outcome>, proceeding". Then continue without the opinion, and record your own conclusion as a note with ref=<ask id>.
31
31
  - On held: the navigator stands by a point you rejected. Tell the user at once, with both positions, so they can intervene; do not argue it further.
32
- - The points left for the user, the confirmed deferrals (they stay listed, not settled), and the points sidecar_close lists as unsettled.
32
+ - On a point left for the user: you and the navigator did not settle it within its reviews. Tell the user at once, with both positions, as for held.
33
+ - The confirmed deferrals (they stay listed, not settled), and the points sidecar_close lists as unsettled.
33
34
  - In your report, where the navigator disagreed with you and what you did about it. Report the case state accurately, for example "design agreed; implementation pending": do not say the navigator agrees while its points are open, planned or reopened.`;
34
35
  const text = z.string().trim().min(1, "must be a non-empty string");
35
36
  const upTo = (max) => text.max(max, `must be at most ${max} characters`);
@@ -1,5 +1,5 @@
1
1
  import { DEFAULTS } from "../config.js";
2
- import { decisionState, unsettled } from "../cases/items.js";
2
+ import { decisionState, itemStatus, unsettled } from "../cases/items.js";
3
3
  const ROLE = `You are the navigator in a sidecar case. The driver, another coding agent, works on a task in this workspace and asks you for an independent opinion, one question at a time. You are read-only: you read and search; you never change anything.
4
4
 
5
5
  How to work
@@ -50,7 +50,7 @@ export function buildPrompt(state, ask, opts) {
50
50
  const review = opts.review ?? [];
51
51
  // A decision under review is shown with its item, not a second time among the updates.
52
52
  const shown = new Set(review.map((i) => i.decision.n));
53
- const { head, tail, parts } = layout(state, ask, opts.fresh, opts.rebrief ?? false, review, shown, opts.git);
53
+ const { head, tail, parts } = layout(state, ask, opts.fresh, opts.rebrief ?? false, review, shown, opts.git, opts.reviewBudget ?? DEFAULTS.reviewBudget);
54
54
  const size = fixedSize(head, tail, parts);
55
55
  if (size > bound)
56
56
  return { ok: false, size, bound };
@@ -83,10 +83,11 @@ export function buildPrompt(state, ask, opts) {
83
83
  * re-brief, the larger of the two prompts, so the targets claimed for the turn fit either.
84
84
  */
85
85
  export function reviewRoom(state, ask, bound, git) {
86
- const { head, tail, parts } = layout(state, ask, true, true, [], new Set(), git);
86
+ // The budget only labels entries, which the fixed size does not count.
87
+ const { head, tail, parts } = layout(state, ask, true, true, [], new Set(), git, DEFAULTS.reviewBudget);
87
88
  return bound - fixedSize(head, tail, parts) - "\n\n".length;
88
89
  }
89
- function layout(state, ask, fresh, rebrief, review, shown, git) {
90
+ function layout(state, ask, fresh, rebrief, review, shown, git, budget) {
90
91
  // A resumed session raised every point after its start itself; a fresh one holds none.
91
92
  const reviewSection = renderReview(review, fresh ? undefined : (i) => i.raisedN > state.sessionStart);
92
93
  const tail = [
@@ -147,7 +148,7 @@ function layout(state, ask, fresh, rebrief, review, shown, git) {
147
148
  {
148
149
  title: "Your points not yet settled",
149
150
  entries: pending.map((i) => ({
150
- text: `- [${i.ref}] ${[i.status, i.severity].filter((v) => v !== undefined).join(", ")}: ${capped(i.point)}`,
151
+ text: `- [${i.ref}] ${[pendingStatus(i, budget), i.severity].filter((v) => v !== undefined).join(", ")}: ${capped(i.point)}`,
151
152
  n: i.raisedN,
152
153
  seeded: [i.raisedN],
153
154
  })),
@@ -157,6 +158,11 @@ function layout(state, ask, fresh, rebrief, review, shown, git) {
157
158
  ]),
158
159
  };
159
160
  }
161
+ /** A point the review budget left for the user says so: no review of it is coming. */
162
+ const pendingStatus = (item, budget) => {
163
+ const status = itemStatus(item, budget);
164
+ return status === "exhausted" ? "left for the user" : status;
165
+ };
160
166
  const nonEmpty = (parts) => parts.filter((p) => p.entries.length > 0);
161
167
  /**
162
168
  * The case's workspace is the navigator's working directory, but a navigator does not assume it,
@@ -212,6 +212,7 @@ async function fresh(isRebrief) {
212
212
  bound: config.seedBound,
213
213
  review,
214
214
  git,
215
+ reviewBudget: config.reviewBudget,
215
216
  });
216
217
  if (!prompt.ok)
217
218
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lysyi3m/sidecar",
3
- "version": "1.7.1",
3
+ "version": "1.9.0",
4
4
  "description": "Lets one coding agent consult another mid-task: a driver asks, a read-only navigator answers",
5
5
  "license": "MIT",
6
6
  "repository": {