A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(agent): a file write is only irreversible if nobody kept the bytes
esengine1d7251594b65
diff --git a/desktop/electron/fileJournal.ts b/desktop/electron/fileJournal.tsnew file mode 100644index 000000000..ce2b09006--- /dev/null+++ b/desktop/electron/fileJournal.ts@@ -0,0 +1,330 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file fileJournal.ts+ * @brief Before-images of the project files a transaction is about to change,+ * so writing one can be taken back the way editing a scene already can.+ *+ * The editor's undo stack covers the DOCUMENT and stops at the disk, which is+ * why the tool catalog had to call every file write `irreversible` and ask the+ * user before each one. But a write is only irreversible when nobody kept the+ * bytes it overwrote. This keeps them: a transaction is opened around an agent+ * turn, every project path a write is about to touch is captured first, and one+ * revert puts the whole set back.+ *+ * Three rules make the capture trustworthy:+ *+ * - FIRST capture of a path wins. A turn that writes the same file four times+ * must revert to what was there before the first write, not the third.+ * - Order is kept and unwound LIFO, so a rename followed by a write to the new+ * name comes apart in the order that leaves each step's precondition intact.+ * - A path too big to hold is recorded as UNJOURNALED rather than skipped+ * silently. A revert that quietly leaves a 400MB import in place, while the+ * UI says the turn was taken back, is worse than one that says what it could+ * not restore.+ *+ * Copies live in the OS temp dir, next to the trash-undo holding area and for+ * the same reason: a project must not grow an undo directory, and a machine that+ * loses power owes nobody these bytes.+ */+import { mkdir, cp, rm, stat, readdir } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { randomUUID } from 'node:crypto';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { META_EXT } from './contentPolicy';+import { resolveInside } from './pathSandbox';++const HOLDING_DIR = path.join(tmpdir(), 'estella-agent-journal');++/**+ * How much of a project one transaction may hold onto.+ *+ * Sized for the thing this exists to make reversible — authoring: scripts,+ * scenes, prefabs, materials, a sprite or two. An `import_assets` that drags in+ * a video does not fit, and that is the case the partial report is for. Holding+ * gigabytes to make one import undoable would trade a rare convenience for a+ * disk nobody agreed to spend.+ */+let budgetBytes = 256 * 1024 * 1024;++/** How many finished transactions stay restorable. Older ones are dropped from+ * the disk as soon as a newer turn pushes them past this. */+const RETAINED = 8;++/** What happened to one path, in the terms the transcript reports it. */+export type ChangeKind = 'add' | 'modify' | 'remove';++/** One captured path: what it was before, and what the write did to it. */+interface Entry {+ /** Project-relative, with `/` separators — the identity the UI shows. */+ rel: string;+ kind: ChangeKind;+ /** Directory inside the transaction's holding dir, or null when the path did+ * not exist (revert deletes) or could not be held (revert cannot). */+ backup: string | null;+ /** True when the path existed but the budget refused to hold it. */+ unjournaled: boolean;+ /** Whether the captured path was a directory (revert restores it whole). */+ isDir: boolean;+}++interface Transaction {+ id: string;+ root: string;+ /** Insertion-ordered; `capture` is a no-op once a path is in here. */+ entries: Map<string, Entry>;+ bytes: number;+ open: boolean;+}++/** A transaction's changes as the editor renders them. */+export interface JournalChange {+ path: string;+ kind: ChangeKind;+ /** True when a revert cannot put this path back (see {@link BUDGET_BYTES}). */+ unjournaled: boolean;+}++/** What a revert managed. `restored` + `unjournaled` is every path it tried. */+export interface RevertResult {+ /** Project-relative paths whose prior state is back on disk. */+ restored: string[];+ /** Paths left as the transaction made them, because nothing was held. */+ unjournaled: string[];+ /** Paths whose restore threw, with the reason — a disk that filled, a file+ * the user opened in another program and locked. Never swallowed. */+ failed: Array<{ path: string; error: string }>;+}++const transactions = new Map<string, Transaction>();+/** Finished ids, oldest first — the retention ring (see {@link RETAINED}). */+const finished: string[] = [];+let active: Transaction | null = null;++/**+ * Open a transaction and make it the one every write door captures into.+ *+ * One at a time by design: the doors capture AMBIENTLY rather than being handed+ * a transaction id, which is what lets a write the agent caused indirectly — a+ * document the editor saved because a tool asked it to — land in the same+ * transaction as the tool call. Nested or concurrent transactions would make+ * "which one owns this write" unanswerable at the door.+ */+export function beginTransaction(root: string): string {+ if (active) endTransaction();+ const id = randomUUID();+ active = { id, root, entries: new Map(), bytes: 0, open: true };+ transactions.set(id, active);+ return id;+}++/** Close the open transaction; its captures stay restorable until retention+ * drops them. Returns its id, or null when none was open. */+export function endTransaction(): string | null {+ if (!active) return null;+ const id = active.id;+ active.open = false;+ active = null;+ finished.push(id);+ while (finished.length > RETAINED) {+ const old = finished.shift()!;+ void discard(old);+ }+ return id;+}++/** The open transaction's id, or null. Doors use it only to decide whether to+ * capture; the id itself belongs to whoever opened it. */+export function activeTransaction(): string | null {+ return active?.id ?? null;+}++/** What a door is about to do. The journal turns it into a {@link ChangeKind}:+ * a write to a path that does not exist is an add, to one that does a modify. */+export type Intent = 'write' | 'remove';++/**+ * Hold what `relPath` is right now, before the caller changes it.+ *+ * A no-op when no transaction is open — which is the ordinary case (a person+ * editing by hand), and the reason every write door can call this+ * unconditionally instead of asking first.+ *+ * The door says what it INTENDS; whether that lands as an add or a modify is+ * the journal's to answer, because it is the side that has just looked at the+ * path. A door deciding for itself is a door that can be wrong about it, and+ * "created" vs "changed" is the whole of what the history entry claims.+ */+export async function capture(relPath: string, intent: Intent): Promise<void> {+ const tx = active;+ if (!tx) return;+ const rel = relPath.split(path.sep).join('/');+ if (tx.entries.has(rel)) return;++ let abs: string;+ try {+ abs = resolveInside(tx.root, rel, 'project root');+ } catch {+ // A path the sandbox refuses is not this module's to report on — the door+ // itself is about to throw for the same reason.+ return;+ }++ if (!existsSync(abs)) {+ // A tombstone, not a copy: revert deletes what the transaction created.+ // A `remove` of something that is not there changed nothing worth recording.+ if (intent === 'write') {+ tx.entries.set(rel, { rel, kind: 'add', backup: null, unjournaled: false, isDir: false });+ }+ return;+ }++ const kind: ChangeKind = intent === 'remove' ? 'remove' : 'modify';+ const info = await stat(abs);+ const size = info.isDirectory() ? await dirSize(abs) : info.size;+ const meta = abs + META_EXT;+ const metaSize = existsSync(meta) ? (await stat(meta)).size : 0;++ if (tx.bytes + size + metaSize > budgetBytes) {+ tx.entries.set(rel, { rel, kind, backup: null, unjournaled: true, isDir: info.isDirectory() });+ return;+ }++ const backup = path.join(HOLDING_DIR, tx.id, String(tx.entries.size));+ await mkdir(backup, { recursive: true });+ await cp(abs, path.join(backup, 'item'), { recursive: true });+ // The sidecar travels with the file, so a revert restores the asset's uuid+ // along with its bytes — every `@uuid:` reference to it survives the round trip.+ if (metaSize) await cp(meta, path.join(backup, 'item' + META_EXT));+ tx.bytes += size + metaSize;+ tx.entries.set(rel, { rel, kind, backup, unjournaled: false, isDir: info.isDirectory() });+}++/** Capture several paths in the order given (a door that writes a set). */+export async function captureAll(relPaths: readonly string[], intent: Intent): Promise<void> {+ for (const rel of relPaths) await capture(rel, intent);+}++async function dirSize(abs: string): Promise<number> {+ let total = 0;+ for (const entry of await readdir(abs, { withFileTypes: true })) {+ const child = path.join(abs, entry.name);+ if (entry.isDirectory()) total += await dirSize(child);+ else if (entry.isFile()) total += (await stat(child)).size;+ // A budget that walked symlinks could be talked into counting the whole+ // disk by a project that contains one pointing at `/`.+ }+ return total;+}++/** What a transaction has touched so far, in the order it touched it. */+export function changes(id: string): JournalChange[] {+ const tx = transactions.get(id);+ if (!tx) return [];+ return [...tx.entries.values()].map((e) => ({+ path: e.rel,+ kind: e.kind,+ unjournaled: e.unjournaled,+ }));+}++/** Whether `id` still holds enough to be worth offering a revert for. */+export function isRestorable(id: string): boolean {+ const tx = transactions.get(id);+ return !!tx && tx.entries.size > 0;+}++/**+ * Put every captured path back, newest capture first, and say what happened.+ *+ * LIFO because captures within a transaction can depend on each other: creating+ * `Scripts/` then writing `Scripts/HP.ts` must come apart as delete-the-file+ * then delete-the-directory, and the reverse order leaves a directory that+ * refuses to go.+ *+ * A failure on one path does not stop the rest. The alternative — abandoning the+ * revert half way — leaves a project in a state neither the turn nor the user+ * asked for, and the report is the thing that lets someone finish by hand.+ */+export async function revert(id: string): Promise<RevertResult> {+ const tx = transactions.get(id);+ const out: RevertResult = { restored: [], unjournaled: [], failed: [] };+ if (!tx) return out;+ if (tx === active) endTransaction();++ for (const entry of [...tx.entries.values()].reverse()) {+ if (entry.unjournaled) {+ out.unjournaled.push(entry.rel);+ continue;+ }+ try {+ await restore(tx.root, entry);+ out.restored.push(entry.rel);+ } catch (e) {+ out.failed.push({ path: entry.rel, error: (e as Error)?.message ?? String(e) });+ }+ }+ // Reverting consumes the transaction: the copies have served their purpose,+ // and a second revert of the same id would restore stale bytes over whatever+ // the user has done since.+ await discard(id);+ return out;+}++async function restore(root: string, entry: Entry): Promise<void> {+ const abs = resolveInside(root, entry.rel, 'project root');+ const meta = abs + META_EXT;+ if (entry.backup === null) {+ // The transaction created it; taking the transaction back removes it.+ await rm(abs, { recursive: true, force: true });+ await rm(meta, { force: true });+ return;+ }+ const item = path.join(entry.backup, 'item');+ const itemMeta = item + META_EXT;+ await rm(abs, { recursive: true, force: true });+ await mkdir(path.dirname(abs), { recursive: true });+ await cp(item, abs, { recursive: true });+ if (existsSync(itemMeta)) await cp(itemMeta, meta);+ else await rm(meta, { force: true });+}++/** Forget a transaction and delete its copies — the user kept the work. */+export async function discard(id: string): Promise<void> {+ const tx = transactions.get(id);+ if (!tx) return;+ if (tx === active) endTransaction();+ transactions.delete(id);+ const i = finished.indexOf(id);+ if (i >= 0) finished.splice(i, 1);+ await rm(path.join(HOLDING_DIR, id), { recursive: true, force: true }).catch(() => {});+}++/** Drop everything — a project switch, or shutdown. */+export async function discardAll(): Promise<void> {+ active = null;+ const ids = [...transactions.keys()];+ transactions.clear();+ finished.length = 0;+ for (const id of ids) {+ await rm(path.join(HOLDING_DIR, id), { recursive: true, force: true }).catch(() => {});+ }+}++/** Project-relative paths a revert of `id` would touch — what the editor+ * refreshes afterwards. */+export function touchedPaths(id: string): string[] {+ return [...(transactions.get(id)?.entries.values() ?? [])].map((e) => e.rel);+}++export const __testing = {+ HOLDING_DIR,+ RETAINED,+ /** Shrink the budget so a test can reach it without writing 256MB. */+ setBudget(bytes: number): number {+ const was = budgetBytes;+ budgetBytes = bytes;+ return was;+ },+};diff --git a/desktop/electron/importAssets.ts b/desktop/electron/importAssets.tsindex df2cac51c..d318a7e2f 100644--- a/desktop/electron/importAssets.ts+++ b/desktop/electron/importAssets.ts@@ -12,6 +12,7 @@ import { existsSync } from 'node:fs';import path from 'node:path';import { isInsideRoot } from './pathSandbox';import { resolveInRoot, META_EXT } from './projectFs';+import { capture } from './fileJournal';import { EXT_TO_TYPE, metaTypeFor, metaTypeForFile, mintMeta, writeMeta, adoptOrphan } from './assetMeta';import { CONTENT_TYPED_EXTENSIONS } from '../../tools/assetMetaTable.js';@@ -83,9 +84,11 @@ export async function createAsset(}const name = uniqueName(absDir, named);const abs = path.join(absDir, name);+ const rel = destDir ? `${destDir}/${name}` : name;+ await capture(rel, 'write');await writeFile(abs, content, 'utf8');await writeFile(abs + META_EXT, JSON.stringify(mintMeta(type), null, 2) + '\n', 'utf8');- return destDir ? `${destDir}/${name}` : name;+ return rel;}export interface ImportResult {@@ -117,15 +120,21 @@ export async function importAssets(root: string, destDir: string, sources: strin}const inside = relInRoot(root, src);if (inside) {+ // Registering in place only mints a sidecar; the file itself is untouched.+ // Captured anyway, so a revert takes the `.meta` — and with it the+ // registry entry — back off a file the user had not adopted.+ await capture(inside, 'write');await adoptOrphan(path.resolve(root, inside)); // 'has-meta' = already registered, keep its uuidimported.push(inside);continue;}const name = uniqueName(absDir, path.basename(src));const absDest = path.join(absDir, name);+ const rel = destDir ? `${destDir}/${name}` : name;+ await capture(rel, 'write');await copyFile(src, absDest);await writeMeta(absDest, type);- imported.push(destDir ? `${destDir}/${name}` : name);+ imported.push(rel);}return { imported, skipped };}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 3773edb47..2d2565d61 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -24,6 +24,7 @@ import {META_EXT,} from './projectFs';import { isInsideRoot } from './pathSandbox';+import * as journal from './fileJournal';import { syncAutosave, listAutosave, restoreAutosave, clearAutosave, type AutosaveEntry } from './autosave';import { listRecents, addRecent, removeRecent, listTemplates, createFromTemplate } from './launcher';import { buildProjectScripts } from './buildScripts';@@ -866,6 +867,10 @@ const platformRuntimeDirs = (): PlatformRuntimeDirs => ({// Staging failure does NOT block the open — but it is returned so the renderer// can say it loudly (Output Log + toast), never swallowed into a console.warn.async function adoptRoot(root: string): Promise<string | undefined> {+ // Held copies name paths under the OLD root; nothing about them is restorable+ // into this one, and offering a revert that would write into a project the+ // user has left is worse than losing the offer.+ if (projectRoot !== root) await journal.discardAll();projectRoot = root;if (win) startProjectWatch(root, win.webContents);// The compiler follows the project. Built lazily on the first question, so an@@ -987,8 +992,11 @@ ipcMain.handle('fs:stat', (_e, relPath: string) => statInRoot(requireRoot(), rel// Delete to the OS trash (recoverable, not an unrecoverable rm) — the asset's// `.meta` sidecar goes with it so no orphan stays in the registry. A pre-trash// snapshot backs the renderer's Undo toast; the returned token restores it.+// The one project mutation that is not an fs write: the OS takes the file, so+// the journal's copy is what a revert puts back (the trash has no restore API).ipcMain.handle('fs:trash', async (_e, relPath: string) => {const root = requireRoot();+ await journal.capture(relPath, 'remove');const token = await snapshotForTrash(root, relPath);const abs = resolveInRoot(root, relPath);await shell.trashItem(abs);diff --git a/desktop/electron/projectFs.ts b/desktop/electron/projectFs.tsindex 03b06a3d6..d42bfe7d6 100644--- a/desktop/electron/projectFs.ts+++ b/desktop/electron/projectFs.ts@@ -25,6 +25,7 @@ import {} from '../src/project/format';import { META_EXT, isContentDir, isContentFile } from './contentPolicy';import { resolveInside } from './pathSandbox';+import { capture } from './fileJournal';export { META_EXT };@@ -137,6 +138,7 @@ export async function readOptionalInRoot(root: string, relPath: string): Promiseexport async function writeInRoot(root: string, relPath: string, contents: string): Promise<void> {const abs = resolveInRoot(root, relPath);+ await capture(relPath, 'write');await mkdir(path.dirname(abs), { recursive: true });await writeFile(abs, contents, 'utf8');}@@ -308,6 +310,10 @@ export async function renameInRoot(root: string, fromRel: string, toRelPath: strconst to = resolveInRoot(root, toRelPath);if (from === to) return;if (existsSync(to)) throw new Error(`"${toRelPath}" already exists`);+ // Both ends, because a rename changes both: putting back only the source+ // would leave the file in two places, only the destination in neither.+ await capture(fromRel, 'remove');+ await capture(toRelPath, 'write');await mkdir(path.dirname(to), { recursive: true });await rename(from, to);const fromMeta = from + META_EXT;@@ -318,6 +324,7 @@ export async function renameInRoot(root: string, fromRel: string, toRelPath: strexport async function mkdirInRoot(root: string, relPath: string): Promise<void> {const abs = resolveInRoot(root, relPath);if (existsSync(abs)) throw new Error(`"${relPath}" already exists`);+ await capture(relPath, 'write');await mkdir(abs, { recursive: true });}@@ -351,6 +358,7 @@ export async function duplicateInRoot(root: string, relPath: string): Promise<stto = path.join(dir, `${stem}${i === 1 ? ' copy' : ` copy ${i}`}${ext}`);if (!existsSync(to)) break;}+ await capture(toRel(root, to), 'write');await cp(from, to, { recursive: true });if (isDir) {diff --git a/desktop/electron/scriptScaffold.ts b/desktop/electron/scriptScaffold.tsindex 75100e6e8..0e8b97bec 100644--- a/desktop/electron/scriptScaffold.ts+++ b/desktop/electron/scriptScaffold.ts@@ -27,6 +27,7 @@ import {scriptNameProblem, scriptTargetDir, scriptModulePath, scriptWiring,type ScriptEntries, type ScriptKind,} from '../src/project/scripts';+import { capture } from './fileJournal';export type { ScriptEntries, ScriptKind };@@ -189,6 +190,7 @@ async function appendWiring(root: string, entryRel: string, line: string): Promiconst existing = existsSync(abs) ? await readFile(abs, 'utf8') : '';if (existing.split('\n').some((l) => l.trim() === line)) return;const gap = existing === '' || existing.endsWith('\n') ? '' : '\n';+ await capture(entryRel, 'write');await mkdir(path.dirname(abs), { recursive: true });await writeFile(abs, `${existing}${gap}${line}\n`, 'utf8');}@@ -216,6 +218,7 @@ export async function scaffoldScript(: systemTemplate(name, opts.entries);try {+ await capture(moduleRel, 'write');await mkdir(path.dirname(abs), { recursive: true });await writeFile(abs, source, 'utf8');await appendWiring(root, entry, line);diff --git a/desktop/tests/file-journal-doors.test.ts b/desktop/tests/file-journal-doors.test.tsnew file mode 100644index 000000000..6e52c249f--- /dev/null+++ b/desktop/tests/file-journal-doors.test.ts@@ -0,0 +1,159 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Every project-write door announces itself to the journal.+ *+ * The journal is only as good as its coverage: one door that writes without+ * capturing is a file the "Revert" button silently leaves behind, and the UI has+ * no way to know. So this drives the DOORS — writeInRoot, renameInRoot, the+ * importer, the script scaffold — and asserts the disk comes back, rather than+ * testing the journal against itself (file-journal.test.ts does that).+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import {+ writeInRoot, renameInRoot, mkdirInRoot, duplicateInRoot,+} from '../electron/projectFs';+import { createAsset, importAssets } from '../electron/importAssets';+import { scaffoldScript } from '../electron/scriptScaffold';+import { beginTransaction, endTransaction, changes, revert, discardAll } from '../electron/fileJournal';++let root = '';+const abs = (rel: string) => path.join(root, rel);+const read = (rel: string) => readFile(abs(rel), 'utf8');+const seed = async (rel: string, text: string) => {+ await mkdir(path.dirname(abs(rel)), { recursive: true });+ await writeFile(abs(rel), text, 'utf8');+};++const ENTRIES = { main: 'src/main.ts', register: 'src/components.ts' };++beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), 'estella-doors-test-'));+});+afterEach(async () => {+ await discardAll();+ await rm(root, { recursive: true, force: true });+});++describe('the doors a turn writes through', () => {+ it('writeInRoot', async () => {+ await seed('HUD.esscene', 'v0');+ beginTransaction(root);+ await writeInRoot(root, 'HUD.esscene', 'v1');+ await revert(endTransaction()!);+ expect(await read('HUD.esscene')).toBe('v0');+ });++ it('renameInRoot puts the file back where it was', async () => {+ await seed('Art/hero.png', 'PNG');+ beginTransaction(root);+ await renameInRoot(root, 'Art/hero.png', 'Art/villain.png');+ await revert(endTransaction()!);+ expect(await read('Art/hero.png')).toBe('PNG');+ expect(existsSync(abs('Art/villain.png'))).toBe(false);+ });++ it('mkdirInRoot', async () => {+ beginTransaction(root);+ await mkdirInRoot(root, 'UI');+ await revert(endTransaction()!);+ expect(existsSync(abs('UI'))).toBe(false);+ });++ it('duplicateInRoot removes the copy it named itself', async () => {+ await seed('Art/hero.png', 'PNG');+ beginTransaction(root);+ const copy = await duplicateInRoot(root, 'Art/hero.png');+ expect(existsSync(abs(copy))).toBe(true);+ await revert(endTransaction()!);+ expect(existsSync(abs(copy))).toBe(false);+ expect(await read('Art/hero.png')).toBe('PNG');+ });++ it('createAsset takes the sidecar with the file', async () => {+ beginTransaction(root);+ const rel = await createAsset(root, 'Levels', 'Arena', '{}', 'scene');+ expect(existsSync(abs(rel + '.meta'))).toBe(true);+ await revert(endTransaction()!);+ expect(existsSync(abs(rel))).toBe(false);+ expect(existsSync(abs(rel + '.meta'))).toBe(false);+ });++ // Registering a file that was already in the project mints only a sidecar.+ // The revert has to take that back too: a `.meta` left behind is an asset in+ // the registry the user never adopted.+ it('importAssets un-registers a file it adopted in place', async () => {+ await seed('Art/loose.png', 'PNG');+ beginTransaction(root);+ await importAssets(root, 'Art', [abs('Art/loose.png')]);+ expect(existsSync(abs('Art/loose.png.meta'))).toBe(true);++ await revert(endTransaction()!);+ expect(await read('Art/loose.png')).toBe('PNG');+ expect(existsSync(abs('Art/loose.png.meta'))).toBe(false);+ });++ it('importAssets removes a file it copied in', async () => {+ const outside = await mkdtemp(path.join(tmpdir(), 'estella-src-'));+ await writeFile(path.join(outside, 'sprite.png'), 'PNG', 'utf8');+ try {+ beginTransaction(root);+ const { imported } = await importAssets(root, 'Art', [path.join(outside, 'sprite.png')]);+ expect(imported).toEqual(['Art/sprite.png']);+ await revert(endTransaction()!);+ expect(existsSync(abs('Art/sprite.png'))).toBe(false);+ } finally {+ await rm(outside, { recursive: true, force: true });+ }+ });++ // The scaffold writes TWO files — the module and the entry line that makes it+ // live. A revert that took back only the module would leave an import of a+ // file that no longer exists, which is a project that will not build.+ it('scaffoldScript takes back the module AND the entry wiring', async () => {+ await seed(ENTRIES.main, 'export {};\n');+ await seed(ENTRIES.register, 'export {};\n');+ beginTransaction(root);+ const made = await scaffoldScript(root, {+ kind: 'component', name: 'HealthBarBehavior', entries: ENTRIES,+ });+ if (!made.ok || !made.path) throw new Error(made.error ?? 'no path');+ const module = made.path;+ // Asserted BEFORE the revert: an existsSync that was false all along would+ // pass this test without the journal doing anything.+ expect(existsSync(abs(module))).toBe(true);++ const id = endTransaction()!;+ expect(changes(id).map((c) => c.kind)).toContain('add');+ await revert(id);+ expect(existsSync(abs(module))).toBe(false);+ expect(await read(ENTRIES.register)).toBe('export {};\n');+ expect(await read(ENTRIES.main)).toBe('export {};\n');+ });+});++describe('what the change list says', () => {+ it('separates what the turn created from what it changed', async () => {+ await seed('HUD.esscene', 'v0');+ beginTransaction(root);+ await writeInRoot(root, 'HUD.esscene', 'v1');+ await writeInRoot(root, 'src/HealthBar.ts', 'export {};');++ expect(changes(endTransaction()!)).toEqual([+ { path: 'HUD.esscene', kind: 'modify', unjournaled: false },+ { path: 'src/HealthBar.ts', kind: 'add', unjournaled: false },+ ]);+ });++ it('is empty when no transaction was open', async () => {+ await seed('HUD.esscene', 'v0');+ await writeInRoot(root, 'HUD.esscene', 'v1');+ const id = beginTransaction(root);+ expect(changes(id)).toEqual([]);+ endTransaction();+ });+});diff --git a/desktop/tests/file-journal.test.ts b/desktop/tests/file-journal.test.tsnew file mode 100644index 000000000..decf6d615--- /dev/null+++ b/desktop/tests/file-journal.test.ts@@ -0,0 +1,255 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file fileJournal — the half of an agent transaction that lives on disk.+ *+ * The claim under test is the one the UI makes on its behalf: after a revert the+ * project's files are what they were before the transaction opened. So the+ * assertions read the disk rather than the journal's own bookkeeping.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import {+ beginTransaction, endTransaction, activeTransaction, capture, changes,+ revert, discard, discardAll, touchedPaths, isRestorable, __testing,+} from '../electron/fileJournal';++let root = '';++const abs = (rel: string) => path.join(root, rel);+const write = async (rel: string, text: string) => {+ await mkdir(path.dirname(abs(rel)), { recursive: true });+ await writeFile(abs(rel), text, 'utf8');+};+const read = (rel: string) => readFile(abs(rel), 'utf8');++beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), 'estella-journal-test-'));+});++afterEach(async () => {+ await discardAll();+ await rm(root, { recursive: true, force: true });+});++describe('a transaction over project files', () => {+ it('puts back what a write overwrote', async () => {+ await write('Scripts/HP.ts', 'before');+ beginTransaction(root);+ await capture('Scripts/HP.ts', 'write');+ await write('Scripts/HP.ts', 'after');++ const id = endTransaction()!;+ expect(await read('Scripts/HP.ts')).toBe('after');+ await revert(id);+ expect(await read('Scripts/HP.ts')).toBe('before');+ });++ it('deletes what the transaction created', async () => {+ beginTransaction(root);+ await capture('Scripts/HealthBarBehavior.ts', 'write');+ await write('Scripts/HealthBarBehavior.ts', 'export class HealthBarBehavior {}');++ const id = endTransaction()!;+ await revert(id);+ expect(existsSync(abs('Scripts/HealthBarBehavior.ts'))).toBe(false);+ });++ // A turn that writes the same file four times must revert to what was there+ // before the FIRST write — the state the user last saw.+ it('keeps the first capture of a path, not the last', async () => {+ await write('HUD.esscene', 'v0');+ beginTransaction(root);+ for (const v of ['v1', 'v2', 'v3']) {+ await capture('HUD.esscene', 'write');+ await write('HUD.esscene', v);+ }++ const id = endTransaction()!;+ expect(changes(id)).toHaveLength(1);+ await revert(id);+ expect(await read('HUD.esscene')).toBe('v0');+ });++ // Creating a directory then a file inside it comes apart the other way round;+ // deleting the directory first would leave the file with nowhere to be.+ it('unwinds captures newest-first', async () => {+ beginTransaction(root);+ await capture('UI', 'write');+ await mkdir(abs('UI'), { recursive: true });+ await capture('UI/HealthBar.esprefab', 'write');+ await write('UI/HealthBar.esprefab', '{}');++ const id = endTransaction()!;+ const result = await revert(id);+ expect(result.failed).toEqual([]);+ expect(existsSync(abs('UI'))).toBe(false);+ });++ it('restores a .meta sidecar with its file, so the uuid survives', async () => {+ await write('Art/hero.png', 'PNG0');+ await write('Art/hero.png.meta', '{"uuid":"keep-me"}');+ beginTransaction(root);+ await capture('Art/hero.png', 'remove');+ await rm(abs('Art/hero.png'));+ await rm(abs('Art/hero.png.meta'));++ const id = endTransaction()!;+ await revert(id);+ expect(await read('Art/hero.png')).toBe('PNG0');+ expect(JSON.parse(await read('Art/hero.png.meta')).uuid).toBe('keep-me');+ });++ // A file that gained a sidecar during the transaction must lose it again:+ // leaving one behind puts an asset in the registry the revert claims to have+ // removed.+ it('removes a sidecar the transaction added', async () => {+ await write('Art/hero.png', 'PNG0');+ beginTransaction(root);+ await capture('Art/hero.png', 'write');+ await write('Art/hero.png.meta', '{"uuid":"new"}');++ const id = endTransaction()!;+ await revert(id);+ expect(existsSync(abs('Art/hero.png.meta'))).toBe(false);+ });++ it('restores a captured directory whole', async () => {+ await write('Levels/one.esscene', 'A');+ await write('Levels/two.esscene', 'B');+ beginTransaction(root);+ await capture('Levels', 'write');+ await rm(abs('Levels'), { recursive: true });+ await write('Levels/three.esscene', 'C');++ const id = endTransaction()!;+ await revert(id);+ expect(await read('Levels/one.esscene')).toBe('A');+ expect(await read('Levels/two.esscene')).toBe('B');+ expect(existsSync(abs('Levels/three.esscene'))).toBe(false);+ });+});++describe('what it reports', () => {+ it('names each path once, with what was done to it', async () => {+ await write('HUD.esscene', 'v0');+ beginTransaction(root);+ await capture('HUD.esscene', 'write');+ await capture('Scripts/HP.ts', 'write');++ const id = endTransaction()!;+ expect(changes(id)).toEqual([+ { path: 'HUD.esscene', kind: 'modify', unjournaled: false },+ { path: 'Scripts/HP.ts', kind: 'add', unjournaled: false },+ ]);+ expect(touchedPaths(id)).toEqual(['HUD.esscene', 'Scripts/HP.ts']);+ });++ // A door captures before it looks, so it captures deletes that turn out to be+ // no-ops too. Recording one would put a phantom line in the history entry.+ it('records nothing for a remove of a path that is not there', async () => {+ beginTransaction(root);+ await capture('never-existed.txt', 'remove');+ expect(changes(endTransaction()!)).toEqual([]);+ });++ // The point of the report: a revert that leaves something in place says so,+ // rather than letting the UI claim the whole turn came back.+ it('says which paths it could not hold', async () => {+ const was = __testing.setBudget(100);+ try {+ await write('small.txt', 'x'.repeat(50));+ await write('Video/intro.mp4', 'y'.repeat(200));+ beginTransaction(root);+ await capture('small.txt', 'write');+ await capture('Video/intro.mp4', 'write');+ await write('small.txt', 'replaced');+ await write('Video/intro.mp4', 'replaced');++ const id = endTransaction()!;+ expect(changes(id)).toEqual([+ { path: 'small.txt', kind: 'modify', unjournaled: false },+ { path: 'Video/intro.mp4', kind: 'modify', unjournaled: true },+ ]);+ const result = await revert(id);+ expect(result.restored).toEqual(['small.txt']);+ expect(result.unjournaled).toEqual(['Video/intro.mp4']);+ expect(await read('small.txt')).toBe('x'.repeat(50));+ expect(await read('Video/intro.mp4')).toBe('replaced');+ } finally {+ __testing.setBudget(was);+ }+ });++ it('reports a restore that threw instead of swallowing it', async () => {+ await write('locked.txt', 'before');+ beginTransaction(root);+ await capture('locked.txt', 'write');+ const id = endTransaction()!;+ // The project root is gone — every restore under it must fail loudly.+ await rm(root, { recursive: true, force: true });+ await writeFile(root, 'now a file', 'utf8');++ const result = await revert(id);+ expect(result.restored).toEqual([]);+ expect(result.failed).toHaveLength(1);+ expect(result.failed[0].path).toBe('locked.txt');+ });+});++describe('a transaction lifetime', () => {+ it('captures nothing while none is open', async () => {+ await write('a.txt', 'before');+ expect(activeTransaction()).toBeNull();+ await capture('a.txt', 'write');+ await write('a.txt', 'after');+ // No transaction, nothing held, nothing to revert.+ expect(changes('nope')).toEqual([]);+ });++ it('opening a second one closes the first', async () => {+ beginTransaction(root);+ await capture('a.txt', 'write');+ const second = beginTransaction(root);+ expect(activeTransaction()).toBe(second);+ });++ it('a revert consumes the transaction, so a second one is a no-op', async () => {+ await write('a.txt', 'before');+ beginTransaction(root);+ await capture('a.txt', 'write');+ await write('a.txt', 'after');+ const id = endTransaction()!;++ await revert(id);+ await write('a.txt', 'the user typed this');+ const again = await revert(id);+ expect(again.restored).toEqual([]);+ expect(await read('a.txt')).toBe('the user typed this');+ });++ it('discard drops the copies and stops offering a revert', async () => {+ await write('a.txt', 'before');+ beginTransaction(root);+ await capture('a.txt', 'write');+ const id = endTransaction()!;+ expect(isRestorable(id)).toBe(true);++ await discard(id);+ expect(isRestorable(id)).toBe(false);+ });++ it('reverting the open transaction closes it first', async () => {+ await write('a.txt', 'before');+ const id = beginTransaction(root);+ await capture('a.txt', 'write');+ await write('a.txt', 'after');++ await revert(id);+ expect(activeTransaction()).toBeNull();+ expect(await read('a.txt')).toBe('before');+ });+});