@koinzhang/paseo-plugin-activity 0.4.0 → 0.6.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/README.md +3 -3
  3. package/client/activity-heatmap.tsx +17 -25
  4. package/client/agent-creations.tsx +207 -0
  5. package/client/agent-directory.test.ts +191 -0
  6. package/client/agent-directory.ts +150 -0
  7. package/client/attention-pill.tsx +17 -105
  8. package/client/color-mix.test.ts +27 -0
  9. package/client/color-mix.ts +38 -0
  10. package/client/fit-text.test.ts +41 -0
  11. package/client/fit-text.ts +33 -0
  12. package/client/global-surface.tsx +104 -31
  13. package/client/hourly-activity-timeline.tsx +392 -0
  14. package/client/measured-width.ts +72 -0
  15. package/client/pill-directory.ts +20 -68
  16. package/client/range.test.ts +44 -0
  17. package/client/range.ts +14 -0
  18. package/client/rank-color.test.ts +108 -14
  19. package/client/rank-color.ts +261 -48
  20. package/client/usage-stats.tsx +116 -5
  21. package/client/use-agent-turn-end.ts +19 -2
  22. package/client/use-workspace-agent-statuses.ts +18 -42
  23. package/client/workspace/constants.ts +2 -0
  24. package/client/workspace/host-archive-sync.test.ts +46 -0
  25. package/client/workspace/host-archive-sync.ts +15 -0
  26. package/client/workspace/list-host-agents.test.ts +11 -63
  27. package/client/workspace/list-host-agents.ts +4 -58
  28. package/client/workspace/panel.tsx +99 -12
  29. package/client/workspace/rank-section.tsx +150 -11
  30. package/index.server.ts +30 -0
  31. package/package.json +3 -3
  32. package/paseo-plugin.json +1 -1
  33. package/server/background-sync.test.ts +43 -0
  34. package/server/background-sync.ts +9 -0
  35. package/server/handlers-query.test.ts +225 -0
  36. package/server/handlers.ts +117 -0
  37. package/shared/activity.test.ts +123 -6
  38. package/shared/activity.ts +103 -5
  39. package/shared/classify.test.ts +10 -0
  40. package/shared/classify.ts +10 -0
  41. package/shared/explorer-agent-display.test.ts +61 -0
  42. package/shared/explorer-agent-display.ts +21 -2
  43. package/shared/format.test.ts +28 -3
  44. package/shared/format.ts +22 -2
  45. package/shared/insights.test.ts +113 -70
  46. package/shared/insights.ts +53 -39
  47. package/shared/usage.test.ts +209 -0
  48. package/shared/usage.ts +283 -1
  49. package/client/pill-directory.test.ts +0 -92
  50. package/client/workspace/agent-live-status-sync.tsx +0 -103
  51. package/client/workspace/status-cache.test.ts +0 -62
  52. package/client/workspace/status-cache.ts +0 -23
@@ -5,9 +5,14 @@ import { join } from "node:path";
5
5
  import { test } from "node:test";
6
6
  import type { PluginHandlerContext } from "@getpaseo/plugin/server";
7
7
  import {
8
+ createActivityByHourHandler,
8
9
  createActivityByDayHandler,
10
+ createAgentCreationsHandler,
11
+ createAgentLifetimeHandler,
9
12
  createAgentsHandler,
10
13
  createByProviderHandler,
14
+ createRecentMcpCallsHandler,
15
+ createRecentSkillCallsHandler,
11
16
  createSkillsByNameHandler,
12
17
  } from "./handlers.ts";
13
18
  import { createUsageStore, type ToolCallRow } from "./store.ts";
