feat(activity): ingest local Claude Code chats into unified timeline

Before this commit, /activity only knew about prompts dispatched through
/control and runs spawned by orchestration. The much larger pool of
context — every time the founder typed into a local Claude Code session
in their terminal — sat invisible on disk in the JSONL transcripts the
CLI writes to ~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl. The
"god-level context-aware" ask is to fuse the two streams so /activity
becomes "everything you typed about this project anywhere," which is
what an agent fleet's activity view should always have been.

Mechanism:
  1. New table claude_code_history mirrors per-event metadata from the
     JSONL transcripts. (session_id, event_uuid) is UNIQUE so re-ingest
     is idempotent — incremental sync is just a re-run.
  2. scripts/ingest-claude-code-history.ts walks the projects dir,
     resolves cwd → user_projects.dir_path → projectKey, and inserts
     user + assistant turns with ON CONFLICT DO NOTHING. Backfilled the
     31,284 historical events on first run (FleetCrown 11.7k, revamp-it
     6.3k, OrangeCat 5.2k, etc.).
  3. digests.ts pulls the user-only slice into the digest timeline as
     a new "local_chat" kind, includes those events in per-project
     activity counts so the chip wall ranks projects honestly, and
     bumps MAX_TIMELINE_ITEMS 80→120 so a busy day fits without
     starving prompts/runs.

EventStream renders the new kind without changes — it was already
content-agnostic. A FilterCard toggle for "include/exclude local chats"
is a natural follow-up but the timeline is already useful as-is.

Schema applied to local Postgres via raw SQL because drizzle-kit push
wanted to interactively confirm an unrelated agent_tokens.token
constraint backfill. The schema file is the SSOT; this commit is the
source of truth a future migration tool will diff against.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mao NakamotoandClaude Opus 4.7 committed 2026-06-10 17:15:23 +02:00
1 parent 83d07ef1bf
commit 7293d3bf0f
5 files changed
+308 -6

No files matched your search

