Files
hyperframes/packages/cli/src/utils/appHistory.ts
T
WaterrrForever 6fe3c2ce94 feat(cli): catch up on what the desktop app did since a project was handed over (#5114)
* feat(cli): catch up on what the desktop app did since a project was handed over

The desktop app records each chat turn in .hyperframes/app-history.jsonl.
`hyperframes catch-up [dir]` prints the turns since the hand-off or the last
catch-up (what the person asked, what Framey did, which files changed) plus
the project files changed since, by the app or by hand, then marks them seen.

`hyperframes open` and Studio's Edit with Framey mark the hand-off moment.
Any command run on a project with unseen turns ends with a line naming
catch-up, so an agent back in the terminal hears about it even when it
forgets. /hyperframes and /hyperframes-cli tell the agent to catch up as
soon as the person writes again.

* feat(cli): hand a Grok terminal session over to the desktop app

Grok gives every tool command its session as GROK_SESSION_ID (grok 1.0.4),
so `hyperframes open` and Edit with Framey now name a Grok session in
.hyperframes/agent-handoff.json, after Claude Code and Codex. The desktop
app reads its turns from Grok's own session files.

* feat(cli): tell a new project's agent to catch up after the desktop app

Scaffolded projects' CLAUDE.md and AGENTS.md now say to run
`npx hyperframes catch-up` before the next change once the project was
opened in the desktop app. Claude Code, Codex and Grok read these files on
their own, so a resumed session catches up even when it never loaded a
HyperFrames skill: a resumed Claude Code session that had not, asked to
change the title, ran catch-up first.

catch-up also prints each reply on one line.

* fix(cli): read and write .hyperframes records without following links, mark seen after showing

Review (Jerrai, Rames):
- One helper (projectRecords.ts) now reads and writes every record in
  .hyperframes/. A linked folder is refused. A read opens once with
  O_NOFOLLOW and checks the open file is a plain file, which clears the
  CodeQL race. A write goes to a temp file renamed over the record, so a
  link is replaced, never written through. agent-handoff.json, the seen
  record and the history all go through it.
- catch-up marks a turn seen only after showing it, and only up to the
  newest turn shown, so a turn written just after the read shows next
  time. Changed files have their own "checked" time.
- Turns show only once the project was handed over from this machine, so
  a history file shipped in a cloned repo is never shown as the person's
  words. The end-of-command check skips reading when the history is
  older than the seen record.
- The skills mention catch-up only when the CLI printed a line naming it,
  so an older CLI never meets an unknown command.
- The notice test uses basename, which fixes Windows.

* feat(cli): add the catch-up line to an older project's instructions on hand-off

A project scaffolded before catch-up existed has no line telling its agent
to catch up, and a resumed session that never loaded a HyperFrames skill
then edits without knowing what happened in the app. When `hyperframes open`
or Edit with Framey hands such a project over, its scaffolded CLAUDE.md and
AGENTS.md (they start "# HyperFrames Composition Project") gain the
template's line, in the template's place. A file of the person's own, a
link, a missing file, or one that has the line is left alone. The file is
rewritten through a temp file with its mode kept. A test keeps the line the
same as the template's.

* fix(cli): keep catch-up's cursor in the person's home, never reset it, read without links on Windows

Review (Rames, Jerrai):
- The seen record moved from the project to ~/.hyperframes/catch-up/,
  keyed by the project's real path. A seen file a cloned repo commits
  can no longer make its history read as the person's words.
- A second hand-off (`open` again, or another Edit with Framey click)
  keeps the cursor, so turns the app recorded meanwhile still show.
- Reads lstat the path, open it once, and refuse a file whose dev/ino
  differs from what lstat saw. That holds where O_NOFOLLOW doesn't
  exist, fixing the Windows test. The note writer reads the same way,
  which clears the new CodeQL alert.
- Writes use core's replaceFileAtomically, which retries a rename that
  Windows briefly refuses.
- catch-up names every changed file, and the cursor is the newest `at`
  shown, not the last line's.
- `open --json` carries `catchUp` after a hand-off.
- The bin scripts are back to mode 644.

* fix(cli): open before checking for CodeQL, never show a turn dated ahead

Review (Rames, Jerrai):
- readPlainFile opens the file first, then requires lstat to find the same
  plain file (dev/ino) at the path, and reads only through the fd. That is
  just as safe, and it clears CodeQL's check-then-use alert.
- catch-up skips turns dated after the moment it reads. So a cloned history
  can't show a far-future turn as the person's words or park the cursor
  past real ones.
- The seen key uses core's realpath (realpathSync.native), so letter case
  can't split a project in two. ~/.hyperframes/catch-up is made 0700, and
  a hand-off that can't note itself says so.
- Tests stub HOME with vi.stubEnv and restore it.
2026-10-06 13:20:27 +00:00

174 lines
6.6 KiB
TypeScript

import { createHash } from "node:crypto";
import { lstatSync, mkdirSync, readdirSync } from "node:fs";
import { realpath } from "@hyperframes/core/safe-path";
import { homedir } from "node:os";
import { dirname, join, relative, resolve, sep } from "node:path";
import { readPlainFile, readRecord, recordChangedAt, replaceFile } from "./projectRecords.js";
// The desktop app records each chat turn in .hyperframes/ (hyperframes-internal appHistory.mjs), one JSON object
// a line. The seen record holds the newest turn shown here and when files were last checked. It starts at a
// hand-off and lives in this person's ~/.hyperframes, keyed by the project's real path, so a file a cloned repo
// ships can never claim one.
export const APP_HISTORY = "app-history.jsonl";
const MAX_READ_BYTES = 1024 * 1024;
const MAX_FIELD_CHARS = 2000;
const MAX_WALKED_FILES = 5000;
const SKIPPED_DIRS = new Set(["node_modules", "renders", "snapshots"]);
export interface AppTurn {
at: string;
engine: string;
asked: string;
did: string;
files: string[];
}
const text = (value: unknown): string =>
typeof value === "string" ? value.slice(0, MAX_FIELD_CHARS) : "";
function toTurn(line: string): AppTurn | null {
let raw: Record<string, unknown>;
try {
raw = Object(JSON.parse(line));
} catch {
return null;
}
const at = text(raw.at);
if (Number.isNaN(Date.parse(at))) return null;
const files = Array.isArray(raw.files) ? raw.files.map(text).filter(Boolean) : [];
return { at, engine: text(raw.engine), asked: text(raw.asked), did: text(raw.did), files };
}
export function readAppTurns(dir: string): AppTurn[] {
return readRecord(dir, APP_HISTORY, MAX_READ_BYTES)
.split("\n")
.flatMap((line) => toTurn(line) ?? []);
}
export interface Seen {
/** The newest turn already shown; 0 when the project was never handed over from here. */
at: number;
/** When the project's files were last checked for changes. */
checked: number;
}
const stamp = (value: unknown): number => (typeof value === "string" ? Date.parse(value) || 0 : 0);
function seenPath(dir: string): string {
let real: string;
try {
real = realpath(dir);
} catch {
real = resolve(dir);
}
const key = createHash("sha256").update(real).digest("hex").slice(0, 32);
return join(homedir(), ".hyperframes", "catch-up", `${key}.json`);
}
export function readSeen(dir: string): Seen {
try {
const seen: Record<string, unknown> = Object(JSON.parse(readPlainFile(seenPath(dir), 4096)));
const at = stamp(seen.at);
return { at, checked: stamp(seen.checked) || at };
} catch {
return { at: 0, checked: 0 };
}
}
/** False when it could not be written; the same turns then show again, never fewer. */
export function markSeen(dir: string, seen: Seen): boolean {
const path = seenPath(dir);
const at = (time: number) => new Date(time).toISOString();
try {
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
} catch {
return false;
}
return replaceFile(path, JSON.stringify({ at: at(seen.at), checked: at(seen.checked) }), 0o600);
}
/** Turns after `since` and not after `now`: a turn dated ahead, as a cloned history could carry, is never shown and
* never moves the cursor past real ones. */
export function unseenTurns(dir: string, since: number, now = Date.now()): AppTurn[] {
if (!since) return [];
return readAppTurns(dir).filter(
(turn) => Date.parse(turn.at) > since && Date.parse(turn.at) <= now,
);
}
/** Project files changed after `since`, by the app or by hand; hidden folders and outputs are not the video. */
export function filesChangedSince(dir: string, since: number): string[] {
const changed: string[] = [];
let walked = 0;
const walk = (folder: string): void => {
let entries;
try {
entries = readdirSync(folder, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (walked++ > MAX_WALKED_FILES) return;
if (entry.name.startsWith(".") || SKIPPED_DIRS.has(entry.name)) continue;
const path = join(folder, entry.name);
if (entry.isDirectory()) walk(path);
else if (entry.isFile() && lstatSync(path).mtimeMs > since)
changed.push(relative(dir, path).split(sep).join("/"));
}
};
walk(dir);
return changed.sort();
}
/** The project a command ran on: its folder or a file in it, as given on the command line or the working folder. */
function projectsNamed(cwd: string, args: string[]): string[] {
const candidates = [cwd, ...args.filter((arg) => !arg.startsWith("-"))].flatMap((arg) => {
const path = resolve(cwd, arg);
return [path, dirname(path)];
});
return [...new Set(candidates)];
}
/** One line for the end of any command run on a project the app has chatted about since it was last looked at. */
export function appHistoryNotice(cwd: string, args: string[]): string | null {
for (const dir of projectsNamed(cwd, args)) {
const { at } = readSeen(dir);
if (!at || recordChangedAt(dir, APP_HISTORY) <= at) continue;
const count = unseenTurns(dir, at).length;
if (count === 0) continue;
const where = relative(cwd, dir);
const turns = count === 1 ? "1 chat turn" : `${count} chat turns`;
return (
`The HyperFrames desktop app has ${turns} on this project you haven't seen. ` +
`Run \`npx hyperframes catch-up${where ? ` ${where}` : ""}\` before changing it.`
);
}
return null;
}
// The line scaffolded CLAUDE.md and AGENTS.md carry (templates/_shared); a test keeps the two the same.
export const CATCH_UP_NOTE =
"> **Back from the desktop app.** Once this project was opened in the HyperFrames desktop app, run " +
"`npx hyperframes catch-up` before your next change here: it lists what the person asked Framey in the app " +
"and which files changed since.";
const SCAFFOLD_TITLE = "# HyperFrames Composition Project";
const AFTER = "> alive through review, and stop it explicitly with `preview --stop` afterward.\n";
/** On a hand-off, a project scaffolded before catch-up existed gains its line, so an agent that reads the
* project's instructions catches up. Any other file, a link, or one that has the line stays as it is. */
export function addCatchUpNote(dir: string): void {
for (const name of ["CLAUDE.md", "AGENTS.md"]) {
const path = join(dir, name);
try {
const text = readPlainFile(path, MAX_READ_BYTES);
if (!text.startsWith(SCAFFOLD_TITLE) || text.includes("hyperframes catch-up")) continue;
const next = text.includes(AFTER)
? text.replace(AFTER, `${AFTER}\n${CATCH_UP_NOTE}\n`)
: `${text.trimEnd()}\n\n${CATCH_UP_NOTE}\n`;
replaceFile(path, next, lstatSync(path).mode & 0o777);
} catch {
// No such file: nothing to add to.
}
}
}