@@ -60,6 +65,15 @@ test("by-provider and activity-by-day read the local store only", async () => {
60
65
  const activity = await createActivityByDayHandler(store)({});
61
66
  assert.equal(activity.days[0]?.skills, 1);
62
67
  assert.equal(activity.days[0]?.agents, 1);
68
+ const hourly = await createActivityByHourHandler(
69
+ store,
70
+ () => new Date("2026-09-19T12:30:00.000Z"),
71
+ )({ hours: 2 });
72
+ assert.equal(hourly.hours.length, 2);
73
+ assert.equal(hourly.hours[0]?.start, "2026-09-19T11:00:00.000Z");
74
+ assert.equal(hourly.hours[0]?.total, 0);
75
+ assert.equal(hourly.hours[1]?.skills, 1);
76
+ assert.equal(hourly.hours[1]?.agents, 1);
63
77
  } finally {
64
78
  store.close();
65
79
  rmSync(dir, { recursive: true, force: true });
@@ -123,6 +137,217 @@ test("usage.agents filters by workspace and merges the registry", async () => {
123
137
  }
124
138
  });
125
139
 
140
+ test("recent skill calls returns newest workspace calls with agent titles", async () => {
141
+ const dir = mkdtempSync(join(tmpdir(), "recent-skills-"));
142
+ const store = createUsageStore({ dir, driver: "sqlite" });
143
+ try {
144
+ store.upsertMany([
145
+ row({ agentId: "a1", callId: "older", skillName: "review", ts: "2026-09-19T10:00:00.000Z" }),
146
+ row({ agentId: "a2", callId: "newer", skillName: "paseo", ts: "2026-09-19T12:00:00.000Z" }),
147
+ row({
148
+ agentId: "a1",
149
+ callId: "low",
150
+ skillName: "reference-only",
151
+ confidence: "low",
152
+ ts: "2026-09-19T13:00:00.000Z",
153
+ }),
154
+ row({
155
+ agentId: "other",
156
+ callId: "other-workspace",
157
+ workspaceId: "w2",
158
+ ts: "2026-09-19T14:00:00.000Z",
159
+ }),
160
+ ]);
161
+ store.upsertAgents([
162
+ {
163
+ agentId: "a1",
164
+ workspaceId: "w1",
165
+ parentAgentId: null,
166
+ provider: "codex",
167
+ title: "Alpha",
168
+ createdAt: "2026-09-19T09:00:00.000Z",
169
+ archivedAt: null,
170
+ updatedAt: "2026-09-19T10:00:00.000Z",
171
+ },
172
+ {
173
+ agentId: "a2",
174
+ workspaceId: "w1",
175
+ parentAgentId: null,
176
+ provider: "codex",
177
+ title: null,
178
+ createdAt: "2026-09-19T09:00:00.000Z",
179
+ archivedAt: null,
180
+ updatedAt: "2026-09-19T12:00:00.000Z",
181
+ },
182
+ ]);
183
+
184
+ const result = await createRecentSkillCallsHandler(store)({
185
+ workspaceId: "w1",
186
+ limit: 2,
187
+ });
188
+ assert.deepEqual(
189
+ result.items.map((item) => [
190
+ item.callId,
191
+ item.skillName,
192
+ item.agentTitle,
193
+ item.calledAt,
194
+ ]),
195
+ [
196
+ ["newer", "paseo", null, "2026-09-19T12:00:00.000Z"],
197
+ ["older", "review", "Alpha", "2026-09-19T10:00:00.000Z"],
198
+ ],
199
+ );
200
+ } finally {
201
+ store.close();
202
+ rmSync(dir, { recursive: true, force: true });
203
+ }
204
+ });
205
+
206
+ test("recent MCP calls returns newest workspace calls with agent titles", async () => {
207
+ const dir = mkdtempSync(join(tmpdir(), "recent-mcp-"));
208
+ const store = createUsageStore({ dir, driver: "sqlite" });
209
+ try {
210
+ store.upsertMany([
211
+ row({
212
+ agentId: "a1",
213
+ callId: "older",
214
+ category: "mcp",
215
+ skillName: null,
216
+ mcpServer: "github",
217
+ mcpTool: "search",
218
+ ts: "2026-09-19T10:00:00.000Z",
219
+ }),
220
+ row({
221
+ agentId: "a2",
222
+ callId: "newer",
223
+ category: "mcp",
224
+ skillName: null,
225
+ mcpServer: "paseo",
226
+ mcpTool: "list_agents",
227
+ ts: "2026-09-19T12:00:00.000Z",
228
+ }),
229
+ row({
230
+ agentId: "other",
231
+ callId: "other-workspace",
232
+ workspaceId: "w2",
233
+ category: "mcp",
234
+ skillName: null,
235
+ mcpServer: "other",
236
+ mcpTool: "tool",
237
+ ts: "2026-09-19T14:00:00.000Z",
238
+ }),
239
+ ]);
240
+ store.upsertAgents([
241
+ {
242
+ agentId: "a1",
243
+ workspaceId: "w1",
244
+ parentAgentId: null,
245
+ provider: "codex",
246
+ title: "Alpha",
247
+ createdAt: "2026-09-19T09:00:00.000Z",
248
+ archivedAt: null,
249
+ updatedAt: "2026-09-19T10:00:00.000Z",
250
+ },
251
+ ]);
252
+
253
+ const result = await createRecentMcpCallsHandler(store)({
254
+ workspaceId: "w1",
255
+ limit: 2,
256
+ });
257
+ assert.deepEqual(
258
+ result.items.map((item) => [
259
+ item.callId,
260
+ `${item.server}.${item.tool}`,
261
+ item.agentTitle,
262
+ ]),
263
+ [
264
+ ["newer", "paseo.list_agents", null],
265
+ ["older", "github.search", "Alpha"],
266
+ ],
267
+ );
268
+ } finally {
269
+ store.close();
270
+ rmSync(dir, { recursive: true, force: true });
271
+ }
272
+ });
273
+
274
+ test("usage.agent-lifetime reads spans from the registry, active agents included", async () => {
275
+ const dir = mkdtempSync(join(tmpdir(), "fast-lifetime-"));
276
+ const store = createUsageStore({ dir, driver: "sqlite" });
277
+ const registryRow = (
278
+ agentId: string,
279
+ provider: string,
280
+ createdAt: string,
281
+ archivedAt: string | null,
282
+ ) => ({
283
+ agentId,
284
+ workspaceId: "w1",
285
+ parentAgentId: null,
286
+ provider,
287
+ title: agentId,
288
+ createdAt,
289
+ archivedAt,
290
+ updatedAt: archivedAt ?? createdAt,
291
+ });
292
+ try {
293
+ store.upsertAgents([
294
+ registryRow("codex-old", "codex", "2026-09-07T03:34:09.656Z", "2026-09-18T17:18:18.001Z"),
295
+ registryRow("claude-long", "claude", "2026-09-08T03:09:29.070Z", "2026-09-19T17:18:17.939Z"),
296
+ registryRow("active", "claude", "2026-09-01T00:00:00.000Z", null),
297
+ ]);
298
+ const all = await createAgentLifetimeHandler(store)({});
299
+ // `active` spans created→now, which is wider than either archived span.
300
+ assert.equal(all.longest?.agentId, "active");
301
+ assert.equal(all.longest?.archivedAt, null);
302
+ assert.equal(all.sampleSize, 3);
303
+
304
+ const codexOnly = await createAgentLifetimeHandler(store)({ provider: "codex" });
305
+ assert.equal(codexOnly.longest?.agentId, "codex-old");
306
+ assert.equal(codexOnly.sampleSize, 1);
307
+ } finally {
308
+ store.close();
309
+ rmSync(dir, { recursive: true, force: true });
310
+ }
311
+ });
312
+
313
+ test("usage.agent-creations buckets registry rows by day and provider", async () => {
314
+ const dir = mkdtempSync(join(tmpdir(), "fast-creations-"));
315
+ const store = createUsageStore({ dir, driver: "sqlite" });
316
+ try {
317
+ store.upsertAgents(
318
+ [
319
+ ["a1", "claude-code", "2026-09-19T01:00:00.000Z"],
320
+ ["a2", "claude", "2026-09-19T02:00:00.000Z"],
321
+ ["a3", "codex", "2026-09-19T03:00:00.000Z"],
322
+ ["a4", "codex", "2026-08-01T03:00:00.000Z"],
323
+ ].map(([agentId, provider, createdAt]) => ({
324
+ agentId: agentId!,
325
+ workspaceId: "w1",
326
+ parentAgentId: null,
327
+ provider: provider!,
328
+ title: agentId!,
329
+ createdAt: createdAt!,
330
+ archivedAt: null,
331
+ updatedAt: createdAt!,
332
+ })),
333
+ );
334
+ const all = await createAgentCreationsHandler(store)({ from: "2026-09-01T00:00:00.000Z" });
335
+ assert.deepEqual(
336
+ all.days.map((day) => [day.date, day.total, day.providers.map((item) => `${item.provider}:${item.count}`)]),
337
+ [["2026-09-19", 3, ["claude:2", "codex:1"]]],
338
+ );
339
+
340
+ const codexOnly = await createAgentCreationsHandler(store)({ provider: "codex" });
341
+ assert.deepEqual(codexOnly.days.map((day) => [day.date, day.total]), [
342
+ ["2026-08-01", 1],
343
+ ["2026-09-19", 1],
344
+ ]);
345
+ } finally {
346
+ store.close();
347
+ rmSync(dir, { recursive: true, force: true });
348
+ }
349
+ });
350
+
126
351
  test("skills-by-name refreshes an empty handle and resolves project skills", async () => {
127
352
  const dir = mkdtempSync(join(tmpdir(), "fast-skills-"));
128
353
  const store = createUsageStore({ dir, driver: "sqlite" });
@@ -5,8 +5,10 @@ import { homedir } from "node:os";
5
5
  import { basename, dirname, resolve, sep } from "node:path";
6
6
  import { realpathSync, statSync } from "node:fs";
7
7
  import {
8
+ aggregateAgentCreations,
8
9
  aggregateAgents,
9
10
  aggregateByProvider,
11
+ aggregateActivityByHour,
10
12
  aggregateMcpByTool,
11
13
  aggregateShellTop,
12
14
  aggregateSkillsByName,
@@ -14,7 +16,11 @@ import {
14
16
  isFileRead,
15
17
  isFileWrite,
16
18
  isShellCall,
19
+ pickLongestAgentLifetime,
17
20
  usageActivityByDayRpc,
21
+ usageActivityByHourRpc,
22
+ usageAgentCreationsRpc,
23
+ usageAgentLifetimeRpc,
18
24
  usageAgentsRpc,
19
25
  usageAgentUnarchiveRpc,
20
26
  usageByProviderRpc,
@@ -22,6 +28,8 @@ import {
22
28
  usageListRpc,
23
29
  usageMcpByToolRpc,
24
30
  usageReadSkillRpc,
31
+ usageRecentMcpCallsRpc,
32
+ usageRecentSkillCallsRpc,
25
33
  usageSkillsByNameRpc,
26
34
  usageSummaryRpc,
27
35
  } from "../shared/usage.ts";
@@ -191,6 +199,63 @@ export function createSkillsByNameHandler(store: UsageStore) {
191
199
  };
192
200
  }
193
201
 
202
+ export function createRecentSkillCallsHandler(store: UsageStore) {
203
+ return async (
204
+ input: RpcInput<typeof usageRecentSkillCallsRpc>,
205
+ ): Promise<RpcOutput<typeof usageRecentSkillCallsRpc>> => {
206
+ const titles = new Map(
207
+ store
208
+ .selectAgents({ workspaceId: input.workspaceId })
209
+ .map((agent) => [agent.agentId, agent.title?.trim() || null] as const),
210
+ );
211
+ const items = store
212
+ .select({ workspaceId: input.workspaceId, category: "skill" })
213
+ .filter((row) => row.confidence !== "low" && row.skillName?.trim())
214
+ .sort((a, b) => {
215
+ const byTime = (b.ts ?? b.ingestedAt).localeCompare(a.ts ?? a.ingestedAt);
216
+ return byTime || b.callId.localeCompare(a.callId);
217
+ })
218
+ .slice(0, input.limit ?? 8)
219
+ .map((row) => ({
220
+ agentId: row.agentId,
221
+ agentTitle: titles.get(row.agentId) ?? null,
222
+ callId: row.callId,
223
+ skillName: row.skillName!.trim(),
224
+ calledAt: row.ts ?? row.ingestedAt,
225
+ }));
226
+ return { items };
227
+ };
228
+ }
229
+
230
+ export function createRecentMcpCallsHandler(store: UsageStore) {
231
+ return async (
232
+ input: RpcInput<typeof usageRecentMcpCallsRpc>,
233
+ ): Promise<RpcOutput<typeof usageRecentMcpCallsRpc>> => {
234
+ const titles = new Map(
235
+ store
236
+ .selectAgents({ workspaceId: input.workspaceId })
237
+ .map((agent) => [agent.agentId, agent.title?.trim() || null] as const),
238
+ );
239
+ const items = store
240
+ .select({ workspaceId: input.workspaceId, category: "mcp" })
241
+ .filter((row) => row.mcpServer?.trim() && row.mcpTool?.trim())
242
+ .sort((a, b) => {
243
+ const byTime = (b.ts ?? b.ingestedAt).localeCompare(a.ts ?? a.ingestedAt);
244
+ return byTime || b.callId.localeCompare(a.callId);
245
+ })
246
+ .slice(0, input.limit ?? 8)
247
+ .map((row) => ({
248
+ agentId: row.agentId,
249
+ agentTitle: titles.get(row.agentId) ?? null,
250
+ callId: row.callId,
251
+ server: row.mcpServer!.trim(),
252
+ tool: row.mcpTool!.trim(),
253
+ calledAt: row.ts ?? row.ingestedAt,
254
+ }));
255
+ return { items };
256
+ };
257
+ }
258
+
194
259
  export function createMcpByToolHandler(store: UsageStore) {
195
260
  return async (
196
261
  input: RpcInput<typeof usageMcpByToolRpc>,
@@ -255,6 +320,31 @@ export function createAgentsHandler(store: UsageStore) {
255
320
  };
256
321
  }
257
322
 
323
+ /** Longest created→archived agent from the registry alone (049) — no tool-call join. */
324
+ export function createAgentLifetimeHandler(store: UsageStore) {
325
+ return async (
326
+ input: RpcInput<typeof usageAgentLifetimeRpc>,
327
+ ): Promise<RpcOutput<typeof usageAgentLifetimeRpc>> => {
328
+ return pickLongestAgentLifetime(store.selectAgents({ provider: input.provider }), {
329
+ provider: input.provider,
330
+ });
331
+ };
332
+ }
333
+
334
+ /** Daily agent creations with a per-provider breakdown (051) — registry only. */
335
+ export function createAgentCreationsHandler(store: UsageStore) {
336
+ return async (
337
+ input: RpcInput<typeof usageAgentCreationsRpc>,
338
+ ): Promise<RpcOutput<typeof usageAgentCreationsRpc>> => {
339
+ const agents = store.selectAgents({
340
+ provider: input.provider,
341
+ from: input.from,
342
+ to: input.to,
343
+ });
344
+ return { days: aggregateAgentCreations(agents, input) };
345
+ };
346
+ }
347
+
258
348
  /**
259
349
  * 0.8 SDK has no reload API (handle.refresh is a read). Run CLI on this daemon's
260
350
  * machine, inheriting PATH and PASEO_HOME / PASEO_HOST / PASEO_LISTEN. CLI also
@@ -314,6 +404,33 @@ export function createActivityByDayHandler(store: UsageStore) {
314
404
  };
315
405
  }
316
406
 
407
+ export function createActivityByHourHandler(
408
+ store: UsageStore,
409
+ now: () => Date = () => new Date(),
410
+ ) {
411
+ return async (
412
+ input: RpcInput<typeof usageActivityByHourRpc>,
413
+ ): Promise<RpcOutput<typeof usageActivityByHourRpc>> => {
414
+ const end = now();
415
+ const endMs = end.getTime();
416
+ const currentHourMs = Math.floor(endMs / (60 * 60 * 1000)) * 60 * 60 * 1000;
417
+ const start = new Date(currentHourMs - (input.hours - 1) * 60 * 60 * 1000);
418
+ const filter = {
419
+ from: start.toISOString(),
420
+ to: end.toISOString(),
421
+ };
422
+ return {
423
+ hours: aggregateActivityByHour(store.select(filter), {
424
+ start,
425
+ hours: input.hours,
426
+ provider: input.provider,
427
+ agents: store.selectAgents({ ...filter, provider: input.provider }),
428
+ messages: store.selectUserMessages(filter),
429
+ }),
430
+ };
431
+ };
432
+ }
433
+
317
434
  const MAX_SKILL_BYTES = 512 * 1024;
318
435
 
319
436
  function isPathInside(absolute: string, root: string): boolean {
@@ -1,6 +1,13 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { describe, it } from "node:test";
3
- import { activityLevel, buildActivityCalendar, computeStreaks } from "./activity.ts";
3
+ import {
4
+ activityLevel,
5
+ buildActivityCalendar,
6
+ buildAgentCreationBuckets,
7
+ computeStreaks,
8
+ rankCreationProviders,
9
+ stackCreationProviders,
10
+ } from "./activity.ts";
4
11
 
5
12
  const days = [
6
13
  { date: "2026-03-07", skills: 2, mcp: 1, agents: 2, messages: 4, total: 9 },
@@ -63,18 +70,65 @@ describe("activity calendar", () => {
63
70
  assert.equal(weeklyCell?.agents, 1);
64
71
  assert.equal(weeklyCell?.messages, 3);
65
72
  });
66
- it("includes the current week across DST and marks future padding cells", () => {
73
+ it("aligns rows to weekdays across day, month, year, leap day and DST boundaries (058)", () => {
67
74
  const previous = process.env.TZ;
68
75
  process.env.TZ = "America/New_York";
69
76
  try {
70
- const result = buildActivityCalendar([], "daily", new Date(2026, 2, 1).toISOString(), new Date(2026, 2, 15));
71
- assert.equal(result.weeks.length, 52);
72
- assert.equal(result.weeks[51]?.[0]?.key, "2026-03-15");
73
- assert.equal(result.weeks[51]?.[1]?.future, true);
77
+ for (const [year, month, day] of [
78
+ [2026, 8, 19], [2026, 8, 20], [2026, 8, 21], // Saturday → Sunday → Monday
79
+ [2026, 8, 30], [2026, 9, 1],
80
+ [2026, 11, 31], [2027, 0, 1],
81
+ [2024, 1, 29], [2024, 2, 1],
82
+ [2026, 2, 8], [2026, 2, 9], [2026, 10, 1], [2026, 10, 2],
83
+ ]) {
84
+ const end = new Date(year!, month!, day!);
85
+ const label = `${year}-${month! + 1}-${day}`;
86
+ for (const mode of ["daily", "weekly", "cumulative"] as const) {
87
+ const result = buildActivityCalendar(days, mode, undefined, end);
88
+ const cells = result.weeks.flat();
89
+ assert.equal(result.weeks.length, 52, label);
90
+ assert.ok(result.weeks.every(week => week.length === 7), label);
91
+ assert.equal(new Set(cells.map(cell => cell.key)).size, 364, label);
92
+ assert.ok(cells.every(cell => !cell.excluded), label);
93
+ // Row index === weekday, Sunday first.
94
+ for (const week of result.weeks) {
95
+ week.forEach((cell, row) => {
96
+ const [y, m, d] = cell.key.split("-").map(Number);
97
+ assert.equal(new Date(y!, m! - 1, d!).getDay(), row, `${label} ${cell.key}`);
98
+ });
99
+ }
100
+ // Visible days are contiguous and end on today; the rest of the last column is future.
101
+ const visible = cells.filter(cell => !cell.future);
102
+ assert.equal(visible.length, cells.length - (6 - end.getDay()), label);
103
+ const expected = new Date(end);
104
+ for (let i = visible.length - 1; i >= 0; i--) {
105
+ const key = `${expected.getFullYear()}-${String(expected.getMonth() + 1).padStart(2, "0")}-${String(expected.getDate()).padStart(2, "0")}`;
106
+ assert.equal(visible[i]?.key, key, label);
107
+ expected.setDate(expected.getDate() - 1);
108
+ }
109
+ }
110
+ }
74
111
  } finally {
75
112
  if (previous === undefined) delete process.env.TZ; else process.env.TZ = previous;
76
113
  }
77
114
  });
115
+ it("starts the last column on the Sunday of the current week (058)", () => {
116
+ const result = buildActivityCalendar(days, "weekly", from, today);
117
+ const last = result.weeks[51]!;
118
+ assert.equal(last[0]?.key, "2026-03-08"); // Sunday of the week containing 2026-03-10
119
+ assert.equal(last[2]?.key, "2026-03-10"); // today, Tuesday
120
+ assert.ok(last.slice(3).every(cell => cell.future));
121
+ assert.equal(last[0]?.agents, 1); // natural-week total for 2026-03-08
122
+ assert.equal(last[0]?.messages, 3);
123
+ assert.equal(result.weeks[50]?.find(cell => cell.key === "2026-03-07")?.agents, 2);
124
+ });
125
+ it("carries history before the window into cumulative totals", () => {
126
+ const history = [{ date: "2020-01-01", skills: 1, mcp: 2, agents: 3, messages: 4, total: 10 }, ...days];
127
+ const cells = buildActivityCalendar(history, "cumulative", undefined, today).weeks.flat();
128
+ assert.equal(cells[0]?.total, 10);
129
+ assert.equal(cells[51 * 7 + 2]?.key, "2026-03-10");
130
+ assert.equal(cells[51 * 7 + 2]?.total, 28);
131
+ });
78
132
  it("renders empty windows and bounded intensity", () => {
79
133
  const result = buildActivityCalendar([], "daily", undefined, today);
80
134
  assert.equal(result.weeks.length, 52);
@@ -94,3 +148,66 @@ describe("activity calendar", () => {
94
148
  assert.deepEqual(computeStreaks(messageOnly, today), { current: 2, longest: 2 });
95
149
  });
96
150
  });
151
+
152
+ describe("agent creation buckets (051)", () => {
153
+ const day = (date: string, providers: Array<[string, number]>) => ({
154
+ date,
155
+ total: providers.reduce((sum, [, count]) => sum + count, 0),
156
+ providers: providers.map(([provider, count]) => ({ provider, label: provider, count })),
157
+ });
158
+
159
+ it("zero-fills the window per local day and keeps per-provider slices", () => {
160
+ const buckets = buildAgentCreationBuckets(
161
+ [day("2026-03-07", [["claude", 2]]), day("2026-03-09", [["codex", 1], ["claude", 3]])],
162
+ { from: new Date(2026, 2, 7).toISOString(), today },
163
+ );
164
+ assert.deepEqual(buckets.map((bucket) => bucket.key), ["2026-03-07", "2026-03-08", "2026-03-09", "2026-03-10"]);
165
+ assert.deepEqual(buckets.map((bucket) => bucket.count), [2, 0, 4, 0]);
166
+ assert.deepEqual(buckets[2]?.providers.map((slice) => [slice.provider, slice.count]), [["codex", 1], ["claude", 3]]);
167
+ assert.deepEqual(buckets[1]?.providers, []);
168
+ });
169
+
170
+ it("clamps to the window, drops out-of-range days, and keeps today as the last bucket", () => {
171
+ const buckets = buildAgentCreationBuckets(
172
+ [day("2026-03-01", [["claude", 5]]), day("2026-03-10", [["claude", 1]]), day("2026-03-11", [["claude", 9]])],
173
+ { from: new Date(2026, 2, 7).toISOString(), today },
174
+ );
175
+ assert.deepEqual(buckets.map((bucket) => bucket.key), ["2026-03-07", "2026-03-08", "2026-03-09", "2026-03-10"]);
176
+ assert.equal(buckets.reduce((sum, bucket) => sum + bucket.count, 0), 1);
177
+ });
178
+
179
+ it("ranks providers by window totals with a stable tie-break", () => {
180
+ const buckets = buildAgentCreationBuckets(
181
+ [
182
+ day("2026-03-08", [["codex", 1], ["claude", 1]]),
183
+ day("2026-03-09", [["claude", 2], ["amp", 3]]),
184
+ ],
185
+ { from: new Date(2026, 2, 7).toISOString(), today },
186
+ );
187
+ assert.deepEqual(rankCreationProviders(buckets).map((item) => [item.provider, item.count]), [
188
+ ["amp", 3],
189
+ ["claude", 3],
190
+ ["codex", 1],
191
+ ]);
192
+ });
193
+
194
+ it("stacks day segments by window rank with largest series at the bottom", () => {
195
+ const buckets = buildAgentCreationBuckets(
196
+ [
197
+ day("2026-03-08", [["codex", 1], ["claude", 1]]),
198
+ day("2026-03-09", [["claude", 2], ["amp", 3]]),
199
+ ],
200
+ { from: new Date(2026, 2, 7).toISOString(), today },
201
+ );
202
+ const ranked = rankCreationProviders(buckets);
203
+ // Top→bottom paint order: smallest window total present first.
204
+ assert.deepEqual(
205
+ stackCreationProviders(ranked, buckets[1]!.providers).map((s) => s.provider),
206
+ ["codex", "claude"],
207
+ );
208
+ assert.deepEqual(
209
+ stackCreationProviders(ranked, buckets[2]!.providers).map((s) => s.provider),
210
+ ["claude", "amp"],
211
+ );
212
+ });
213
+ });
@@ -1,4 +1,4 @@
1
- import type { ActivityDay } from "./usage.ts";
1
+ import type { ActivityDay, AgentCreationDay } from "./usage.ts";
2
2
 
3
3
  function pad2(value: number): string {
4
4
  return String(value).padStart(2, "0");
@@ -34,9 +34,11 @@ export type HeatmapMode = "daily" | "weekly" | "cumulative";
34
34
 
35
35
  export function buildActivityCalendar(days: readonly ActivityDay[], mode: HeatmapMode, _from?: string, today = new Date(), locale = "en") {
36
36
  const end = startOfLocalDay(today);
37
- // Always fixed 52-week year window (ChatGPT-style). Range chips filter RPC data only —
38
- // short windows must not shrink the grid (021). `_from` kept for call-site compatibility.
39
- const start = addDays(startOfWeekSunday(end), -7 * 51);
37
+ // 52 natural weeks (Sunday-start) ending with the week containing today (058):
38
+ // rows are weekdays (Sunday → Saturday), columns are calendar weeks. Days after
39
+ // today in the last column stay hidden.
40
+ // Range chips filter RPC data only (021). `_from` kept for call-site compatibility.
41
+ const start = addDays(startOfWeekSunday(end), -(51 * 7));
40
42
  const first = start;
41
43
  const daily = new Map(days.map(day => [day.date, day]));
42
44
  const weekly = new Map<string, ActivityDay>();
@@ -87,7 +89,7 @@ export function buildActivityCalendar(days: readonly ActivityDay[], mode: Heatma
87
89
  messages += raw?.messages ?? 0;
88
90
  const value =
89
91
  mode === "weekly"
90
- ? weekly.get(toDayKey(cursor))
92
+ ? weekly.get(toDayKey(startOfWeekSunday(date)))
91
93
  : mode === "cumulative"
92
94
  ? { skills, mcp, agents, messages, total: skills + mcp + agents + messages }
93
95
  : raw;
@@ -178,3 +180,99 @@ export function computeStreaks(
178
180
 
179
181
  return { current, longest };
180
182
  }
183
+
184
+ export type CreationProviderSlice = {
185
+ provider: string;
186
+ label: string;
187
+ count: number;
188
+ };
189
+
190
+ export type CreationBucket = {
191
+ /** Local day key; stable identity across refetches. */
192
+ key: string;
193
+ count: number;
194
+ /** Providers with creations that day, highest day-count first (051). Stack order uses `stackCreationProviders`. */
195
+ providers: CreationProviderSlice[];
196
+ };
197
+
198
+ const DAY_MS = 24 * 60 * 60 * 1000;
199
+
200
+ /** DST-proof day index for a local calendar date. */
201
+ function dayIndex(date: Date): number {
202
+ return Math.floor(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / DAY_MS);
203
+ }
204
+
205
+ /**
206
+ * Zero-filled daily buckets over `[from, today]` (051). Days without creations
207
+ * stay as empty buckets so the histogram never skips a date.
208
+ */
209
+ export function buildAgentCreationBuckets(
210
+ days: readonly AgentCreationDay[],
211
+ options: { from: string; today?: Date },
212
+ ): CreationBucket[] {
213
+ const today = startOfLocalDay(options.today ?? new Date());
214
+ const todayKey = toDayKey(today);
215
+ const fromDate = new Date(options.from);
216
+ const start = startOfLocalDay(Number.isNaN(fromDate.getTime()) ? today : fromDate);
217
+ const startKey = toDayKey(start);
218
+ const byDay = new Map<string, CreationProviderSlice[]>();
219
+ for (const day of days) {
220
+ if (day.date < startKey || day.date > todayKey) continue;
221
+ byDay.set(
222
+ day.date,
223
+ day.providers.filter((item) => item.count > 0),
224
+ );
225
+ }
226
+ const buckets: CreationBucket[] = [];
227
+ for (let cursor = start; dayIndex(cursor) <= dayIndex(today); cursor = addDays(cursor, 1)) {
228
+ const key = toDayKey(cursor);
229
+ const providers = byDay.get(key) ?? [];
230
+ buckets.push({
231
+ key,
232
+ count: providers.reduce((sum, item) => sum + item.count, 0),
233
+ providers,
234
+ });
235
+ }
236
+ return buckets;
237
+ }
238
+
239
+ /**
240
+ * Providers across the whole window, ranked by total creations (051). Drives
241
+ * the stable stack order and colour assignment; tooltip rows use
242
+ * `stackCreationProviders` so zero-count series are omitted (056).
243
+ */
244
+ export function rankCreationProviders(
245
+ buckets: readonly CreationBucket[],
246
+ ): CreationProviderSlice[] {
247
+ const totals = new Map<string, CreationProviderSlice>();
248
+ for (const bucket of buckets) {
249
+ for (const slice of bucket.providers) {
250
+ const current = totals.get(slice.provider);
251
+ if (current) current.count += slice.count;
252
+ else totals.set(slice.provider, { ...slice });
253
+ }
254
+ }
255
+ return [...totals.values()].sort(
256
+ (a, b) => b.count - a.count || a.provider.localeCompare(b.provider),
257
+ );
258
+ }
259
+
260
+ /**
261
+ * Day segments in top→bottom paint order for a column stack (051): follows
262
+ * window rank so every bar shares the same series order; largest window total
263
+ * sits at the bottom. Providers with no creations that day are omitted.
264
+ */
265
+ export function stackCreationProviders(
266
+ ranked: readonly CreationProviderSlice[],
267
+ dayProviders: readonly CreationProviderSlice[],
268
+ ): CreationProviderSlice[] {
269
+ const byId = new Map(dayProviders.map((slice) => [slice.provider, slice]));
270
+ // `ranked` is window-total descending; reverse so the first child (top of a
271
+ // column + flex-end stack) is the smallest series present that day.
272
+ return [...ranked]
273
+ .reverse()
274
+ .flatMap((item) => {
275
+ const slice = byId.get(item.provider);
276
+ return slice && slice.count > 0 ? [slice] : [];
277
+ });
278
+ }