endSession

tcmts.cli.mcp.endSession · #jouagmh3 · term · runs on the server

uses node:fs

When the server of a session on a branch made for it stops: the branch goes, with its directory, if everything on it is on the codebase's own branch already (nothing was changed, or it landed), no scratch file holds unsaved work, and no running server works on it (but the one stopping, stopping: its process). Otherwise it stays, for the user to look at and land (tcm merge), or for the agent to go on with (a server started again from the same directory does: startSession; or tcm mcp --branch <it>). Decided in a write transaction, as servers claim their branches. Whether it went.

import { sessionDirFor, unsavedIn } from "#codebase/tcmts/cli/codebase";
import { liveMcpServers, withCodebase } from "#codebase/tcmts/cli/mcp";
import { hasWork } from "#codebase/tcmts/cli/merge";
import fs from "node:fs";

export function endSession(root: string, branch: string, stopping?: number): boolean {
  const dir = sessionDirFor(root, branch);
  const gone = withCodebase(root, (cb) =>
    cb.store.transaction(() => {
      const own = cb.store.branch().name;
      if (
        own === branch ||
        !cb.store.hasBranch(branch) ||
        unsavedIn(dir).length ||
        liveMcpServers(root).some((s) => s.branch === branch && s.pid !== stopping) ||
        hasWork(cb, branch, own)
      )
        return false;
      cb.store.deleteBranch(branch);
      fs.rmSync(dir, { recursive: true, force: true });
      return true;
    }),
  );
  return gone;
}

uses

used by