+1
View File
@@ -31,6 +31,7 @@
"test:activity-ssot": "node scripts/activity-ssot-check.mjs",
"test:digest": "npx tsx scripts/test/digest.ts",
"generate:agent-prompts": "npx tsx scripts/generate-agent-prompts.ts",
"ingest:history": "npx tsx scripts/ingest-claude-code-history.ts",
"desktop:dev": "cd desktop && npm run dev",
"desktop:build": "cd desktop && npm run build",
"desktop:preview": "cd desktop && npm run preview",
+208
View File
@@ -0,0 +1,208 @@
// Ingest local Claude Code conversation transcripts into the FleetCrown DB so
// /activity can show "what was typed locally" alongside "what was dispatched
// through /control." Source of truth is the per-session JSONL the CLI writes
// at ~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl.
//
// Idempotent: dedup key is (session_id, event_uuid). Re-runs over the same
// JSONL files are no-ops. Incremental ingest is just a re-run — JSONLs only
// grow, conflicts swallow already-ingested events.
//
// Usage:
// npm run ingest:history # one-shot, every JSONL under ~/.claude/projects
// tsx scripts/ingest-claude-code-history.ts --dir <abs-path> # one specific JSONL dir
// tsx scripts/ingest-claude-code-history.ts --since <ISO> # skip files older than ISO
import { readdir, readFile, stat } from "node:fs/promises";
import { join } from "node:path";
import { homedir } from "node:os";
import { db } from "@/db";
import { claudeCodeHistory, type NewClaudeCodeHistoryRow } from "@/db/schema/claude-code-history";
import { userProjects } from "@/db/schema/user-projects";
import { getDefaultUser } from "@/db/queries/users";
import { eq, and } from "drizzle-orm";
const CLAUDE_PROJECTS_DIR = join(homedir(), ".claude", "projects");
type JsonlEvent = {
type?: string;
uuid?: string;
sessionId?: string;
timestamp?: string;
cwd?: string;
gitBranch?: string;
message?: {
role?: string;
content?: string | Array<{ type?: string; text?: string }>;
};
};
function extractText(content: JsonlEvent["message"] extends { content: infer C } ? C : unknown): string {
if (typeof content === "string") return content.trim();
if (!Array.isArray(content)) return "";
const parts: string[] = [];
for (const item of content) {
if (item && typeof item === "object" && "text" in item && typeof item.text === "string") {
parts.push(item.text);
}
}
return parts.join("\n").trim();
}
type ProjectIndex = Array<{ key: string; dirPath: string }>;
async function loadProjectIndex(userId: string): Promise<ProjectIndex> {
const rows = await db
.select({ name: userProjects.name, dirPath: userProjects.dirPath })
.from(userProjects)
.where(and(eq(userProjects.userId, userId), eq(userProjects.isActive, true)));
return rows
.filter((r): r is { name: string; dirPath: string } => Boolean(r.dirPath))
.map((r) => ({ key: r.name, dirPath: r.dirPath.replace(/\/+$/, "") }))
.sort((a, b) => b.dirPath.length - a.dirPath.length);
}
function resolveProjectKey(cwd: string | undefined, index: ProjectIndex): string | null {
if (!cwd) return null;
const normalized = cwd.replace(/\/+$/, "");
for (const entry of index) {
if (normalized === entry.dirPath) return entry.key;
if (normalized.startsWith(entry.dirPath + "/")) return entry.key;
}
return null;
}
async function ingestJsonl(
path: string,
userId: string,
projectIndex: ProjectIndex,
): Promise<{ added: number; skipped: number; errored: number }> {
const text = await readFile(path, "utf8");
const lines = text.split("\n");
const batch: NewClaudeCodeHistoryRow[] = [];
let errored = 0;
for (const line of lines) {
const raw = line.trim();
if (!raw) continue;
let event: JsonlEvent;
try {
event = JSON.parse(raw);
} catch {
errored++;
continue;
}
if (event.type !== "user" && event.type !== "assistant") continue;
if (!event.uuid || !event.sessionId || !event.timestamp) continue;
const occurredAt = new Date(event.timestamp);
if (Number.isNaN(occurredAt.getTime())) continue;
const promptText = extractText(event.message?.content);
if (!promptText) continue;
const projectKey = resolveProjectKey(event.cwd, projectIndex);
batch.push({
userId,
projectKey,
projectPath: event.cwd ?? "",
gitBranch: event.gitBranch ?? null,
sessionId: event.sessionId,
eventUuid: event.uuid,
promptType: event.type,
promptText,
occurredAt,
});
}
if (batch.length === 0) return { added: 0, skipped: 0, errored };
// Chunk inserts so a single huge JSONL doesn't blow past postgres's parameter
// limit. ~600 rows × ~10 cols ≈ 6000 params, comfortably under 65535.
let added = 0;
const CHUNK = 500;
for (let i = 0; i < batch.length; i += CHUNK) {
const slice = batch.slice(i, i + CHUNK);
const result = await db
.insert(claudeCodeHistory)
.values(slice)
.onConflictDoNothing({ target: [claudeCodeHistory.sessionId, claudeCodeHistory.eventUuid] })
.returning({ id: claudeCodeHistory.id });
added += result.length;
}
return { added, skipped: batch.length - added, errored };
}
async function listJsonlFiles(root: string, sinceMs: number | null): Promise<string[]> {
let dirs: string[];
try {
dirs = await readdir(root, { withFileTypes: true })
.then((entries) => entries.filter((e) => e.isDirectory()).map((e) => join(root, e.name)));
} catch {
return [];
}
const out: string[] = [];
for (const dir of dirs) {
const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
for (const entry of entries) {
if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
const full = join(dir, entry.name);
if (sinceMs !== null) {
const s = await stat(full).catch(() => null);
if (!s || s.mtimeMs < sinceMs) continue;
}
out.push(full);
}
}
return out;
}
function parseArgs(argv: string[]): { dir: string; sinceMs: number | null } {
let dir = CLAUDE_PROJECTS_DIR;
let sinceMs: number | null = null;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--dir" && argv[i + 1]) {
dir = argv[i + 1];
i++;
} else if (arg === "--since" && argv[i + 1]) {
const t = Date.parse(argv[i + 1]);
if (!Number.isNaN(t)) sinceMs = t;
i++;
}
}
return { dir, sinceMs };
}
async function main() {
const { dir, sinceMs } = parseArgs(process.argv.slice(2));
const user = await getDefaultUser();
if (!user) {
console.error("ingest-history: no default user in DB. Onboard a user first.");
process.exit(1);
}
const projectIndex = await loadProjectIndex(user.id);
console.log(`ingest-history: scanning ${dir} (${projectIndex.length} projects indexed)`);
if (sinceMs !== null) console.log(`ingest-history: filtering files modified since ${new Date(sinceMs).toISOString()}`);
const files = await listJsonlFiles(dir, sinceMs);
console.log(`ingest-history: ${files.length} JSONL file(s) to process`);
let totalAdded = 0, totalSkipped = 0, totalErrored = 0;
for (const file of files) {
try {
const r = await ingestJsonl(file, user.id, projectIndex);
totalAdded += r.added;
totalSkipped += r.skipped;
totalErrored += r.errored;
if (r.added > 0 || r.errored > 0) {
console.log(` ${file}: +${r.added} added, ${r.skipped} skipped, ${r.errored} errored`);
}
} catch (err) {
console.error(` ${file}: failed —`, (err as Error).message);
}
}
console.log(`\nDone. ${totalAdded} new event(s), ${totalSkipped} already in DB, ${totalErrored} malformed line(s).`);
process.exit(0);
}
main().catch((err) => {
console.error("ingest-history: fatal —", err);
process.exit(1);
});
+62 -6
View File
@@ -1,6 +1,6 @@
import { and, desc, eq, gte, sql } from "drizzle-orm";
import { db } from "@/db";
import { promptHistory, orchestrationRuns, userProjects } from "@/db/schema";
import { promptHistory, orchestrationRuns, userProjects, claudeCodeHistory } from "@/db/schema";
import { splitSessionItems } from "@/lib/session-content";
import { getAdapterLabel, getIntentLabel } from "@/config/control-intents";
import {
@@ -23,7 +23,8 @@ export type { EventStatus } from "@/lib/activity-status";
const MAX_RAW_ROWS_PER_QUERY = 200;
const MAX_PROMPT_SAMPLES_FOR_TIMELINE = 60;
const MAX_RUN_SAMPLES_FOR_TIMELINE = 60;
const MAX_TIMELINE_ITEMS = 80;
const MAX_LOCAL_CHAT_SAMPLES_FOR_TIMELINE = 60;
const MAX_TIMELINE_ITEMS = 120;
const COMPACT_LIMITS = {
completed: 10,
next: 8,
@@ -85,7 +86,7 @@ export type DigestTimelineItem = {
title: string;
body: string;
status: EventStatus;
kind: "prompt" | "run";
kind: "prompt" | "run" | "local_chat";
};
export type ProjectStatus = {
@@ -162,9 +163,16 @@ async function fetchActivityRows(userId: string, since: Date, projectKey: string
];
if (projectKey) runConditions.push(eq(orchestrationRuns.projectKey, projectKey));
const localChatConditions = [
eq(claudeCodeHistory.userId, userId),
gte(claudeCodeHistory.occurredAt, since),
eq(claudeCodeHistory.promptType, "user"),
];
if (projectKey) localChatConditions.push(eq(claudeCodeHistory.projectKey, projectKey));
// Activity counts per project run unfiltered so the chip wall can rank
// projects by hotness even when one is currently selected.
const [projectRows, promptCounts, runCounts, prompts, runs] = await Promise.all([
const [projectRows, promptCounts, runCounts, localChatCounts, prompts, runs, localChats] = await Promise.all([
db
.select({ key: userProjects.name })
.from(userProjects)
@@ -186,6 +194,18 @@ async function fetchActivityRows(userId: string, since: Date, projectKey: string
.from(orchestrationRuns)
.where(and(eq(orchestrationRuns.userId, userId), gte(orchestrationRuns.startedAt, since)))
.groupBy(orchestrationRuns.projectKey),
db
.select({
projectKey: claudeCodeHistory.projectKey,
n: sql<number>`count(*)::int`,
})
.from(claudeCodeHistory)
.where(and(
eq(claudeCodeHistory.userId, userId),
gte(claudeCodeHistory.occurredAt, since),
eq(claudeCodeHistory.promptType, "user"),
))
.groupBy(claudeCodeHistory.projectKey),
db
.select({
id: promptHistory.id,
@@ -217,14 +237,29 @@ async function fetchActivityRows(userId: string, since: Date, projectKey: string
.where(and(...runConditions))
.orderBy(desc(orchestrationRuns.startedAt))
.limit(MAX_RAW_ROWS_PER_QUERY),
db
.select({
id: claudeCodeHistory.id,
projectKey: claudeCodeHistory.projectKey,
projectPath: claudeCodeHistory.projectPath,
gitBranch: claudeCodeHistory.gitBranch,
sessionId: claudeCodeHistory.sessionId,
promptText: claudeCodeHistory.promptText,
occurredAt: claudeCodeHistory.occurredAt,
})
.from(claudeCodeHistory)
.where(and(...localChatConditions))
.orderBy(desc(claudeCodeHistory.occurredAt))
.limit(MAX_RAW_ROWS_PER_QUERY),
]);
return { projectRows, promptCounts, runCounts, prompts, runs };
return { projectRows, promptCounts, runCounts, localChatCounts, prompts, runs, localChats };
}
type ActivityRows = Awaited<ReturnType<typeof fetchActivityRows>>;
type PromptRow = ActivityRows["prompts"][number];
type RunRow = ActivityRows["runs"][number];
type LocalChatRow = ActivityRows["localChats"][number];
// ─── Builders — each one does one thing ─────────────────────────────────────
@@ -232,10 +267,15 @@ function buildProjectsList(
projectRows: ActivityRows["projectRows"],
promptCounts: ActivityRows["promptCounts"],
runCounts: ActivityRows["runCounts"],
localChatCounts: ActivityRows["localChatCounts"],
): DigestProjectOption[] {
const activityByProject = new Map<string, number>();
for (const row of promptCounts) activityByProject.set(row.projectKey, (activityByProject.get(row.projectKey) ?? 0) + row.n);
for (const row of runCounts) activityByProject.set(row.projectKey, (activityByProject.get(row.projectKey) ?? 0) + row.n);
for (const row of localChatCounts) {
if (!row.projectKey) continue;
activityByProject.set(row.projectKey, (activityByProject.get(row.projectKey) ?? 0) + row.n);
}
return projectRows
.map((row) => ({ key: row.key, label: row.key, activity: activityByProject.get(row.key) ?? 0 }))
@@ -265,6 +305,21 @@ function buildPromptTimeline(prompts: PromptRow[]): DigestTimelineItem[] {
}));
}
function buildLocalChatTimeline(rows: LocalChatRow[]): DigestTimelineItem[] {
return rows.slice(0, MAX_LOCAL_CHAT_SAMPLES_FOR_TIMELINE).map((row) => {
const branch = row.gitBranch ? ` · ${row.gitBranch}` : "";
return {
id: `local_chat:${row.id}`,
occurredAt: row.occurredAt.toISOString(),
projectKey: row.projectKey ?? "(unscoped)",
title: `Claude Code · local chat${branch}`,
body: row.promptText,
status: "neutral" as const,
kind: "local_chat" as const,
};
});
}
function buildRunTimeline(runs: RunRow[]): DigestTimelineItem[] {
return runs.slice(0, MAX_RUN_SAMPLES_FOR_TIMELINE).map((run) => ({
id: `run:${run.id}`,
@@ -336,7 +391,7 @@ export async function getProjectDigest(
const rows = await fetchActivityRows(userId, since, projectKey);
const projects = buildProjectsList(rows.projectRows, rows.promptCounts, rows.runCounts);
const projects = buildProjectsList(rows.projectRows, rows.promptCounts, rows.runCounts, rows.localChatCounts);
const projectStatuses = buildProjectStatuses(rows.runs, projects);
const stats = buildStats(rows.prompts, rows.runs);
const compacted = buildCompacted(rows.prompts, rows.runs);
@@ -344,6 +399,7 @@ export async function getProjectDigest(
const timeline = [
...buildPromptTimeline(rows.prompts),
...buildRunTimeline(rows.runs),
...buildLocalChatTimeline(rows.localChats),
]
.sort((a, b) => b.occurredAt.localeCompare(a.occurredAt))
.slice(0, MAX_TIMELINE_ITEMS);
+36
View File
@@ -0,0 +1,36 @@
import { pgTable, uuid, text, timestamp, uniqueIndex, index } from "drizzle-orm/pg-core";
import { users } from "./users";
import { entities } from "./entities";
// Per-event mirror of local Claude Code conversations. The CLI writes a JSONL
// transcript per session at ~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl;
// scripts/ingest-claude-code-history.ts tails those files and lands user +
// assistant turns here so /activity unifies "what was dispatched from /control"
// with "what the founder typed locally to an agent."
//
// (sessionId, eventUuid) is unique → re-ingesting the same JSONL is idempotent
// and incremental ingest just needs to skip files where the newest event_uuid
// is already present.
export const claudeCodeHistory = pgTable("claude_code_history", {
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id").notNull().references(() => users.id),
// Optional FK to user_projects-equivalent entity. NULL when the JSONL's cwd
// doesn't match any registered project (e.g. ad-hoc dirs).
projectId: uuid("project_id").references(() => entities.id, { onDelete: "set null" }),
projectKey: text("project_key"),
projectPath: text("project_path").notNull(),
gitBranch: text("git_branch"),
sessionId: text("session_id").notNull(),
eventUuid: text("event_uuid").notNull(),
promptType: text("prompt_type").$type<"user" | "assistant">().notNull(),
promptText: text("prompt_text").notNull(),
occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
ingestedAt: timestamp("ingested_at", { withTimezone: true }).defaultNow().notNull(),
}, (t) => [
uniqueIndex("idx_cc_history_session_event").on(t.sessionId, t.eventUuid),
index("idx_cc_history_user_occurred").on(t.userId, t.occurredAt),
index("idx_cc_history_project_key").on(t.projectKey),
]);
export type ClaudeCodeHistoryRow = typeof claudeCodeHistory.$inferSelect;
export type NewClaudeCodeHistoryRow = typeof claudeCodeHistory.$inferInsert;
+1
View File
@@ -16,6 +16,7 @@ export * from "./habits";
export * from "./orchestration-events";
export * from "./orchestration-runs";
export * from "./prompt-history";
export * from "./claude-code-history";
export * from "./auth";
export * from "./user-projects";
export * from "./project-states";