Cotton code
419 lines · 19.4 KB · TypeScriptRaw
/** * `log_session` — crates/cotton-tools/src/mcp/handlers/records_2/sessions.rs. * * A SESSION LOG MUST NEVER FAIL. The Stop hook advances its cursor only on * success, so a call that refuses is resent every turn and fails every turn. * Every cap TRUNCATES rather than refusing, a blank turn is skipped, and a * `seq` the session already holds is a no-op. Text is redacted, THEN clipped. * * The row is upserted by `(tool, externalId)`, its id DERIVED from that pair; * a `sessionId` names the row a session Cotton started IS, and folds an * adopted twin back into it. Turns and tasks have ids derived from * `(session, seq)`, so a resend is the same row. Everything lands in one write. * * `adoptable_here` (the device-key fallback) never fires here: an MCP caller * authenticates a token and proves no device, exactly as in Rust. */import { derivedId, fail, isoTimestamp, optionalString, type Data, type ToolContext } from "../../context.ts";import type { StoredRow } from "../../../store.ts";import { clipped, flag, int, intOrNull, normalizeRepoUrl, parseMs, projectsForRepo, projectsOf, redactedToFit, resolveProject, SESSION_TITLE_MAX, SESSION_TOOLS, text, utf16Clip, type ProjectRef } from "./common.ts";import { absorbing, TYPED_KINDS, type DeliveredMessage } from "./echo.ts";import { SealedRows } from "../sealed_rows.ts";const TASK_STATES = ["open", "active", "done"];const TURN_ROLES = ["user", "assistant"];const TASK_TEXT_MAX = 500;const SESSION_SUMMARY_MAX = 2000;const PROMPT_TEXT_MAX = 8000;const SESSION_MODEL_MAX = 80;interface Turn {  seq: number;  ts: string;  role: string;  text: string;}interface Task {  seq: number;  text: string;  state: string;}interface LogArgs {  tool: string;  externalId: string;  sessionRowId: string | null;  machine: string;  lastActiveAt: string;  prompts: Turn[];  repoUrl: string | null;  branch: string | null;  cwd: string | null;  project: string | null;  startedAt: string | null;  endedAt: string | null;  title: string | null;  titleIfEmpty: string | null;  summary: string | null;  model: string | null;  turnCount: number | null;  transcriptRef: string | null;  /** null says nothing about tasks; a list REPLACES the row's list. */  tasks: Task[] | null;}const isCount = (v: unknown): v is number => typeof v === "number" && Number.isInteger(v) && v >= 0;function validate(args: Data): LogArgs {  const tool = optionalString(args, "tool");  if (!tool || !SESSION_TOOLS.includes(tool)) fail(`tool must be one of ${SESSION_TOOLS.join(", ")}`);  const externalId = optionalString(args, "externalId") ?? fail("externalId is required — the tool's own session id");  const machine = optionalString(args, "machine") ?? fail("machine is required — this machine's hostname");  const lastActiveAt = isoTimestamp(optionalString(args, "lastActiveAt")) ?? fail("lastActiveAt must be an ISO-8601 timestamp");  const stamp = (key: string): string | null => {    const raw = optionalString(args, key);    if (raw === null) return null;    return isoTimestamp(raw) ?? fail(`${key} must be an ISO-8601 timestamp`);  };  const startedAt = stamp("startedAt");  const endedAt = stamp("endedAt");  let turnCount: number | null = null;  if (args.turnCount !== undefined) {    if (!isCount(args.turnCount)) fail("turnCount must be a non-negative integer");    turnCount = args.turnCount;  }  const prompts: Turn[] = [];  const rawPrompts = args.prompts;  if (rawPrompts !== undefined && rawPrompts !== null) {    if (!Array.isArray(rawPrompts)) fail("prompts must be an array");    for (const entry of rawPrompts as unknown[]) {      if (!entry || typeof entry !== "object" || Array.isArray(entry)) fail("each prompt must be { seq, ts, text }");      const p = entry as Data;      if (!isCount(p.seq)) fail("prompt.seq must be a non-negative integer");      const ts = typeof p.ts === "string" ? isoTimestamp(p.ts) : null;      if (ts === null) fail("prompt.ts must be an ISO-8601 timestamp");      if (typeof p.text !== "string") fail("prompt.text must be a string");      let role = "user";      if (p.role !== undefined) {        if (typeof p.role !== "string" || !TURN_ROLES.includes(p.role)) fail(`prompt.role must be one of ${TURN_ROLES.join(", ")}`);        role = p.role;      }      const said = redactedToFit(p.text, PROMPT_TEXT_MAX);      if (!said.trim()) continue;      prompts.push({ seq: p.seq, ts, role, text: said });    }  }  let tasks: Task[] | null = null;  if (Array.isArray(args.tasks)) {    const seen = new Map<number, Task>();    for (const entry of args.tasks as unknown[]) {      if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;      const t = entry as Data;      if (!isCount(t.seq) || typeof t.text !== "string") continue;      const said = redactedToFit(t.text, TASK_TEXT_MAX);      if (!said.trim()) continue;      const state = typeof t.state === "string" && TASK_STATES.includes(t.state) ? t.state : "open";      if (!seen.has(t.seq)) seen.set(t.seq, { seq: t.seq, text: said, state });    }    tasks = [...seen.values()].sort((a, b) => a.seq - b.seq);  }  return {    tool,    externalId,    sessionRowId: optionalString(args, "sessionId"),    machine,    lastActiveAt,    prompts,    repoUrl: optionalString(args, "repoUrl"),    branch: optionalString(args, "branch"),    cwd: optionalString(args, "cwd"),    project: optionalString(args, "project"),    startedAt,    endedAt,    title: clipped(optionalString(args, "title"), SESSION_TITLE_MAX),    titleIfEmpty: clipped(optionalString(args, "titleIfEmpty"), SESSION_TITLE_MAX),    summary: clipped(optionalString(args, "summary"), SESSION_SUMMARY_MAX),    model: clipped(optionalString(args, "model"), SESSION_MODEL_MAX),    turnCount,    transcriptRef: optionalString(args, "transcriptRef"),    tasks,  };}/** PR and commit links a recap says it shipped, each once, in order. The lazy `+?` is load-bearing. */export function shippedIn(summary: string | null): string[] {  if (summary === null) return [];  const seen: string[] = [];  for (const m of summary.matchAll(/https?:\/\/github\.com\/[^\s()<>[\]"']+?\/(?:pull|commit)\/[^\s()<>[\]"'.,;]+/g)) if (!seen.includes(m[0])) seen.push(m[0]);  return seen;}/** An explicit slug wins; otherwise the ONE active project listing the repo, or none. */function sessionProject(projects: ProjectRef[], project: string | null, repoUrl: string | null): string | null {  if (project !== null) return resolveProject(projects, project);  if (repoUrl === null) return null;  const matched = projectsForRepo(projects.filter((p) => p.status === "active"), repoUrl);  return matched.length === 1 ? matched[0]!.id : null;}/** A session coming BACK: an adopted row with an end, and activity strictly after it. */function reopens(row: StoredRow, lastActiveAt: string): boolean {  if (flag(row.data, "host_owned")) return false;  const ended = parseMs(text(row.data, "ended_at"));  const active = parseMs(lastActiveAt);  return ended !== null && active !== null && active > ended;}/** The row the caller NAMED; a name matching nothing is the one refusal this tool allows. */function namedRow(ctx: ToolContext, args: LogArgs): StoredRow | null {  if (args.sessionRowId === null) return null;  const row = ctx.get("session", args.sessionRowId);  if (!row) fail(`no such session: ${args.sessionRowId} — sessionId is a session's full row id, never a prefix`);  if (text(row.data, "tool") !== args.tool) return null;  const held = text(row.data, "external_id");  return held === null || held === args.externalId ? row : null;}/** The named row a twin folds into: the twin adopted, the named row a different, hosted row with its id free. */function foldableNamed(twin: StoredRow, named: StoredRow | null): StoredRow | null {  if (flag(twin.data, "host_owned") || !named || named.id === twin.id) return null;  if (!flag(named.data, "host_owned") || text(named.data, "external_id") !== null) return null;  return named;}function liveProject(ctx: ToolContext, id: string | null): string | null {  return id !== null && ctx.get("project", id) ? id : null;}function promptsOf(ctx: ToolContext, sessionId: string): StoredRow[] {  return ctx.where("prompt", "session", sessionId);}/** A derived id the synchronous pass needs: answered from the cache, or noted as missing and answered "". */type Ids = (table: string, parts: string[]) => string;/** * Derived ids are hashed asynchronously, and an await lets another call onto * the object's thread. So the reads, the decisions and the write run in one * SYNCHRONOUS pass over ids hashed beforehand; a pass that finds an id it * lacks writes nothing, the ids are hashed, and the pass runs again — the * pass that writes saw the rows it writes over, with nothing in between. */export async function logSession(ctx: ToolContext, raw: Data): Promise<Data> {  const args = validate(raw);  const cache = new Map<string, string>();  // OPEN TABLES (24 Nov 2026): the session tables may be sealed; writes are sealed with the window's key or on arrival.  const rows = await SealedRows.of(ctx, ["session", "prompt", "session_task", "session_message"]);  for (;;) {    const missing = new Map<string, [string, string[]]>();    const ids: Ids = (table, parts) => {      const key = JSON.stringify([table, ...parts]);      const held = cache.get(key);      if (held !== undefined) return held;      missing.set(key, [table, parts]);      return "";    };    const answered = pass(ctx, args, ids, () => missing.size > 0 || rows.lacking(), rows);    if (answered) return answered;    for (const [key, [table, parts]] of missing) cache.set(key, derivedId(table, parts));    // What the pass lacked of sealed rows: opened and sealed here, between passes (src/mcp/tools/sealed_rows.ts).    await rows.fill();  }}/** One synchronous pass: null when it needed an id it did not have, and then it wrote nothing. */function pass(ctx: ToolContext, args: LogArgs, ids: Ids, lacking: () => boolean, rows: SealedRows): Data | null {  /** A row as this pass reads it (opened when sealed); undefined while it waits to be opened. */  const open = (table: string, row: StoredRow): StoredRow | undefined => rows.read(table, [row])[0];  const projects = projectsOf(ctx);  const resolvedProject = sessionProject(projects, args.project, args.repoUrl);  const summary = args.summary === null ? null : redactedToFit(args.summary, SESSION_SUMMARY_MAX);  const repoUrl = args.repoUrl === null ? null : normalizeRepoUrl(args.repoUrl);  // The name is resolved FIRST: an id naming no row is refused before the pair is even asked.  const named = namedRow(ctx, args);  const twinOrRow = ctx.where("session", "external_id", args.externalId).find((r) => text(r.data, "tool") === args.tool) ?? null;  let twin: StoredRow | null = null;  let existing: StoredRow | null;  if (twinOrRow) {    const into = foldableNamed(twinOrRow, named);    if (into) twin = twinOrRow;    existing = into ?? twinOrRow;  } else {    existing = named;  }  const sessionId = existing ? existing.id : ids("cotton_sessions", [args.tool, args.externalId]);  if (lacking()) return null;  // THE FOLD: the twin's turns re-sequenced after whatever the named row has.  const moved: { id: string; data: Data; from: StoredRow }[] = [];  let foldedTitle: string | null = null;  if (twin && existing) {    let seq = promptsOf(ctx, existing.id).reduce((max, p) => Math.max(max, intOrNull(p.data, "seq") ?? -1), -1);    const moving = rows.read("prompt", promptsOf(ctx, twin.id)).sort((a, b) => int(a.data, "seq") - int(b.data, "seq"));    for (const p of moving) {      seq += 1;      moved.push({        id: ids("cotton_prompts", [existing.id, String(seq)]),        data: { session: existing.id, project: liveProject(ctx, text(p.data, "project")), seq, ts: text(p.data, "ts") ?? "", role: text(p.data, "role") ?? "user", text: text(p.data, "text") ?? "" },        from: p,      });    }    const mine = open("session", existing);    const theirs = open("session", twin);    foldedTitle = mine && theirs && text(mine.data, "title") === null ? text(theirs.data, "title") : null;  }  // Turns: only seqs the session does not hold yet; the first telling of a seq wins.  const onDisk = existing ? promptsOf(ctx, sessionId) : [];  const have = new Set<number>(onDisk.map((p) => intOrNull(p.data, "seq")).filter((s): s is number => s !== null));  for (const m of moved) have.add(m.data.seq as number);  const unique = new Map<number, Turn>();  for (const p of args.prompts) if (!have.has(p.seq) && !unique.has(p.seq)) unique.set(p.seq, p);  const ordered = [...unique.values()].sort((a, b) => a.seq - b.seq);  // A reply the phone sent and the Mac typed comes back as the owner's turn: it is not written twice.  const echoes = new Set<number>();  if (existing && ordered.some((p) => p.role === "user")) {    const delivered: DeliveredMessage[] = rows      .read("session_message", ctx.where("session_message", "to_session", sessionId))      .filter((m) => text(m.data, "to_kind") === "session" && TYPED_KINDS.includes(text(m.data, "kind") ?? "") && text(m.data, "status") !== "withdrawn")      .flatMap((m) => {        const body = text(m.data, "body");        return body === null ? [] : [{ id: m.id, body, created_at: m.created_at }];      })      .sort((a, b) => (a.created_at < b.created_at ? -1 : a.created_at > b.created_at ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0));    if (delivered.length) {      const kept = new Map<number, string>();      for (const p of onDisk) {        const seq = intOrNull(p.data, "seq");        const ts = text(p.data, "ts");        if (seq !== null && ts !== null) kept.set(seq, ts);      }      let past: { opened: number | null; message: DeliveredMessage } | null = null;      for (const p of ordered) {        let before: [number, string] | null = null;        for (const [at, ts] of kept) if (at < p.seq && (before === null || at > before[0])) before = [at, ts];        const window = before ? before[0] : null;        if (p.role === "user") {          const sameWindow = past && past.opened === window ? past.message : null;          const message = absorbing(p.text, before ? before[1] : null, sameWindow, delivered);          if (message) {            past = { opened: window, message };            echoes.add(p.seq);            continue;          }        }        kept.set(p.seq, p.ts);      }    }  }  const turns = ordered.filter((p) => !echoes.has(p.seq));  const turnIds = turns.map((p) => ids("cotton_prompts", [sessionId, String(p.seq)]));  const taskIds = args.tasks ? args.tasks.map((t) => ids("cotton_session_tasks", [sessionId, String(t.seq)])) : [];  if (lacking()) return null;  const promptCount = have.size + turns.length;  // Every write is prepared first (sealed when its table is): a pass that lacks a sealed value writes nothing.  type Op = { kind: "create"; table: string; id: string; data: Data } | { kind: "update"; table: string; row: StoredRow; data: Data } | { kind: "delete"; row: StoredRow };  const ops: Op[] = [];  let projectId: string | null;  if (twin && existing) {    // THE CLEAR FIRST: the id comes off the twin before the named row takes it.    ops.push({ kind: "update", table: "session", row: twin, data: { external_id: null, state: "withdrawn", state_at: ctx.now, ended_at: ctx.now, error: `folded into the session it was: ${existing.id}` } });    for (const m of moved) {      ops.push({ kind: "create", table: "prompt", id: m.id, data: m.data });      ops.push({ kind: "delete", row: m.from });    }  }  if (existing) {    const row = existing;    const seen = open("session", row);    // The owner's reassignment outranks the repo: only an explicit slug, or a project for a session that had none, moves it.    // A project row since deleted is no project: the engine cannot write a link to a row that is gone.    projectId = args.project !== null ? resolvedProject : (liveProject(ctx, text(row.data, "project")) ?? resolvedProject);    const patch: Data = { last_active_at: args.lastActiveAt, project: projectId, machine: args.machine };    if (text(row.data, "external_id") === null) patch.external_id = args.externalId;    patch.turn_count = args.turnCount ?? int(row.data, "turn_count") + 1;    if (args.startedAt !== null) patch.started_at = args.startedAt;    if (args.endedAt !== null) patch.ended_at = args.endedAt;    else if (reopens(row, args.lastActiveAt)) patch.ended_at = null;    if (repoUrl !== null) patch.repo_url = repoUrl;    if (args.branch !== null) patch.branch = args.branch;    if (args.cwd !== null) patch.cwd = args.cwd;    if (foldedTitle !== null) patch.title = foldedTitle;    if (args.title !== null) patch.title = args.title;    if (args.model !== null) patch.model = utf16Clip(args.model, SESSION_MODEL_MAX);    if (args.titleIfEmpty !== null && seen && text(seen.data, "title") === null && foldedTitle === null) patch.title = args.titleIfEmpty;    if (summary !== null) {      patch.summary = summary;      patch.shipped = shippedIn(summary);    }    if (args.transcriptRef !== null) patch.transcript_ref = args.transcriptRef;    if (intOrNull(row.data, "prompt_count") !== promptCount) patch.prompt_count = promptCount;    ops.push({ kind: "update", table: "session", row, data: patch });  } else {    projectId = resolvedProject;    ops.push({      kind: "create",      table: "session",      id: sessionId,      data: {        project: projectId,        tool: args.tool,        external_id: args.externalId,        machine: args.machine,        device_id: null,        repo_url: repoUrl,        branch: args.branch,        cwd: args.cwd,        started_at: args.startedAt ?? args.lastActiveAt,        last_active_at: args.lastActiveAt,        ended_at: args.endedAt,        summary,        title: args.title ?? args.titleIfEmpty,        model: args.model === null ? null : utf16Clip(args.model, SESSION_MODEL_MAX),        shipped: shippedIn(summary),        turn_count: args.turnCount ?? 1,        prompt_count: promptCount,        transcript_ref: args.transcriptRef,      },    });  }  turns.forEach((p, i) => {    ops.push({ kind: "create", table: "prompt", id: turnIds[i]!, data: { session: sessionId, project: projectId, seq: p.seq, ts: p.ts, role: p.role, text: redactedToFit(p.text, PROMPT_TEXT_MAX) } });  });  if (args.tasks) {    const held = new Map(ctx.where("session_task", "session", sessionId).map((t) => [t.id, t]));    args.tasks.forEach((t, i) => {      const id = taskIds[i]!;      const data = { session: sessionId, seq: t.seq, text: t.text, state: t.state };      const row = held.get(id);      if (row) ops.push({ kind: "update", table: "session_task", row, data });      else ops.push({ kind: "create", table: "session_task", id, data });    });    const keep = new Set(taskIds);    for (const [id, row] of held) if (!keep.has(id)) ops.push({ kind: "delete", row });  }  const ready = ops.map((op) => (op.kind === "create" ? rows.create(op.table, op.id, op.data) : op.kind === "update" ? rows.patch(op.table, op.row, op.data) : null));  if (lacking()) return null;  ctx.write((w) => {    ops.forEach((op, i) => {      if (op.kind === "delete") w.delete(ctx.store.get(op.row.table, op.row.id) ?? op.row);      else if (op.kind === "create") rows.made(w, op.table, op.id, ready[i]!);      else rows.changed(w, op.table, op.row, ready[i]!);    });  });  const out: Data = { sessionId, promptCount, inserted: turns.length };  if (args.tasks) {    out.tasksDone = args.tasks.filter((t) => t.state === "done").length;    out.tasksTotal = args.tasks.length;  }  return out;}