Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): bot activity heatmap backend — per-day handled/sent rollup
Gusb0224f10d5ec
diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex 34dae4fa5..e422f7ab2 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -3,6 +3,7 @@ import type { HostCommand, UnreadNotice } from "../community-cli-contract";import { makeRuntimeConfig } from "../runtime-config";import { resolveModelConfig } from "./bot-model";import { formatHandle } from "../lib/discriminator";+import { utcDayKey } from "../utils/day-key";import * as message from "../db/queries/community/message";import * as bot from "../db/queries/community/bot";import * as member from "../db/queries/community/member";@@ -240,17 +241,18 @@ async function writeWakeTriggerAudit(senderHandle: `@${formatHandle(sender.name, sender.discriminator)}`,reason: (isMention ? "mention" : "unread") as "unread" | "mention",};- // Fold the "handled this lifecycle" count bump into the SAME atomic batch as- // the wake_trigger audit insert+prune — one message that triggers a wake =- // one batched round-trip, not a separate hot-path write (Cecilia's perf red- // line, #533). It shares the audit batch's all-or-nothing fate: a failed- // audit write skips the +1 too, which is fine (a dropped increment on a D1- // blip is far cheaper than a per-message extra round-trip). The counter is- // reset to 0 at nap/session_reset (`touchBotRefreshContext`).+ // Fold the "handled today" heatmap bump into the SAME atomic batch as the+ // wake_trigger audit insert+prune — one message that triggers a wake = one+ // batched round-trip, not a separate hot-path write (Cecilia's perf red line,+ // #533). It shares the audit batch's all-or-nothing fate: a failed audit+ // write skips the +1 too, which is fine (a dropped increment on a D1 blip is+ // far cheaper than a per-message extra round-trip). `day` comes from the+ // shared `utcDayKey` so it agrees with the sent-side bump for the same+ // calendar day. This rollup is a calendar fact — never zeroed on nap/reset.const inserted = await botAuditLog.insertBotAuditWakeTrigger(db,{ botId: input.botUserId, launchId: input.launchId, payload },- [bot.bumpBotHandledMessageCountStatement(db, input.botUserId)]+ [bot.bumpBotDailyActivityStatement(db, input.botUserId, utcDayKey(new Date()), "handled")]);if (!inserted || !env) return;diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 44734bdf1..addda7968 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -571,3 +571,27 @@ export const communityBotActivityEvent = sqliteTable(]);+// 22. community_bot_daily_activity+// Per-bot, per-calendar-day rollup powering the my-bots activity heatmap:+// how many messages the bot HANDLED (woke for) and SENT that day. One row per+// (botId, day); each counter is bumped +1 via an upsert that rides an EXISTING+// write batch (handled → the wake_trigger audit batch; sent → the community+// message insert batch), so there is no new hot-path round-trip. `day` is a+// UTC `YYYY-MM-DD` key computed by a single shared helper so both upserts agree+// on the day boundary. Unlike `user.handledMessageCount` (the lifecycle counter+// this replaces), this is a CALENDAR fact: it is NEVER zeroed on nap/reset and+// never touched by the FSM. Read is the last 30 days per bot (≤30 rows, covered+// by the PK), so no rolling prune is required.+export const communityBotDailyActivity = sqliteTable(+ "community_bot_daily_activity",+ {+ botId: text("bot_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ day: text("day").notNull(),+ handledCount: integer("handled_count").notNull().default(0),+ sentCount: integer("sent_count").notNull().default(0),+ },+ (t) => [primaryKey({ columns: [t.botId, t.day] })]+);+diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.tsindex 9e0de1ab6..84aa2fe1d 100644--- a/src/shared/src/db/queries/community/bot-audit-log.ts+++ b/src/shared/src/db/queries/community/bot-audit-log.ts@@ -58,8 +58,8 @@ export async function insertBotActivityEventAndPrune(data: BotActivityEventInput,/*** Extra Drizzle statements to run in the SAME atomic batch as the insert +- * prune — lets a caller fold a companion write (e.g. the per-message- * `handledMessageCount` bump on a wake_trigger) into this one round-trip+ * prune — lets a caller fold a companion write (e.g. the per-day+ * `handled` activity-rollup bump on a wake_trigger) into this one round-trip* instead of issuing a separate hot-path write. They share the batch's* all-or-nothing fate. Appended AFTER insert+prune so `results[0]` is still* the insert.@@ -201,8 +201,9 @@ export async function insertBotAuditWakeTrigger(/*** Extra Drizzle statements to fold into the SAME atomic batch as the* wake_trigger insert + prune (see `insertBotActivityEventAndPrune`). The- * wake path uses this to bump `handledMessageCount` in the one round-trip- * that already writes the audit row, rather than a separate hot-path write.+ * wake path uses this to bump the per-day `handled` activity rollup in the+ * one round-trip that already writes the audit row, rather than a separate+ * hot-path write.*/extraStatements: unknown[] = []): Promise<{ id: string; createdAt: string } | null> {diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex 9a1669409..220b02535 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -18,7 +18,7 @@* return null / 404 at the route. The victim's state must be untouched.*/-import { aliasedTable, and, count, eq, inArray, isNull, sql } from "drizzle-orm";+import { aliasedTable, and, count, eq, gte, inArray, isNull, sql } from "drizzle-orm";import { user } from "../../schema";import {communityBotBinding,@@ -31,6 +31,7 @@ import {communityFriendship,communityUserProfile,communityReadState,+ communityBotDailyActivity,} from "../../community-schema";import { communityMachine } from "../../community-machine-schema";import type { Database } from "../../index";@@ -56,12 +57,6 @@ export type BotRow = {* nap/session_reset audit chokepoint — a monotonic historical fact.*/lastRefreshContextAt: string | null;- /**- * Count of messages HANDLED in the current context lifecycle — incremented- * once per message that triggered a wake (post-gate), reset to 0 at the same- * nap/session_reset chokepoint. NOT raw messages received.- */- handledMessageCount: number;};export type BotBinding = {@@ -99,7 +94,6 @@ export async function listBotsForOwner(createdAt: user.createdAt,updatedAt: user.updatedAt,lastRefreshContextAt: user.lastRefreshContextAt,- handledMessageCount: user.handledMessageCount,description: communityUserProfile.aboutMe,machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,@@ -128,7 +122,6 @@ export async function listBotsForOwner(createdAt: r.createdAt,updatedAt: r.updatedAt,lastRefreshContextAt: r.lastRefreshContextAt ?? null,- handledMessageCount: r.handledMessageCount ?? 0,machineId: r.machineId,runtime: r.runtime,modelName: r.modelName ?? null,@@ -154,7 +147,6 @@ export async function getBotOwnedBy(createdAt: user.createdAt,updatedAt: user.updatedAt,lastRefreshContextAt: user.lastRefreshContextAt,- handledMessageCount: user.handledMessageCount,description: communityUserProfile.aboutMe,machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,@@ -187,7 +179,6 @@ export async function getBotOwnedBy(createdAt: r.createdAt,updatedAt: r.updatedAt,lastRefreshContextAt: r.lastRefreshContextAt ?? null,- handledMessageCount: r.handledMessageCount ?? 0,machineId: r.machineId ?? null,runtime: r.runtime ?? null,modelName: r.modelName ?? null,@@ -669,12 +660,11 @@ export async function updateBotModel(}/**- * Record a context refresh on a bot: stamp `lastRefreshContextAt` and zero- * `handledMessageCount` (the current lifecycle just ended). Called at — and- * ONLY at — the two audit chokepoints that record a refresh: `nap`+ * Record a context refresh on a bot: stamp `lastRefreshContextAt`. Called at —+ * and ONLY at — the two audit chokepoints that record a refresh: `nap`* (self-initiated) and `session_reset` (owner). Keeping this the single write- * point is what makes both fields monotonic-per-lifecycle facts that never- * drift from the audit log or the live FSM. Scoped to `isBot=true` and not+ * point is what makes the field a monotonic historical fact that never drifts+ * from the audit log or the live FSM. Scoped to `isBot=true` and not* soft-deleted; the caller has already authorized the action (runner-key for* nap, owner for reset), so no ownerUserId predicate here. `now` is injected so* callers pass the same instant they wrote the audit row.@@ -686,26 +676,121 @@ export async function touchBotRefreshContext(): Promise<void> {await db.update(user)- .set({ lastRefreshContextAt: now, handledMessageCount: 0 })+ .set({ lastRefreshContextAt: now }).where(and(eq(user.id, botId), eq(user.isBot, true), isNull(user.deletedAt)));}/**- * Drizzle statement that increments a bot's `handledMessageCount` by one, scoped- * to a live bot. Exposed as a statement builder (not an awaited write) so it can- * be composed into the SAME `db.batch([...])` as the per-message wake_trigger- * audit insert — one message that triggers a wake = one batched round-trip that- * writes the audit row AND bumps the count, not two. The counter is reset to 0- * by `touchBotRefreshContext` at each nap/session_reset. Riding the audit batch- * means it shares that batch's all-or-nothing fate (a failed wake_trigger write- * skips the bump too) — acceptable: a dropped +1 on a D1 blip is far cheaper- * than an extra hot-path round-trip per message.+ * Drizzle statement that bumps a bot's per-day activity rollup by one, for the+ * my-bots heatmap. `column` selects which counter — `handled` (rides the+ * wake_trigger audit batch, one bump per message the bot woke for) or `sent`+ * (rides the community_message insert batch, one bump per message the bot+ * sends). Exposed as a statement builder (not an awaited write) so it composes+ * into the SAME `db.batch([...])` as that existing write — no new hot-path+ * round-trip. `day` MUST come from `utcDayKey` (the single day-boundary source)+ * so handled and sent for the same calendar day land in the same `(botId, day)`+ * row. Sharing the host batch's all-or-nothing fate is acceptable: a dropped +1+ * on a D1 blip is far cheaper than a per-message extra round-trip.+ *+ * Unlike the retired `handledMessageCount`, this rollup is a CALENDAR fact — it+ * is never zeroed on nap/reset and never touched by the FSM.*/-export function bumpBotHandledMessageCountStatement(db: Database, botId: string) {+export function bumpBotDailyActivityStatement(+ db: Database,+ botId: string,+ day: string,+ column: "handled" | "sent"+) {+ const isHandled = column === "handled";return db- .update(user)- .set({ handledMessageCount: sql`${user.handledMessageCount} + 1` })- .where(and(eq(user.id, botId), eq(user.isBot, true), isNull(user.deletedAt)));+ .insert(communityBotDailyActivity)+ .values({+ botId,+ day,+ handledCount: isHandled ? 1 : 0,+ sentCount: isHandled ? 0 : 1,+ })+ .onConflictDoUpdate({+ target: [communityBotDailyActivity.botId, communityBotDailyActivity.day],+ set: isHandled+ ? { handledCount: sql`${communityBotDailyActivity.handledCount} + 1` }+ : { sentCount: sql`${communityBotDailyActivity.sentCount} + 1` },+ });+}++export interface BotDailyActivityRow {+ day: string;+ handledCount: number;+ sentCount: number;+}++/**+ * Read a bot's per-day activity for the heatmap: rows with `day >= sinceDay`,+ * ascending. At most ~30 rows (the caller passes `sinceDay = today - 29`),+ * covered by the `(botId, day)` PK. A bot with no activity yet returns `[]`+ * (the caller/FE pads the missing days to zero cells — an empty array is the+ * normal new-bot path, not an error).+ */+export async function getBotDailyActivity(+ db: Database,+ botId: string,+ sinceDay: string+): Promise<BotDailyActivityRow[]> {+ const rows = await db+ .select({+ day: communityBotDailyActivity.day,+ handledCount: communityBotDailyActivity.handledCount,+ sentCount: communityBotDailyActivity.sentCount,+ })+ .from(communityBotDailyActivity)+ .where(+ and(+ eq(communityBotDailyActivity.botId, botId),+ gte(communityBotDailyActivity.day, sinceDay)+ )+ )+ .orderBy(communityBotDailyActivity.day);+ return rows;+}++/**+ * Batch read of per-day activity for ALL of an owner's bots in a single query,+ * so the my-bots list attaches heatmaps without N+1. Rows are scoped to bots+ * the caller owns (join on `user.ownerUserId`, isBot, not soft-deleted) and to+ * `day >= sinceDay`. Returns a Map keyed by botId → that bot's rows (ascending+ * day); a bot with no activity is simply absent from the map (the caller+ * defaults it to `[]`).+ */+export async function getBotDailyActivityForOwner(+ db: Database,+ ownerId: string,+ sinceDay: string+): Promise<Map<string, BotDailyActivityRow[]>> {+ const rows = await db+ .select({+ botId: communityBotDailyActivity.botId,+ day: communityBotDailyActivity.day,+ handledCount: communityBotDailyActivity.handledCount,+ sentCount: communityBotDailyActivity.sentCount,+ })+ .from(communityBotDailyActivity)+ .innerJoin(user, eq(user.id, communityBotDailyActivity.botId))+ .where(+ and(+ eq(user.ownerUserId, ownerId),+ eq(user.isBot, true),+ isNull(user.deletedAt),+ gte(communityBotDailyActivity.day, sinceDay)+ )+ )+ .orderBy(communityBotDailyActivity.day);+ const byBot = new Map<string, BotDailyActivityRow[]>();+ for (const r of rows) {+ const list = byBot.get(r.botId) ?? [];+ list.push({ day: r.day, handledCount: r.handledCount, sentCount: r.sentCount });+ byBot.set(r.botId, list);+ }+ return byBot;}/**diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex cb23646e7..ee8fa235b 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -103,6 +103,16 @@ export type CreateMessageData = {* today's behavior (never deduped). See mutation-idempotency plan.*/clientNonce?: string;+ /**+ * Extra Drizzle statements to commit in the SAME atomic batch as the message+ * insert (zero new round-trip). The bot-send routes use this to bump the+ * per-day sent activity rollup for the heatmap; human sends pass nothing. The+ * statements run only if the message row is written (they share the batch's+ * all-or-nothing fate — and if the CAS seq claim above loses, the batch never+ * runs, so a lost race correctly skips them). This function stays+ * identity-agnostic: the CALLER decides what to append, not `createMessage`.+ */+ extraStatements?: unknown[];};/**@@ -196,7 +206,11 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb.where(eq(communityChannel.id, data.channelId));type InsertedMessage = Awaited<typeof insertMsg>[number];- const results = (await db.batch([insertMsg, scopeUpdate] as any)) as any[];+ // Caller-supplied extra statements (e.g. the bot sent-activity rollup bump)+ // ride this same batch — appended AFTER insert+scope so the message row is+ // index 0. They share the batch's all-or-nothing commit.+ const batchStatements = [insertMsg, scopeUpdate, ...(data.extraStatements ?? [])];+ const results = (await db.batch(batchStatements as any)) as any[];const msg = (results[0] as InsertedMessage[])[0]!;// Author read-watermark: advance the sender's own read-state to thisdiff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex d29b8b570..119d1cc2d 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -44,11 +44,6 @@ export const user = sqliteTable(// historical fact that never drifts from the audit log. NULL = never// refreshed. Surfaced in the my-bots list as "last refreshed N ago".lastRefreshContextAt: text("lastRefreshContextAt"),- // For bots: count of messages HANDLED in the current context lifecycle —- // incremented once per message that triggered a wake (post-gate), reset to- // 0 at the same nap/session_reset chokepoint. NOT raw messages received;- // gate-filtered messages the agent never woke for are excluded.- handledMessageCount: integer("handledMessageCount", { mode: "number" }).notNull().default(0),},(t) => [index("idx_user_ownerUserId_isBot").on(t.ownerUserId, t.isBot)]);diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 3df362cf4..f6fca9de7 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -532,7 +532,7 @@ export { withD1Retry, readOrStale, isRetryableD1Error } from "./db/resilience";export type { RetryOpts } from "./db/resilience";export * as schema from "./db/schema";export * as queries from "./db/queries-index";-export { communityServer, communityServerInvite, communityFriendship, communityServerMember, communityServerFolder, communityServerFolderItem, communityBotActivityEvent } from "./db/community-schema";+export { communityServer, communityServerInvite, communityFriendship, communityServerMember, communityServerFolder, communityServerFolderItem, communityBotActivityEvent, communityBotDailyActivity } from "./db/community-schema";// Loggerexport { Logger, createLogger } from "./logger"@@ -566,6 +566,7 @@ export type { PromptAgent, PromptMention, ParseResult } from "./utils/prompt-parexport { MENTION_TOKEN_RE, stripMentionTokens } from "./utils/mention-token";export { isValidToken, isValidEmail } from "./utils/validation";export { escapeLikePattern } from "./utils/sql-like";+export { utcDayKey, utcDayKeyDaysAgo } from "./utils/day-key";export { isOnline, formatStatus, isPresenceOnline, isPresenceOffline } from "./utils/status";export { isUniqueConstraintError } from "./utils/db-errors";export { generateWorkspaceSlug, sanitizeSlug, slugSuffix } from "./utils/slug";diff --git a/src/shared/src/utils/day-key.ts b/src/shared/src/utils/day-key.tsnew file mode 100644index 000000000..066d680d3--- /dev/null+++ b/src/shared/src/utils/day-key.ts@@ -0,0 +1,26 @@+/**+ * The single source of truth for the calendar-day key used by the bot activity+ * heatmap. Both rollup upserts (handled and sent, written from different code+ * paths) MUST derive "today" through this one helper: if they diverged on the+ * day boundary (e.g. UTC vs local time), the same calendar day's handled and+ * sent counts would land in different `(botId, day)` rows and the two series+ * would misalign, mis-coloring the single-cell total the UI renders.+ *+ * UTC `YYYY-MM-DD`. Accepts a `Date` or an ISO string (or ms epoch) so callers+ * can pass whatever "now" they already hold.+ */+export function utcDayKey(now: Date | string | number): string {+ const d = now instanceof Date ? now : new Date(now)+ return d.toISOString().slice(0, 10)+}++/**+ * The UTC `YYYY-MM-DD` key `days` calendar days before `now` (inclusive-window+ * lower bound). The heatmap read passes `utcDayKeyDaysAgo(now, 29)` so a 30-day+ * window (today + the 29 preceding days) is returned.+ */+export function utcDayKeyDaysAgo(now: Date | string | number, days: number): string {+ const d = now instanceof Date ? new Date(now.getTime()) : new Date(now)+ d.setUTCDate(d.getUTCDate() - days)+ return utcDayKey(d)+}diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.tsindex 49e03443f..b75a80c41 100644--- a/src/shared/test/community/wake-dispatch-build.test.ts+++ b/src/shared/test/community/wake-dispatch-build.test.ts@@ -6,10 +6,10 @@ vi.mock("../../src/db/queries/community/message", () => ({}));const mockGetBotWakeContext = vi.fn();-const mockBumpBotHandledMessageCountStatement = vi.fn(() => ({ __stmt: "bump" }));+const mockBumpBotDailyActivityStatement = vi.fn(() => ({ __stmt: "bump" }));vi.mock("../../src/db/queries/community/bot", () => ({getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),- bumpBotHandledMessageCountStatement: (...a: unknown[]) => mockBumpBotHandledMessageCountStatement(...a),+ bumpBotDailyActivityStatement: (...a: unknown[]) => mockBumpBotDailyActivityStatement(...a),}));const mockHasMentionForMessage = vi.fn();@@ -296,12 +296,17 @@ describe("buildUnreadWakeCommand", () => {reason: "unread",},});- // handledMessageCount rides the SAME atomic batch as the audit insert:- // the +1 statement is built for this bot and handed to- // insertBotAuditWakeTrigger as an extra batch statement — one round-trip,+ // The per-day "handled" activity rollup rides the SAME atomic batch as the+ // audit insert: the upsert statement is built for this bot+today and handed+ // to insertBotAuditWakeTrigger as an extra batch statement — one round-trip,// not a separate hot-path write (Cecilia's perf red line).- expect(mockBumpBotHandledMessageCountStatement).toHaveBeenCalledTimes(1);- expect(mockBumpBotHandledMessageCountStatement).toHaveBeenCalledWith(expect.anything(), "bot_1");+ expect(mockBumpBotDailyActivityStatement).toHaveBeenCalledTimes(1);+ expect(mockBumpBotDailyActivityStatement).toHaveBeenCalledWith(+ expect.anything(),+ "bot_1",+ expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),+ "handled",+ );const [, , extraStatements] = mockInsertBotAuditWakeTrigger.mock.calls[0]!;expect(extraStatements).toEqual([{ __stmt: "bump" }]);});@@ -320,9 +325,9 @@ describe("buildUnreadWakeCommand", () => {await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });expect(mockInsertBotAuditWakeTrigger).not.toHaveBeenCalled();- // Skipped wake never handled the message → no count bump statement is even- // built (rides the same post-gate chokepoint as the audit write).- expect(mockBumpBotHandledMessageCountStatement).not.toHaveBeenCalled();+ // Skipped wake never handled the message → no activity bump statement is+ // even built (rides the same post-gate chokepoint as the audit write).+ expect(mockBumpBotDailyActivityStatement).not.toHaveBeenCalled();});it("wake still fires when the audit insert throws (best-effort, MUST NOT gate the wake)", async () => {diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.tsindex 9db08b1b8..827d34dba 100644--- a/src/shared/test/queries/community-bot.test.ts+++ b/src/shared/test/queries/community-bot.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, vi } from "vitest"+import { drizzle } from "drizzle-orm/d1"import * as q from "../../src/db/queries/community/bot"import {communityBotSyntheticEmail,@@ -24,6 +25,12 @@ describe("community/bot exports", () => {expect(typeof q.getMachineForOwner).toBe("function")})+ it("exposes bot-activity heatmap helpers", () => {+ expect(typeof q.bumpBotDailyActivityStatement).toBe("function")+ expect(typeof q.getBotDailyActivity).toBe("function")+ expect(typeof q.getBotDailyActivityForOwner).toBe("function")+ })+it("exposes write helpers", () => {expect(typeof q.createBot).toBe("function")expect(typeof q.updateBot).toBe("function")@@ -236,3 +243,29 @@ describe("bot limits", () => {expect(COMMUNITY_BOT_NAME_MAX).toBe(32)})})++describe("bumpBotDailyActivityStatement", () => {+ const fakeDb = drizzle({} as never)++ it("handled: inserts (1,0) and ON CONFLICT bumps handled_count", () => {+ const { sql: text, params } = q+ .bumpBotDailyActivityStatement(fakeDb, "bot_1", "2026-07-31", "handled")+ .toSQL()+ // upsert on the (bot_id, day) PK+ expect(text).toContain('insert into "community_bot_daily_activity"')+ expect(text).toContain("on conflict")+ // seeds handled=1/sent=0, updates handled_count = handled_count + 1+ expect(text).toContain('"handled_count" = "community_bot_daily_activity"."handled_count" + 1')+ expect(text).not.toContain('"sent_count" = ')+ expect(params).toEqual(["bot_1", "2026-07-31", 1, 0])+ })++ it("sent: inserts (0,1) and ON CONFLICT bumps sent_count", () => {+ const { sql: text, params } = q+ .bumpBotDailyActivityStatement(fakeDb, "bot_1", "2026-07-31", "sent")+ .toSQL()+ expect(text).toContain('"sent_count" = "community_bot_daily_activity"."sent_count" + 1')+ expect(text).not.toContain('"handled_count" = ')+ expect(params).toEqual(["bot_1", "2026-07-31", 0, 1])+ })+})diff --git a/src/shared/test/utils/day-key.test.ts b/src/shared/test/utils/day-key.test.tsnew file mode 100644index 000000000..ee2b75216--- /dev/null+++ b/src/shared/test/utils/day-key.test.ts@@ -0,0 +1,47 @@+import { describe, it, expect } from "vitest"+import { utcDayKey, utcDayKeyDaysAgo } from "../../src/utils/day-key"++describe("utcDayKey", () => {+ it("returns the UTC YYYY-MM-DD for a Date", () => {+ expect(utcDayKey(new Date("2026-07-31T10:00:00Z"))).toBe("2026-07-31")+ })++ it("accepts an ISO string and an epoch-ms number", () => {+ expect(utcDayKey("2026-07-31T23:59:59Z")).toBe("2026-07-31")+ expect(utcDayKey(Date.parse("2026-01-01T00:00:00Z"))).toBe("2026-01-01")+ })++ it("keys by UTC, not local time — an instant late in a UTC day stays that day", () => {+ // 23:30 UTC is the same UTC calendar day regardless of the runner's tz;+ // this is what keeps the handled and sent upserts on the same (botId, day)+ // row for one calendar day (the single-source red line).+ expect(utcDayKey("2026-07-31T23:30:00Z")).toBe("2026-07-31")+ expect(utcDayKey("2026-08-01T00:30:00Z")).toBe("2026-08-01")+ })++ it("is stable for the same instant across call sites (handled vs sent agree)", () => {+ const instant = "2026-07-31T12:34:56Z"+ expect(utcDayKey(instant)).toBe(utcDayKey(new Date(instant)))+ })+})++describe("utcDayKeyDaysAgo", () => {+ it("returns the key N days before, inclusive-window lower bound", () => {+ // 29 days before 2026-07-31 = 2026-07-02 (a 30-day window incl. today).+ expect(utcDayKeyDaysAgo(new Date("2026-07-31T10:00:00Z"), 29)).toBe("2026-07-02")+ })++ it("0 days ago is today", () => {+ expect(utcDayKeyDaysAgo("2026-07-31T10:00:00Z", 0)).toBe("2026-07-31")+ })++ it("crosses month and year boundaries correctly", () => {+ expect(utcDayKeyDaysAgo("2026-01-05T10:00:00Z", 10)).toBe("2025-12-26")+ })++ it("does not mutate the passed Date", () => {+ const d = new Date("2026-07-31T10:00:00Z")+ utcDayKeyDaysAgo(d, 29)+ expect(d.toISOString()).toBe("2026-07-31T10:00:00.000Z")+ })+})diff --git a/src/web/migrations/0074_bot_daily_activity.sql b/src/web/migrations/0074_bot_daily_activity.sqlnew file mode 100644index 000000000..3f11ad89d--- /dev/null+++ b/src/web/migrations/0074_bot_daily_activity.sql@@ -0,0 +1,31 @@+-- My-bots activity heatmap (Gus /Gus/working #608): replace the single+-- "Handled N msgs" lifecycle counter with a GitHub-style 30-day contribution+-- grid — per bot, per calendar day, how many messages it HANDLED (woke for)+-- and SENT.+--+-- Data source is a per-day rollup table, NOT an aggregate of existing tables:+-- community_bot_activity_event is a rolling 500-row/bot audit log (8 event+-- kinds share the budget) so a busy bot prunes 30-day-old rows within days;+-- and aggregating community_message for sent would need a (author_id,+-- created_at) index on the hottest table. The rollup avoids both.+--+-- Each counter is bumped +1 by an upsert that RIDES an existing write batch+-- (handled → the wake_trigger audit batch; sent → the community_message insert+-- batch), so there is no new hot-path round-trip. `day` is a UTC YYYY-MM-DD key+-- from a single shared helper so both upserts agree on the boundary. Unlike the+-- handledMessageCount column dropped below, this is a CALENDAR fact — never+-- zeroed on nap/reset, never touched by the FSM. Read is the last 30 days per+-- bot (<=30 rows, covered by the PK), so no rolling prune is needed.+CREATE TABLE community_bot_daily_activity (+ bot_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ day TEXT NOT NULL,+ handled_count INTEGER NOT NULL DEFAULT 0,+ sent_count INTEGER NOT NULL DEFAULT 0,+ PRIMARY KEY (bot_id, day)+);++-- Drop the lifecycle counter this heatmap replaces. `lastRefreshContextAt`+-- stays — it is a separate "last refresh N ago" indicator, still written at the+-- nap/session_reset audit chokepoint. Deploy code that stops reading/writing+-- handledMessageCount BEFORE running this migration.+ALTER TABLE user DROP COLUMN handledMessageCount;diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.tsindex 823200578..ec4008023 100644--- a/src/web/src/app/api/community/bots/route.test.ts+++ b/src/web/src/app/api/community/bots/route.test.ts@@ -7,6 +7,8 @@ const mockCreateBot = vi.fn()const mockGetUserPublic = vi.fn()const mockPushBotEventToMachine = vi.fn()const mockLogAudit = vi.fn()+const mockListBotsForOwner = vi.fn()+const mockGetBotDailyActivityForOwner = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -23,6 +25,8 @@ vi.mock("@alook/shared", async () => {countLiveBotsForOwner: (...a: unknown[]) => mockCountLiveBotsForOwner(...a),getMachineForOwner: (...a: unknown[]) => mockGetMachineForOwner(...a),createBot: (...a: unknown[]) => mockCreateBot(...a),+ listBotsForOwner: (...a: unknown[]) => mockListBotsForOwner(...a),+ getBotDailyActivityForOwner: (...a: unknown[]) => mockGetBotDailyActivityForOwner(...a),},user: {getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),@@ -56,7 +60,11 @@ vi.mock("@/lib/middleware/helpers", async () => {}})-import { POST } from "./route"+import { GET, POST } from "./route"++function getReq() {+ return new NextRequest("http://localhost/api/community/bots", { method: "GET" })+}function postReq(body: unknown) {return new NextRequest("http://localhost/api/community/bots", {@@ -115,3 +123,44 @@ describe("POST /api/community/bots — model", () => {expect(mockCreateBot).not.toHaveBeenCalled()})})++describe("GET /api/community/bots — heatmap activity", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it("attaches each bot's 30-day dailyActivity from the batched owner read", async () => {+ mockListBotsForOwner.mockResolvedValue([+ { id: "bot_1", name: "A", machineId: "m1", runtime: "claude", modelName: null },+ { id: "bot_2", name: "B", machineId: "m1", runtime: "claude", modelName: null },+ ])+ const byBot = new Map<string, unknown[]>([+ ["bot_1", [{ day: "2026-07-31", handledCount: 3, sentCount: 1 }]],+ ])+ mockGetBotDailyActivityForOwner.mockResolvedValue(byBot)++ const res = await GET(getReq(), ctx)+ expect(res.status).toBe(200)+ const body = (await res.json()) as { bots: Array<{ id: string; dailyActivity: unknown[] }> }+ // bot_1 gets its rows; bot_2 (absent from the map) defaults to [] — the+ // normal new-bot path, not an error.+ expect(body.bots.find((b) => b.id === "bot_1")?.dailyActivity).toEqual([+ { day: "2026-07-31", handledCount: 3, sentCount: 1 },+ ])+ expect(body.bots.find((b) => b.id === "bot_2")?.dailyActivity).toEqual([])+ // Scoped to the caller (u1) and a 30-day (29-days-ago) window.+ expect(mockGetBotDailyActivityForOwner).toHaveBeenCalledWith(+ expect.anything(),+ "u1",+ expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),+ )+ })++ it("returns an empty bots array when the owner has none", async () => {+ mockListBotsForOwner.mockResolvedValue([])+ mockGetBotDailyActivityForOwner.mockResolvedValue(new Map())+ const res = await GET(getReq(), ctx)+ expect(res.status).toBe(200)+ expect((await res.json()) as { bots: unknown[] }).toEqual({ bots: [] })+ })+})diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.tsindex e5871c4ac..0dc396bba 100644--- a/src/web/src/app/api/community/bots/route.ts+++ b/src/web/src/app/api/community/bots/route.ts@@ -4,6 +4,7 @@ import {CommunityBotCreateRequestSchema,COMMUNITY_BOT_LIMIT_PER_OWNER,runtimeSupportsModel,+ utcDayKeyDaysAgo,} from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"@@ -14,7 +15,21 @@ import { pushBotEventToMachine } from "@/lib/community/bot-push"export const GET = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)const bots = await queries.communityBot.listBotsForOwner(db, ctx.userId)- return writeJSON({ bots })+ // Attach each bot's last-30-day activity for the my-bots heatmap. One batched+ // read scoped to the owner's bots (no N+1); bots with no rows default to [].+ // The FE pads missing days to zero cells, so an empty array is the normal+ // new-bot path.+ const sinceDay = utcDayKeyDaysAgo(new Date(), 29)+ const activityByBot = await queries.communityBot.getBotDailyActivityForOwner(+ db,+ ctx.userId,+ sinceDay,+ )+ const withActivity = bots.map((bot) => ({+ ...bot,+ dailyActivity: activityByBot.get(bot.id) ?? [],+ }))+ return writeJSON({ bots: withActivity })})export const POST = withAuth(async (req: NextRequest, ctx) => {diff --git a/src/web/src/app/api/community/send/route.test.ts b/src/web/src/app/api/community/send/route.test.tsindex 775b9de34..2fbd0f925 100644--- a/src/web/src/app/api/community/send/route.test.ts+++ b/src/web/src/app/api/community/send/route.test.ts@@ -20,6 +20,7 @@ const mockFindActiveAgentRunnerKeyByBearer = vi.fn()const mockGetUserInternal = vi.fn()const mockGetUserByNameAndDiscriminator = vi.fn()const mockGetBotBinding = vi.fn()+const mockBumpBotDailyActivityStatement = vi.fn(() => ({ __stmt: "sent-bump" }))const mockResolveServerByNameForMember = vi.fn()const mockResolveChannelByNameForMember = vi.fn()const mockGetChannelForMember = vi.fn()@@ -46,7 +47,12 @@ vi.mock("@alook/shared", async () => {getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),},- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },+ communityBot: {+ getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a),+ // Sentinel — the route builds this into `extraStatements`; the upsert+ // SQL itself is verified in the shared community-bot test.+ bumpBotDailyActivityStatement: (...a: unknown[]) => mockBumpBotDailyActivityStatement(...a),+ },communityFriendship: {isBlocked: (...a: unknown[]) => mockIsBlocked(...a),areFriends: (...a: unknown[]) => mockAreFriends(...a),@@ -435,4 +441,26 @@ describe("POST /api/community/agent/send", () => {expect.objectContaining({ body: { content: "hi", replyToId: undefined } }))})++ it("heatmap: a bot send bumps its per-day SENT rollup, folded into the message batch", async () => {+ mockGetLatestSeqForScope.mockResolvedValue(5)+ mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 6, content: "hi" } })+ const res = await POST(+ req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })+ )+ expect(res.status).toBe(200)+ // The "sent" upsert is built for THIS bot + today's UTC day key and handed+ // to createCommunityMessage as an extra batch statement — it rides the+ // message insert batch (zero new round-trip), not a separate write.+ expect(mockBumpBotDailyActivityStatement).toHaveBeenCalledWith(+ expect.anything(),+ "bot_1",+ expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),+ "sent",+ )+ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(+ expect.objectContaining({ extraStatements: [{ __stmt: "sent-bump" }] })+ )+ })})diff --git a/src/web/src/app/api/community/send/route.ts b/src/web/src/app/api/community/send/route.tsindex 9201dbc0e..03af6829c 100644--- a/src/web/src/app/api/community/send/route.ts+++ b/src/web/src/app/api/community/send/route.ts@@ -1,5 +1,5 @@import { NextResponse, type NextRequest } from "next/server"-import { queries, withD1Retry, CommunityAgentSendRequestSchema } from "@alook/shared"+import { queries, withD1Retry, CommunityAgentSendRequestSchema, utcDayKey } from "@alook/shared"import { getDb } from "@/lib/db"import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"@@ -200,6 +200,12 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {expectedSeq: latestSeq,attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,clientNonce: body.nonce,+ // Heatmap: bump this bot's per-day SENT rollup in the SAME batch as the+ // message insert (zero new round-trip). Only the bot-send routes pass this,+ // so human sends never bump; `createMessage` stays identity-agnostic.+ extraStatements: [+ queries.communityBot.bumpBotDailyActivityStatement(db, botUserId, utcDayKey(new Date()), "sent"),+ ],})if (!result.ok) {if (result.status === 409) {diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 79e178684..20fda69b0 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -223,6 +223,15 @@ export async function createCommunityMessage(params: {* and fires no side effects. Absent = today's behavior (no dedup lookup).*/clientNonce?: string+ /**+ * Extra Drizzle statements to commit in the SAME batch as the message insert+ * (zero new round-trip). Threaded straight into `createMessage`. The bot-send+ * routes use this to bump the per-day sent-activity heatmap rollup; human+ * sends pass nothing. Runs only if the row is written (shares the batch's+ * all-or-nothing fate; a lost CAS seq claim skips it). This handler stays+ * identity-agnostic — the bot-only caller supplies the statement.+ */+ extraStatements?: unknown[]}): Promise<CreateMessageResult> {const {db,@@ -239,6 +248,7 @@ export async function createCommunityMessage(params: {attachmentIds,skipChildChannelUpdate,clientNonce,+ extraStatements,} = paramsconst content = typeof body.content === "string" ? body.content : ""@@ -341,6 +351,7 @@ export async function createCommunityMessage(params: {mentionType: MentionType | undefined;type?: string;clientNonce?: string;+ extraStatements?: unknown[];} = {authorId,content,@@ -349,6 +360,7 @@ export async function createCommunityMessage(params: {mentionType,...(messageType !== undefined ? { type: messageType } : {}),...(clientNonce !== undefined ? { clientNonce } : {}),+ ...(extraStatements !== undefined ? { extraStatements } : {}),}// Insert first so `reserveAttachmentsForMessage`'s UPDATE can key off