devist 0.26.0

Project bootstrap CLI for AI-assisted development. Spin up new projects from templates, manage backends, and keep your codebase comprehensible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import ActivityHeatmap from "@/components/ActivityHeatmap";
import { useI18n } from "@/i18n/I18nProvider";
import { dateFnsLocale } from "@/lib/dateFns";
import {
  type ConfirmSourceStats,
  type DailyCount,
  type InboxSnapshot,
  type MemoryStats,
  type Stats,
  type WeeklyOutcome,
  fetchActivitySparkline,
  fetchDailyActivity,
  fetchInboxSnapshot,
  fetchMemoryStats,
  fetchRecentConfirmSources,
  fetchStats,
  fetchWeeklyOutcomes,
  listEvents,
} from "@/lib/queries";
import { useRealtimeWorkerEvents } from "@/lib/realtime";
import type { Severity, WorkerEvent } from "@/types";
import { formatDistanceToNow } from "date-fns";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

const SEV_DOT: Record<Severity, string> = {
  info: "bg-muted-foreground/40",
  suggest: "bg-cyan-500",
  warn: "bg-yellow-500",
  block: "bg-red-500",
};

export default function Overview() {
  const { t } = useI18n();
  const [stats, setStats] = useState<Stats | null>(null);
  const [recent, setRecent] = useState<WorkerEvent[]>([]);
  const [inbox, setInbox] = useState<InboxSnapshot | null>(null);
  const [memory, setMemory] = useState<MemoryStats | null>(null);
  const [confirms, setConfirms] = useState<ConfirmSourceStats | null>(null);
  const [sparkline, setSparkline] = useState<DailyCount[]>([]);
  const [heatmap, setHeatmap] = useState<DailyCount[]>([]);
  const [outcomes, setOutcomes] = useState<WeeklyOutcome[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [refreshKey, setRefreshKey] = useState(0);

  useEffect(() => {
    let alive = true;
    Promise.all([
      fetchStats(),
      listEvents({ limit: 10 }),
      fetchInboxSnapshot(),
      fetchMemoryStats(),
      fetchRecentConfirmSources(24),
      fetchActivitySparkline(7),
      fetchDailyActivity(364),
      fetchWeeklyOutcomes(8),
    ])
      .then(([s, r, ix, mem, confirms, spark, hm, oc]) => {
        if (!alive) return;
        setStats(s);
        setRecent(r);
        setInbox(ix);
        setMemory(mem);
        setConfirms(confirms);
        setSparkline(spark);
        setHeatmap(hm);
        setOutcomes(oc);
      })
      .catch((e) => alive && setError(String(e?.message ?? e)));
    return () => {
      alive = false;
    };
  }, [refreshKey]);

  useRealtimeWorkerEvents({
    onInsert: (ev) => {
      setRecent((prev) => [ev, ...prev].slice(0, 10));
      setRefreshKey((k) => k + 1);
    },
    onUpdate: (ev) => {
      setRecent((prev) => prev.map((e) => (e.id === ev.id ? { ...e, ...ev } : e)));
      setRefreshKey((k) => k + 1);
    },
  });

  return (
    <div className="p-6 space-y-6">
      <header>
        <h1 className="text-xl font-semibold">{t("overview.title")}</h1>
      </header>

      {error && (
        <div className="rounded-md border border-red-300 bg-red-50 p-3 text-sm text-red-700">
          {error}
        </div>
      )}

      <section className="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <Stat label={t("overview.stat.eventsToday")} value={stats?.events_today} />
        <Stat label={t("overview.stat.adviceWeek")} value={stats?.advice_this_week} />
        <Stat label={t("overview.stat.warnBlock")} value={stats?.warn_block_this_week} />
      </section>

      <InboxSnapshotCard data={inbox} />
      <AdviceQualityCard outcomes={outcomes} />

      <section className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <ResoPulseCard memory={memory} confirms={confirms} />
        <ActivitySparkCard data={sparkline} />
      </section>

      <ActivityHeatmap
        data={heatmap}
        title={t("overview.heatmap.title")}
        trailing={`${heatmap.reduce((s, d) => s + d.count, 0)} ${t("overview.activity.events")}`}
      />

      <section>
        <h2 className="text-sm font-semibold mb-2">{t("overview.recent")}</h2>
        <div className="rounded-md border bg-card divide-y">
          {recent.length === 0 && (
            <div className="p-4 text-sm text-muted-foreground">{t("overview.empty")}</div>
          )}
          {recent.map((ev) => (
            <ActivityLine key={ev.id} event={ev} />
          ))}
        </div>
      </section>
    </div>
  );
}

function InboxSnapshotCard({ data }: { data: InboxSnapshot | null }) {
  const { t } = useI18n();
  const total = (data?.block ?? 0) + (data?.warn ?? 0) + (data?.suggest ?? 0);
  return (
    <section className="rounded-md border bg-card p-4">
      <div className="flex items-center justify-between gap-4 flex-wrap">
        <div>
          <div className="text-xs uppercase tracking-wide text-muted-foreground">
            {t("overview.inbox.title")}
          </div>
          {data === null ? (
            <div className="mt-2 text-sm text-muted-foreground">—</div>
          ) : total === 0 ? (
            <div className="mt-2 text-sm text-green-600">
              {t("overview.inbox.allClear")}
            </div>
          ) : (
            <div className="mt-2 flex items-center gap-4 text-sm">
              <SeverityCount sev="block" count={data.block} />
              <SeverityCount sev="warn" count={data.warn} />
              <SeverityCount sev="suggest" count={data.suggest} />
            </div>
          )}
        </div>
        <Link
          to="/dashboard/inbox"
          className="text-xs font-medium text-foreground hover:underline whitespace-nowrap"
        >
          {t("overview.inbox.openInbox")}
        </Link>
      </div>
    </section>
  );
}

function AdviceQualityCard({ outcomes }: { outcomes: WeeklyOutcome[] }) {
  const { t } = useI18n();
  if (outcomes.length === 0) {
    return null;
  }
  // outcomes is newest-first; pick the first week with a measurable
  // win_rate as "this week" — pure-pending weeks have null rates.
  const measurable = outcomes.filter((o) => o.win_rate_pct != null);
  if (measurable.length === 0) {
    return (
      <section className="rounded-md border bg-card p-4">
        <div className="text-xs uppercase tracking-wide text-muted-foreground">
          {t("overview.quality.title")}
        </div>
        <div className="mt-2 text-sm text-muted-foreground">
          {t("overview.quality.warmup")}
        </div>
      </section>
    );
  }
  const current = measurable[0];
  const prior = measurable[1];
  const delta =
    prior?.win_rate_pct != null && current.win_rate_pct != null
      ? current.win_rate_pct - prior.win_rate_pct
      : null;

  // Sparkline: oldest → newest left-to-right, only measurable weeks.
  const trend = [...measurable].reverse();
  const max = Math.max(100, ...trend.map((o) => o.win_rate_pct ?? 0));

  return (
    <section className="rounded-md border bg-card p-4">
      <div className="flex items-baseline justify-between gap-3 mb-3">
        <div className="text-xs uppercase tracking-wide text-muted-foreground">
          {t("overview.quality.title")}
        </div>
        <div className="text-xs text-muted-foreground tabular-nums">
          {t("overview.quality.thisWeek", {
            wins: current.wins,
            total: current.wins + current.losses + current.neutral,
          })}
        </div>
      </div>
      <div className="flex items-end gap-6 flex-wrap">
        <div>
          <div className="text-3xl font-semibold tabular-nums">
            {current.win_rate_pct?.toFixed(0)}
            <span className="text-base text-muted-foreground">%</span>
          </div>
          {delta != null && (
            <div
              className={`mt-1 text-xs tabular-nums ${
                delta > 0
                  ? "text-green-600"
                  : delta < 0
                    ? "text-red-600"
                    : "text-muted-foreground"
              }`}
            >
              {delta > 0 ? "▲" : delta < 0 ? "▼" : "—"}{" "}
              {Math.abs(delta).toFixed(1)}{" "}
              {t("overview.quality.vsLastWeek")}
            </div>
          )}
        </div>
        <div className="flex-1 min-w-[200px]">
          <div className="flex items-end gap-1 h-12">
            {trend.map((o) => {
              const h = ((o.win_rate_pct ?? 0) / max) * 100;
              return (
                <div
                  key={o.week_start}
                  className="flex-1 group relative"
                  title={`${o.week_start.slice(0, 10)}: ${o.win_rate_pct?.toFixed(0)}% (${o.wins}/${o.wins + o.losses + o.neutral})`}
                >
                  <div
                    className="w-full bg-foreground/15 group-hover:bg-foreground/40 rounded-sm transition-colors"
                    style={{ height: `${Math.max(2, h)}%` }}
                  />
                </div>
              );
            })}
          </div>
          <div className="mt-1 text-[10px] text-muted-foreground text-right">
            {trend.length} {t("overview.quality.weeksTracked")}
          </div>
        </div>
      </div>
    </section>
  );
}

function SeverityCount({ sev, count }: { sev: Severity; count: number }) {
  const { t } = useI18n();
  return (
    <span className="inline-flex items-center gap-2">
      <span
        className={`inline-block w-2 h-2 rounded-full ${SEV_DOT[sev]}`}
      />
      <span className="font-semibold tabular-nums">{count}</span>
      <span className="text-muted-foreground">{t(`severity.${sev}` as const)}</span>
    </span>
  );
}

function ResoPulseCard({
  memory,
  confirms,
}: {
  memory: MemoryStats | null;
  confirms: ConfirmSourceStats | null;
}) {
  const { t } = useI18n();
  return (
    <div className="rounded-md border bg-card p-4">
      <div className="text-xs uppercase tracking-wide text-muted-foreground">
        {t("overview.reso.title")}
      </div>
      {memory === null ? (
        <div className="mt-2 text-sm text-muted-foreground">—</div>
      ) : (
        <>
          <div className="mt-2 flex items-baseline gap-2">
            <span className="text-2xl font-semibold tabular-nums">
              {memory.total}
            </span>
            <span className="text-xs text-muted-foreground">
              {t("overview.reso.activeMemories")}
            </span>
          </div>
          <div className="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground">
            <PriorityChip
              count={memory.byPriority.constraint}
              label={t("overview.reso.priority.constraint")}
              accent="text-red-700"
            />
            <PriorityChip
              count={memory.byPriority.strong}
              label={t("overview.reso.priority.strong")}
              accent="text-yellow-700"
            />
            <PriorityChip
              count={memory.byPriority.preference}
              label={t("overview.reso.priority.preference")}
              accent="text-cyan-700"
            />
            <PriorityChip
              count={memory.byPriority.info}
              label={t("overview.reso.priority.info")}
            />
          </div>
        </>
      )}
      <div className="mt-4 pt-3 border-t">
        <div className="text-xs text-muted-foreground mb-1.5">
          {t("overview.reso.last24h")}
        </div>
        {confirms === null ? (
          <div className="text-sm text-muted-foreground">—</div>
        ) : (
          <div className="flex flex-wrap gap-x-3 gap-y-1 text-xs">
            <ConfirmChip count={confirms.audit} label={t("overview.reso.confirm.audit")} />
            <ConfirmChip count={confirms.verify} label={t("overview.reso.confirm.verify")} />
            <ConfirmChip count={confirms.apply} label={t("overview.reso.confirm.apply")} />
            <ConfirmChip count={confirms.user} label={t("overview.reso.confirm.user")} />
          </div>
        )}
      </div>
    </div>
  );
}

function PriorityChip({
  count,
  label,
  accent,
}: {
  count: number;
  label: string;
  accent?: string;
}) {
  return (
    <span className="inline-flex items-baseline gap-1">
      <span className={`font-semibold tabular-nums ${accent ?? ""}`}>
        {count}
      </span>
      <span>{label}</span>
    </span>
  );
}

function ConfirmChip({ count, label }: { count: number; label: string }) {
  return (
    <span className="inline-flex items-baseline gap-1">
      <span className="font-semibold tabular-nums text-foreground">{count}</span>
      <span className="text-muted-foreground font-mono">{label}</span>
    </span>
  );
}

function ActivitySparkCard({ data }: { data: DailyCount[] }) {
  const { t } = useI18n();
  const max = Math.max(1, ...data.map((d) => d.count));
  const total = data.reduce((s, d) => s + d.count, 0);
  return (
    <div className="rounded-md border bg-card p-4">
      <div className="flex items-baseline justify-between">
        <div className="text-xs uppercase tracking-wide text-muted-foreground">
          {t("overview.activity.title")}
        </div>
        <div className="text-xs text-muted-foreground tabular-nums">
          {total} {t("overview.activity.events")}
        </div>
      </div>
      {data.length === 0 ? (
        <div className="mt-3 text-sm text-muted-foreground">—</div>
      ) : (
        <div className="mt-4 flex items-end gap-1.5 h-20">
          {data.map((d) => {
            const heightPct = Math.max(2, (d.count / max) * 100);
            return (
              <div
                key={d.date}
                className="flex-1 flex flex-col items-center gap-1.5 group"
                title={`${d.date}: ${d.count}`}
              >
                <div className="w-full flex-1 flex items-end">
                  <div
                    className="w-full bg-foreground/15 group-hover:bg-foreground/40 rounded-sm transition-colors"
                    style={{ height: `${heightPct}%` }}
                  />
                </div>
                <div className="text-[10px] text-muted-foreground tabular-nums">
                  {d.date.slice(8)}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function Stat({ label, value }: { label: string; value: number | undefined }) {
  return (
    <div className="rounded-md border bg-card p-4">
      <div className="text-xs uppercase tracking-wide text-muted-foreground">{label}</div>
      <div className="mt-1 text-2xl font-semibold tabular-nums">{value ?? "—"}</div>
    </div>
  );
}

function ActivityLine({ event }: { event: WorkerEvent }) {
  const { lang } = useI18n();
  const ago = formatDistanceToNow(new Date(event.created_at), {
    addSuffix: true,
    locale: dateFnsLocale(lang),
  });
  const summary = summarize(event);
  return (
    <Link
      to={`/dashboard/projects/${encodeURIComponent(event.project)}`}
      className="flex items-center gap-3 px-3 py-2 text-xs hover:bg-muted/30"
    >
      <span
        className={`shrink-0 inline-block w-1.5 h-1.5 rounded-full ${SEV_DOT[event.severity]}`}
      />
      <span className="font-medium text-foreground shrink-0 truncate max-w-[140px]">
        {event.project}
      </span>
      <span className="text-muted-foreground truncate flex-1 min-w-0">
        {summary}
      </span>
      <span className="text-muted-foreground whitespace-nowrap shrink-0 tabular-nums">
        {ago}
      </span>
    </Link>
  );
}

function summarize(ev: WorkerEvent): string {
  const p = (ev.payload ?? {}) as Record<string, unknown>;
  const text =
    typeof p.text === "string"
      ? p.text
      : typeof p.error === "string"
        ? `error: ${p.error}`
        : ev.path ?? ev.event_type;
  // Single-line: take first line, trim, cap at ~120 chars.
  const oneLine = text.split(/\n/, 1)[0]?.trim() ?? "";
  return oneLine.length > 120 ? `${oneLine.slice(0, 120)}…` : oneLine;
}