import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; import path from "node:path"; import { Volume } from "memfs"; const TEST_DIR = "/test"; const vol = new Volume(); // Call mock.module at TOP LEVEL before any imports of rm.ts happen // This ensures the mock is in place when rm.ts is dynamically imported mock.module("node:fs/promises", createFsMock); // Factory function for the fs mock - used at top level and in resetFsMock() function createFsMock() { return { lstat: async (p: string) => vol.lstatSync(p), mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts), cp: async (src: string, dest: string, opts?: any) => vol.cpSync(src, dest, opts), rm: async (p: string, opts?: any) => { const stat = vol.lstatSync(p); if (stat.isSymbolicLink()) { vol.unlinkSync(p); } else { vol.rmSync(p, opts); } }, symlink: async (target: string, p: string) => vol.symlinkSync(target, p), readlink: async (p: string) => vol.readlinkSync(p), readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts), writeFile: async (p: string, data: any) => vol.writeFileSync(p, data), readdir: async (p: string, opts?: any) => vol.readdirSync(p, opts), stat: async (p: string) => vol.statSync(p), open: async () => ({ close: async () => {} }), }; } function resetFsMock() { mock.module("node:fs/promises", createFsMock); } function makeMock(overrides: Partial> = {}) { return { lstat: mock( async () => ({ isDirectory: () => false, isSymbolicLink: () => false, }) as any, ), mkdir: async () => {}, cp: async () => {}, rm: async () => {}, symlink: async () => {}, readlink: async () => {}, readFile: async () => "", writeFile: async () => {}, readdir: async () => [], stat: mock(async () => ({ isDirectory: () => false }) as any), open: async () => ({ close: async () => {} }), ...overrides, }; } beforeEach(() => { vol.reset(); vol.mkdirSync(TEST_DIR, { recursive: true }); resetFsMock(); }); // Context object for testing (cast to any to satisfy ToolContext type) const ctx = { directory: TEST_DIR, } as any; describe("getTrashPath", () => { test("generates trash path with timestamp", async () => { const { getTrashPath } = await import("../tools/rm.ts"); const result = getTrashPath("/home/user/file.txt", "/home/user"); expect(result).toMatch(/^\/home\/user\/\.trash\/file\.txt\.\.\d+$/); }); test("handles nested paths", async () => { const { getTrashPath } = await import("../tools/rm.ts"); const result = getTrashPath("/home/user/a/b/c.txt", "/home/user"); expect(result).toMatch(/^\/home\/user\/\.trash\/a\/b\/c\.txt\.\.\d+$/); }); test("handles file directly in directory", async () => { const { getTrashPath } = await import("../tools/rm.ts"); const result = getTrashPath("/home/user/file.txt", "/home/user"); expect(result).toContain(".trash/file.txt.."); }); test("preserves directory structure", async () => { const { getTrashPath } = await import("../tools/rm.ts"); const result = getTrashPath("/home/user/a/b/c.txt", "/home/user"); expect(result).toContain(".trash/a/b/c.txt.."); }); test("handles file already inside .trash directory", async () => { // If a file is already inside .trash, getTrashPath will create nested .trash/.trash/... // This tests the path generation, not security (which is handled by assertWithinDirectory) const { getTrashPath } = await import("../tools/rm.ts"); const result = getTrashPath("/home/user/.trash/somefile.txt", "/home/user"); // Should generate: /home/user/.trash/.trash/somefile.txt..timestamp expect(result).toContain(".trash/.trash/somefile.txt.."); }); // Additional getTrashPath tests test("handles file at exact boundary of directory", async () => { const { getTrashPath } = await import("../tools/rm.ts"); const result = getTrashPath("/a/b", "/a"); // "/a/b" relative to "/a" is "b", so trash path should be "/a/.trash/b..TIMESTAMP" expect(result).toMatch(/^\/a\/\.trash\/b\.\.\d+$/); }); test("timestamp in trash path is within a few seconds of Date.now()", async () => { const { getTrashPath } = await import("../tools/rm.ts"); const before = Date.now(); const result = getTrashPath("/home/user/file.txt", "/home/user"); const after = Date.now(); // Extract timestamp from the path (last numeric segment) const match = result.match(/\.\.(\d+)$/); expect(match).not.toBeNull(); const timestamp = parseInt(match![1]!, 10); expect(timestamp).toBeGreaterThanOrEqual(before); expect(timestamp).toBeLessThanOrEqual(after + 1000); // Allow 1 second tolerance }); }); describe("extractTimestamp", () => { test("parses regular file", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); expect(extractTimestamp("file.txt..1773104000000")).toEqual({ path: "file.txt", timestamp: 1773104000000, }); }); test("parses symlink backup", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); expect(extractTimestamp("link..1773104000000.symlink")).toEqual({ path: "link", timestamp: 1773104000000, }); }); test("returns null for missing timestamp", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); expect(extractTimestamp("file.txt")).toBeNull(); }); test("returns null for future timestamp", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); expect(extractTimestamp("file.txt.." + (Date.now() + 100000))).toBeNull(); }); test("returns null for invalid timestamp", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); expect(extractTimestamp("file.txt..notanumber")).toBeNull(); }); test("handles filename with multiple dots", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); expect(extractTimestamp("file.name.txt..1773104000000")).toEqual({ path: "file.name.txt", timestamp: 1773104000000, }); }); test("handles hidden files", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); expect(extractTimestamp(".hidden..1773104000000")).toEqual({ path: ".hidden", timestamp: 1773104000000, }); }); test("handles path with directories", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); expect(extractTimestamp("a/b/c.txt..1773104000000")).toEqual({ path: "a/b/c.txt", timestamp: 1773104000000, }); }); test("allows very old timestamp", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); const oldTimestamp = Date.now() - 70000; expect(extractTimestamp("file.txt.." + oldTimestamp)).not.toBeNull(); }); test("handles timestamp with only digits after dots", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); const result = extractTimestamp("file..1234567890123"); expect(result?.timestamp).toBe(1234567890123); }); test("handles very old valid timestamp", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); const old = Date.now() - 365 * 24 * 60 * 60 * 1000; const result = extractTimestamp(`file..${old}`); expect(result).not.toBeNull(); }); test("trailing dot after stripping .symlink suffix", async () => { // "file...1773104000000.symlink" → strip .symlink → "file...1773104000000." // → strip trailing dot → "file...1773104000000" // → regex matches: path = "file.", timestamp = 1773104000000 const { extractTimestamp } = await import("../tools/rm.ts"); const result = extractTimestamp("file...1773104000000.symlink"); expect(result).not.toBeNull(); expect(result?.path).toBe("file."); expect(result?.timestamp).toBe(1773104000000); }); test("timestamp exactly at boundary (now + 60000) is accepted", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); const boundary = Date.now() + 60000; // Exactly at boundary: condition is timestamp > now + 60000, so boundary itself passes const result = extractTimestamp(`file..${boundary}`); expect(result).not.toBeNull(); }); test("timestamp one millisecond past boundary is rejected", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); const pastBoundary = Date.now() + 60001; expect(extractTimestamp(`file..${pastBoundary}`)).toBeNull(); }); // Additional extractTimestamp tests for new edge cases test("returns null for filename that is just dots and timestamp (empty path after stripping)", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); // "..1773104000000" → after stripping trailing dot: "..1773104000000" // → regex matches "..1773104000000", path becomes empty string → returns null expect(extractTimestamp("..1773104000000")).toBeNull(); }); test("returns null for timestamp embedded in middle but NOT at end", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); // "file..1773104000000.extra" → regex anchored at end, doesn't match expect(extractTimestamp("file..1773104000000.extra")).toBeNull(); }); test("takes rightmost timestamp when multiple double-dot segments exist", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); // "a..b..1773104000001" → regex takes rightmost match: ..1773104000001 expect(extractTimestamp("a..b..1773104000001")).toEqual({ path: "a..b", timestamp: 1773104000001, }); }); test("handles symlink backup where base has multiple double-dots", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); // "a..b..1773104000000.symlink" → strip .symlink → "a..b..1773104000000." // → strip trailing dot → "a..b..1773104000000" → regex: path="a..b", ts=1773104000000 expect(extractTimestamp("a..b..1773104000000.symlink")).toEqual({ path: "a..b", timestamp: 1773104000000, }); }); }); describe("assertWithinDirectory", () => { test("allows paths within directory", async () => { const { assertWithinDirectory } = await import("../tools/rm.ts"); expect(() => assertWithinDirectory("/home/user/file.txt", "/home/user", "test") ).not.toThrow(); }); test("allows same path as directory", async () => { const { assertWithinDirectory } = await import("../tools/rm.ts"); expect(() => assertWithinDirectory("/home/user", "/home/user", "test")).not .toThrow(); }); test("blocks paths escaping directory", async () => { const { assertWithinDirectory } = await import("../tools/rm.ts"); expect(() => assertWithinDirectory("/etc/passwd", "/home/user", "test")) .toThrow("path escapes working directory"); }); test("blocks parent directory escape", async () => { const { assertWithinDirectory } = await import("../tools/rm.ts"); expect(() => assertWithinDirectory("/home/user/../etc/passwd", "/home/user", "test") ).toThrow("path escapes working directory"); }); test("includes operation name in error", async () => { const { assertWithinDirectory } = await import("../tools/rm.ts"); expect(() => assertWithinDirectory("/etc/passwd", "/home/user", "myOp")) .toThrow("myOp: path escapes working directory"); }); test("blocks path that shares prefix but escapes directory", async () => { // /home/userEvil starts with /home/user as a string but is NOT within /home/user/ const { assertWithinDirectory } = await import("../tools/rm.ts"); expect(() => assertWithinDirectory("/home/userEvil/file.txt", "/home/user", "test") ).toThrow("path escapes working directory"); }); test("blocks sibling directory with shared prefix", async () => { const { assertWithinDirectory } = await import("../tools/rm.ts"); expect(() => assertWithinDirectory("/home/user2", "/home/user", "test")) .toThrow("path escapes working directory"); }); // Additional assertWithinDirectory tests test("allows directory path with trailing slash", async () => { const { assertWithinDirectory } = await import("../tools/rm.ts"); // "/home/user/" with trailing slash should work expect(() => assertWithinDirectory("/home/user/file.txt", "/home/user/", "op") ).not.toThrow(); }); test("allows deeply nested path", async () => { const { assertWithinDirectory } = await import("../tools/rm.ts"); expect(() => assertWithinDirectory("/home/user/a/b/c/d/e.txt", "/home/user", "op") ).not.toThrow(); }); }); describe("safeStat", () => { test("returns stat for existing file", async () => { vol.writeFileSync(path.join(TEST_DIR, "exists.txt"), "content"); const { safeStat } = await import("../tools/rm.ts"); const result = await safeStat(path.join(TEST_DIR, "exists.txt")); expect(result.exists).toBe(true); expect(result.isDirectory).toBe(false); }); test("returns stat for existing directory", async () => { vol.mkdirSync(path.join(TEST_DIR, "dir")); const { safeStat } = await import("../tools/rm.ts"); const result = await safeStat(path.join(TEST_DIR, "dir")); expect(result.exists).toBe(true); expect(result.isDirectory).toBe(true); }); test("returns false for missing file", async () => { const { safeStat } = await import("../tools/rm.ts"); const result = await safeStat(path.join(TEST_DIR, "missing.txt")); expect(result.exists).toBe(false); }); test("returns exists:false for ENOENT", async () => { const { safeStat } = await import("../tools/rm.ts"); const result = await safeStat(path.join(TEST_DIR, "nonexistent")); expect(result.exists).toBe(false); expect(result.isDirectory).toBe(false); }); test("throws for non-ENOENT errors", async () => { mock.module("node:fs/promises", () => makeMock({ lstat: mock(async () => { const err = new Error("Permission denied") as NodeJS.ErrnoException; err.code = "EACCES"; throw err; }), })); const { safeStat } = await import("../tools/rm.ts"); await expect(safeStat("/some/path")).rejects.toThrow("Permission denied"); }); // Additional safeStat tests test("safeStat on symlink to directory returns isDirectory:false", async () => { vol.mkdirSync(path.join(TEST_DIR, "targetdir")); vol.writeFileSync(path.join(TEST_DIR, "targetdir", "file.txt"), "content"); vol.symlinkSync( path.join(TEST_DIR, "targetdir"), path.join(TEST_DIR, "linktodir"), ); const { safeStat } = await import("../tools/rm.ts"); // safeStat uses lstat, which sees the symlink itself, not the target const result = await safeStat(path.join(TEST_DIR, "linktodir")); expect(result.exists).toBe(true); expect(result.isDirectory).toBe(false); // It's a symlink, not a directory }); }); describe("isSymlink", () => { test("returns false for regular file", async () => { vol.writeFileSync(path.join(TEST_DIR, "file.txt"), "content"); const { isSymlink } = await import("../tools/rm.ts"); expect(await isSymlink(path.join(TEST_DIR, "file.txt"))).toBe(false); }); test("returns true for symlink", async () => { vol.symlinkSync("target", path.join(TEST_DIR, "link")); const { isSymlink } = await import("../tools/rm.ts"); expect(await isSymlink(path.join(TEST_DIR, "link"))).toBe(true); }); test("returns false for a directory", async () => { vol.mkdirSync(path.join(TEST_DIR, "somedir")); const { isSymlink } = await import("../tools/rm.ts"); expect(await isSymlink(path.join(TEST_DIR, "somedir"))).toBe(false); }); test("returns false when lstat throws any error", async () => { mock.module("node:fs/promises", () => makeMock({ lstat: mock(async () => { throw new Error("EACCES: permission denied"); }), })); const { isSymlink } = await import("../tools/rm.ts"); expect(await isSymlink("/any/path")).toBe(false); }); }); describe("moveToTrash", () => { test("moves file to trash", async () => { vol.writeFileSync(path.join(TEST_DIR, "test.txt"), "hello world"); const { moveToTrash, safeStat } = await import("../tools/rm.ts"); const trashPath = await moveToTrash( path.join(TEST_DIR, "test.txt"), TEST_DIR, false, ); const exists = await safeStat(path.join(TEST_DIR, "test.txt")); expect(exists.exists).toBe(false); expect(vol.readFileSync(trashPath, "utf-8")).toBe("hello world"); }); test("moves directory to trash", async () => { vol.mkdirSync(path.join(TEST_DIR, "dir")); vol.writeFileSync(path.join(TEST_DIR, "dir", "a.txt"), "a"); vol.writeFileSync(path.join(TEST_DIR, "dir", "b.txt"), "b"); const { moveToTrash, safeStat } = await import("../tools/rm.ts"); const trashPath = await moveToTrash( path.join(TEST_DIR, "dir"), TEST_DIR, true, ); const exists = await safeStat(path.join(TEST_DIR, "dir")); expect(exists.exists).toBe(false); expect(vol.readdirSync(trashPath)).toHaveLength(2); }); test("handles deeply nested directory", async () => { vol.mkdirSync(path.join(TEST_DIR, "a", "b", "c"), { recursive: true }); vol.writeFileSync(path.join(TEST_DIR, "a", "b", "c", "deep.txt"), "deep"); const { moveToTrash } = await import("../tools/rm.ts"); const trashPath = await moveToTrash( path.join(TEST_DIR, "a"), TEST_DIR, true, ); expect( vol.readFileSync(path.join(trashPath, "b", "c", "deep.txt"), "utf-8"), ).toBe("deep"); }); test("handles empty directory", async () => { vol.mkdirSync(path.join(TEST_DIR, "empty")); const { moveToTrash, safeStat } = await import("../tools/rm.ts"); const trashPath = await moveToTrash( path.join(TEST_DIR, "empty"), TEST_DIR, true, ); const exists = await safeStat(path.join(TEST_DIR, "empty")); expect(exists.exists).toBe(false); expect(vol.existsSync(trashPath)).toBe(true); }); test("handles symlink backup", async () => { vol.writeFileSync(path.join(TEST_DIR, "target.txt"), "target"); vol.symlinkSync("target.txt", path.join(TEST_DIR, "link")); const { moveToTrash, safeStat } = await import("../tools/rm.ts"); const trashPath = await moveToTrash( path.join(TEST_DIR, "link"), TEST_DIR, false, ); const exists = await safeStat(path.join(TEST_DIR, "link")); expect(exists.exists).toBe(false); expect(vol.readFileSync(trashPath, "utf-8")).toBe("target.txt"); }); test("fails on missing file", async () => { const { moveToTrash } = await import("../tools/rm.ts"); expect(() => moveToTrash(path.join(TEST_DIR, "missing.txt"), TEST_DIR, false) ).toThrow(); }); test("blocks path escape", async () => { const { moveToTrash } = await import("../tools/rm.ts"); expect(() => moveToTrash("/etc/passwd", TEST_DIR, false)).toThrow( "path escapes working directory", ); }); test("creates trash directory if not exists", async () => { vol.writeFileSync(path.join(TEST_DIR, "new.txt"), "content"); vol.rmSync(path.join(TEST_DIR, ".trash"), { recursive: true, force: true }); const { safeStat } = await import("../tools/rm.ts"); const trashDirExistsBefore = await safeStat(path.join(TEST_DIR, ".trash")); expect(trashDirExistsBefore.exists).toBe(false); const { moveToTrash } = await import("../tools/rm.ts"); await moveToTrash(path.join(TEST_DIR, "new.txt"), TEST_DIR, false); const trashDirExistsAfter = await safeStat(path.join(TEST_DIR, ".trash")); expect(trashDirExistsAfter.exists).toBe(true); }); test("cleans up trash on rm failure", async () => { mock.module("node:fs/promises", () => makeMock({ rm: mock(async () => { throw new Error("rm failed"); }), })); const { moveToTrash } = await import("../tools/rm.ts"); await expect(moveToTrash("/a/b.txt", "/a", false)).rejects.toThrow( "rm failed", ); }); test("cleans up symlink backup when rm fails", async () => { let rmCallCount = 0; mock.module("node:fs/promises", () => makeMock({ lstat: mock( async () => ({ isDirectory: () => false, isSymbolicLink: () => true, }) as any, ), rm: mock(async () => { rmCallCount++; if (rmCallCount === 1) { throw new Error("rm failed"); } }), readFile: mock(async () => "target.txt"), })); const { moveToTrash } = await import("../tools/rm.ts"); await expect(moveToTrash("/a/link", "/a", false)).rejects.toThrow( "rm failed", ); }); test("propagates error when cp fails for directory", async () => { mock.module("node:fs/promises", () => makeMock({ lstat: mock( async () => ({ isDirectory: () => true, isSymbolicLink: () => false, }) as any, ), cp: mock(async () => { throw new Error("cp directory failed"); }), stat: mock(async () => ({ isDirectory: () => true }) as any), })); const { moveToTrash } = await import("../tools/rm.ts"); await expect(moveToTrash("/a/dir", "/a", true)).rejects.toThrow( "cp directory failed", ); }); test("propagates error when writeFile fails during symlink backup", async () => { mock.module("node:fs/promises", () => makeMock({ lstat: mock( async () => ({ isDirectory: () => false, isSymbolicLink: () => true, }) as any, ), readlink: mock(async () => "target.txt"), writeFile: mock(async () => { throw new Error("writeFile failed"); }), })); const { moveToTrash } = await import("../tools/rm.ts"); await expect(moveToTrash("/a/link", "/a", false)).rejects.toThrow( "writeFile failed", ); }); // Additional moveToTrash tests test("returns symlink backup path when moving symlink", async () => { vol.writeFileSync(path.join(TEST_DIR, "target.txt"), "target"); vol.symlinkSync("target.txt", path.join(TEST_DIR, "link")); const { moveToTrash } = await import("../tools/rm.ts"); const trashPath = await moveToTrash( path.join(TEST_DIR, "link"), TEST_DIR, false, ); // When moving a symlink, the returned path should be the .symlink backup path expect(trashPath).toMatch(/\.symlink$/); }); }); describe("file", () => { test("removes file and returns backup path", async () => { vol.writeFileSync(path.join(TEST_DIR, "test.txt"), "content"); const { file, safeStat } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "test.txt" }, ctx, ); expect(result).toContain("Removed: test.txt"); expect(result).toContain("Backup:"); const exists = await safeStat(path.join(TEST_DIR, "test.txt")); expect(exists.exists).toBe(false); }); test("throws on empty path", async () => { const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: " " }, ctx), ).rejects.toThrow("path cannot be empty"); }); test("throws when trying to delete project directory", async () => { const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "." }, ctx), ).rejects.toThrow("cannot delete project directory"); }); test("throws when trying to delete parent directory", async () => { const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: ".." }, ctx), ).rejects.toThrow("path escapes working directory"); }); test("throws on not found", async () => { const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "missing.txt" }, ctx), ).rejects.toThrow("not found"); }); test("throws when target is directory", async () => { vol.mkdirSync(path.join(TEST_DIR, "isdir")); const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "isdir" }, ctx), ).rejects.toThrow("Path is a directory"); }); test("includes tool name in error message", async () => { const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "" }, ctx), ).rejects.toThrow("file"); }); // Additional file tool tests test("handles filePath with leading/trailing spaces that resolve to valid file", async () => { vol.writeFileSync(path.join(TEST_DIR, "test.txt"), "content"); const { file, safeStat } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: " test.txt " }, ctx, ); // The result contains the original (untrimmed) path in the message expect(result).toContain("Removed: test.txt "); const exists = await safeStat(path.join(TEST_DIR, "test.txt")); expect(exists.exists).toBe(false); }); test("handles absolute path that is within project directory", async () => { vol.mkdirSync(path.join(TEST_DIR, "subdir"), { recursive: true }); vol.writeFileSync(path.join(TEST_DIR, "subdir", "file.txt"), "content"); const { file, safeStat } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: path.join(TEST_DIR, "subdir", "file.txt") }, ctx, ); expect(result).toContain("Removed:"); const exists = await safeStat(path.join(TEST_DIR, "subdir", "file.txt")); expect(exists.exists).toBe(false); }); test("error message for not found includes the missing filename", async () => { const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "missing.txt" }, ctx), ).rejects.toThrow("missing.txt"); }); test("error message for Path is a directory includes the path", async () => { vol.mkdirSync(path.join(TEST_DIR, "isdir")); const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "isdir" }, ctx), ).rejects.toThrow("isdir"); }); }); describe("directory", () => { test("removes directory and returns backup path", async () => { vol.mkdirSync(path.join(TEST_DIR, "mydir")); vol.writeFileSync(path.join(TEST_DIR, "mydir", "file.txt"), "content"); const { directory: dirTool, safeStat } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "mydir" }, ctx, ); expect(result).toContain("Removed: mydir"); expect(result).toContain("Backup:"); const exists = await safeStat(path.join(TEST_DIR, "mydir")); expect(exists.exists).toBe(false); }); test("throws on empty path", async () => { const { directory: dirTool } = await import("../tools/rm.ts"); await expect( dirTool.execute({ directory: "" }, ctx), ).rejects.toThrow("path cannot be empty"); }); test("throws when trying to delete project directory", async () => { const { directory: dirTool } = await import("../tools/rm.ts"); await expect( dirTool.execute({ directory: "." }, ctx), ).rejects.toThrow("cannot delete project directory"); }); test("throws when trying to delete parent directory", async () => { const { directory: dirTool } = await import("../tools/rm.ts"); await expect( dirTool.execute({ directory: ".." }, ctx), ).rejects.toThrow("path escapes working directory"); }); test("throws when target is file", async () => { vol.writeFileSync(path.join(TEST_DIR, "isfile.txt"), "content"); const { directory: dirTool } = await import("../tools/rm.ts"); await expect( dirTool.execute({ directory: "isfile.txt" }, ctx), ).rejects.toThrow("Path is a file"); }); test("throws when directory is empty path", async () => { const { directory: dirTool } = await import("../tools/rm.ts"); await expect( dirTool.execute({ directory: " " }, ctx), ).rejects.toThrow("path cannot be empty"); }); test("handles directory with subdirectories", async () => { vol.mkdirSync(path.join(TEST_DIR, "parent", "child1", "grandchild"), { recursive: true, }); vol.mkdirSync(path.join(TEST_DIR, "parent", "child2"), { recursive: true }); vol.writeFileSync(path.join(TEST_DIR, "parent", "root.txt"), "root"); vol.writeFileSync( path.join(TEST_DIR, "parent", "child1", "file.txt"), "child", ); vol.writeFileSync( path.join(TEST_DIR, "parent", "child2", "file.txt"), "child2", ); const { directory: dirTool, safeStat } = await import("../tools/rm.ts"); await dirTool.execute({ directory: "parent" }, ctx); const exists = await safeStat(path.join(TEST_DIR, "parent")); expect(exists.exists).toBe(false); }); test("throws on not found directory", async () => { const { directory: dirTool } = await import("../tools/rm.ts"); await expect( dirTool.execute( { directory: "nonexistent-dir" }, ctx, ), ).rejects.toThrow("not found"); }); test("throws on path escape via directory tool", async () => { const { directory: dirTool } = await import("../tools/rm.ts"); await expect( dirTool.execute({ directory: "../outside" }, ctx), ).rejects.toThrow("path escapes working directory"); }); test("includes tool name in directory not-found error", async () => { const { directory: dirTool } = await import("../tools/rm.ts"); await expect( dirTool.execute({ directory: "missing" }, ctx), ).rejects.toThrow("directory not found"); }); // Additional directory tool tests test("handles directory containing hidden files", async () => { vol.mkdirSync(path.join(TEST_DIR, "with-hidden")); vol.writeFileSync( path.join(TEST_DIR, "with-hidden", ".gitignore"), "node_modules", ); vol.writeFileSync(path.join(TEST_DIR, "with-hidden", ".env"), "SECRET=123"); vol.writeFileSync( path.join(TEST_DIR, "with-hidden", "regular.txt"), "content", ); const { directory: dirTool, restore } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "with-hidden" }, ctx, ); expect(result).toContain("Removed: with-hidden"); const backupPath = result.split("Backup: ")[1]!.trim(); await restore.execute({ trashPath: backupPath }, ctx); // All files should be restored expect( vol.existsSync(path.join(TEST_DIR, "with-hidden", ".gitignore")), ).toBe(true); expect(vol.existsSync(path.join(TEST_DIR, "with-hidden", ".env"))).toBe( true, ); expect( vol.existsSync(path.join(TEST_DIR, "with-hidden", "regular.txt")), ).toBe(true); expect( vol.readFileSync( path.join(TEST_DIR, "with-hidden", ".gitignore"), "utf-8", ), ).toBe("node_modules"); expect( vol.readFileSync(path.join(TEST_DIR, "with-hidden", ".env"), "utf-8"), ).toBe("SECRET=123"); expect( vol.readFileSync( path.join(TEST_DIR, "with-hidden", "regular.txt"), "utf-8", ), ).toBe("content"); }); test("error message for Path is a file includes the path", async () => { vol.writeFileSync(path.join(TEST_DIR, "isfile.txt"), "content"); const { directory: dirTool } = await import("../tools/rm.ts"); await expect( dirTool.execute({ directory: "isfile.txt" }, ctx), ).rejects.toThrow("isfile.txt"); }); }); describe("restore", () => { test("restores file from trash", async () => { vol.writeFileSync(path.join(TEST_DIR, "restored.txt"), "original"); const { file, restore } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "restored.txt" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); const restoreResult = await restore.execute( { trashPath: backupPath }, ctx, ); expect(restoreResult).toContain("Restored:"); expect(vol.readFileSync(path.join(TEST_DIR, "restored.txt"), "utf-8")).toBe( "original", ); }); test("restores directory from trash", async () => { vol.mkdirSync(path.join(TEST_DIR, "restored-dir")); vol.writeFileSync( path.join(TEST_DIR, "restored-dir", "file.txt"), "content", ); const { directory: dirTool, restore, safeStat, } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "restored-dir" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); await restore.execute( { trashPath: backupPath }, ctx, ); const exists = await safeStat(path.join(TEST_DIR, "restored-dir")); expect(exists.exists).toBe(true); }); test("throws when destination exists", async () => { vol.writeFileSync(path.join(TEST_DIR, "exists.txt"), "original"); const { file, restore } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "exists.txt" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); vol.writeFileSync(path.join(TEST_DIR, "exists.txt"), "existing"); await expect( restore.execute( { trashPath: backupPath }, ctx, ), ).rejects.toThrow("already exists"); }); test("throws on empty trash path", async () => { const { restore } = await import("../tools/rm.ts"); await expect( restore.execute({ trashPath: "" }, ctx), ).rejects.toThrow("cannot be empty"); }); test("throws when trash item not found", async () => { const { restore } = await import("../tools/rm.ts"); await expect( restore.execute( { trashPath: ".trash/missing..123456789" }, ctx, ), ).rejects.toThrow("Trash item not found"); }); test("throws on invalid trash path format", async () => { vol.mkdirSync(path.join(TEST_DIR, ".trash"), { recursive: true }); vol.writeFileSync(path.join(TEST_DIR, ".trash", "invalid"), "content"); const { restore } = await import("../tools/rm.ts"); await expect( restore.execute({ trashPath: ".trash/invalid" }, ctx), ).rejects.toThrow("Invalid trash path format"); }); test("throws on path escape in restore", async () => { const { restore } = await import("../tools/rm.ts"); await expect( restore.execute( { trashPath: "/tmp/.trash/test..123" }, ctx, ), ).rejects.toThrow("path escapes working directory"); }); test("handles filename with multiple dots", async () => { vol.writeFileSync(path.join(TEST_DIR, "file.name.txt"), "content"); const { file, safeStat } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "file.name.txt" }, ctx, ); expect(result).toContain("Removed: file.name.txt"); const exists = await safeStat(path.join(TEST_DIR, "file.name.txt")); expect(exists.exists).toBe(false); }); test("restores to nested path", async () => { vol.mkdirSync(path.join(TEST_DIR, "a", "b"), { recursive: true }); vol.writeFileSync( path.join(TEST_DIR, "a", "b", "nested.txt"), "nested content", ); const { directory: dirTool, restore } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "a" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); vol.rmSync(path.join(TEST_DIR, "a"), { recursive: true, force: true }); await restore.execute( { trashPath: backupPath }, ctx, ); expect( vol.readFileSync(path.join(TEST_DIR, "a", "b", "nested.txt"), "utf-8"), ).toBe("nested content"); }); test("handles unicode filename", async () => { vol.writeFileSync(path.join(TEST_DIR, "文件.txt"), "content"); const { file, restore } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "文件.txt" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); await restore.execute( { trashPath: backupPath }, ctx, ); expect(vol.existsSync(path.join(TEST_DIR, "文件.txt"))).toBe(true); }); test("restores symlink from backup", async () => { vol.mkdirSync(path.join(TEST_DIR, ".trash"), { recursive: true }); vol.writeFileSync( path.join(TEST_DIR, ".trash", "link..123.symlink"), "target.txt", ); const { restore, isSymlink, safeStat } = await import("../tools/rm.ts"); const result = await restore.execute( { trashPath: ".trash/link..123.symlink" }, ctx, ); expect(result).toContain("Restored:"); expect(await isSymlink(path.join(TEST_DIR, "link"))).toBe(true); }); test("throws when restore appears to succeed but destination does not exist", async () => { // Simulate: cp succeeds but safeStat still returns exists:false (edge case) mock.module("node:fs/promises", () => makeMock({ lstat: mock(async (p: string) => { if (p.includes(".trash")) { // Trash item exists return { isDirectory: () => false, isSymbolicLink: () => false }; } // Destination doesn't exist (simulates weird edge case) const err = new Error("ENOENT") as NodeJS.ErrnoException; err.code = "ENOENT"; throw err; }), readFile: mock(async () => "content"), })); const { restore } = await import("../tools/rm.ts"); await expect( restore.execute( { trashPath: ".trash/file..123" }, { directory: "/a" } as any, ), ).rejects.toThrow("Restore failed: destination not created"); }); test("restores directory to different location", async () => { vol.mkdirSync(path.join(TEST_DIR, "source", "sub"), { recursive: true }); vol.writeFileSync( path.join(TEST_DIR, "source", "sub", "file.txt"), "content", ); vol.mkdirSync(path.join(TEST_DIR, "target"), { recursive: true }); const { directory: dirTool, restore } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "source" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); vol.rmSync(path.join(TEST_DIR, "source"), { recursive: true, force: true }); await restore.execute( { trashPath: backupPath }, ctx, ); expect( vol.existsSync(path.join(TEST_DIR, "source", "sub", "file.txt")), ).toBe(true); }); test("handles restore with missing intermediate directories", async () => { vol.mkdirSync(path.join(TEST_DIR, "dir")); vol.writeFileSync(path.join(TEST_DIR, "dir", "file.txt"), "content"); const { directory: dirTool, restore } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "dir" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); vol.rmSync(path.join(TEST_DIR, "dir"), { recursive: true, force: true }); vol.rmSync(path.join(TEST_DIR, "target"), { recursive: true, force: true }); await restore.execute( { trashPath: backupPath }, ctx, ); expect(vol.existsSync(path.join(TEST_DIR, "dir", "file.txt"))).toBe(true); }); test("restores multiple files from same directory", async () => { vol.mkdirSync(path.join(TEST_DIR, "files")); vol.writeFileSync(path.join(TEST_DIR, "files", "a.txt"), "a"); vol.writeFileSync(path.join(TEST_DIR, "files", "b.txt"), "b"); vol.writeFileSync(path.join(TEST_DIR, "files", "c.txt"), "c"); const { directory: dirTool, restore } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "files" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); await restore.execute( { trashPath: backupPath }, ctx, ); expect( vol.readFileSync(path.join(TEST_DIR, "files", "a.txt"), "utf-8"), ).toBe("a"); expect( vol.readFileSync(path.join(TEST_DIR, "files", "b.txt"), "utf-8"), ).toBe("b"); expect( vol.readFileSync(path.join(TEST_DIR, "files", "c.txt"), "utf-8"), ).toBe("c"); }); test("blocks restore when decoded original path escapes working directory", async () => { // Craft a .trash entry whose decoded original path traverses outside the directory. // e.g. trash filename: "../../etc/passwd..1234567890000" relative to .trash // resolves to a path outside TEST_DIR const timestamp = Date.now() - 1000; const maliciousRelative = `../../etc/passwd..${timestamp}`; const trashDir = path.join(TEST_DIR, ".trash"); vol.mkdirSync(trashDir, { recursive: true }); // Place the file at a path that won't itself escape (it's inside .trash) vol.writeFileSync(path.join(trashDir, `passwd..${timestamp}`), "evil"); const { restore } = await import("../tools/rm.ts"); // The trashPath argument resolves inside TEST_DIR/.trash but the original // decoded path (../../etc/passwd) would escape TEST_DIR await expect( restore.execute( { trashPath: `.trash/../../etc/passwd..${timestamp}` }, ctx, ), ).rejects.toThrow("path escapes working directory"); }); test("restores symlink with relative target path (no validation on target)", async () => { // This test documents current behavior: restore does NOT validate that // the symlink target path is safe. A malicious .symlink file could contain // "../../etc/passwd" and restore would create a symlink pointing outside. // The code only validates the decoded original path, not the symlink target. const timestamp = Date.now() - 1000; const trashDir = path.join(TEST_DIR, ".trash"); vol.mkdirSync(trashDir, { recursive: true }); // Symlink target that goes outside the directory vol.writeFileSync( path.join(trashDir, `malicious..${timestamp}.symlink`), "../../etc/passwd", ); const { restore, isSymlink } = await import("../tools/rm.ts"); // Currently this succeeds (no validation on symlink target) const result = await restore.execute( { trashPath: `.trash/malicious..${timestamp}.symlink` }, ctx, ); expect(result).toContain("Restored:"); // The symlink is created pointing to "../../etc/passwd" expect(await isSymlink(path.join(TEST_DIR, "malicious"))).toBe(true); }); test("cleans up .symlink backup file after restoring symlink", async () => { // Create a symlink, move to trash (produces link..ts.symlink), restore it vol.writeFileSync(path.join(TEST_DIR, "target.txt"), "content"); vol.symlinkSync("target.txt", path.join(TEST_DIR, "link")); const { file, restore, safeStat } = await import("../tools/rm.ts"); // moveToTrash for symlink returns the .symlink path const rmResult = await file.execute( { filePath: "link" }, ctx, ); const symlinkBackupPath = rmResult.split("Backup: ")[1]!.trim(); expect(symlinkBackupPath).toMatch(/\.symlink$/); await restore.execute( { trashPath: symlinkBackupPath }, ctx, ); // The .symlink backup file should be cleaned up after restore const backupStillExists = await safeStat(symlinkBackupPath); expect(backupStillExists.exists).toBe(false); // The symlink should be restored const { isSymlink } = await import("../tools/rm.ts"); expect(await isSymlink(path.join(TEST_DIR, "link"))).toBe(true); }); test("succeeds and warns when trash cleanup rm fails", async () => { const warnSpy = mock(() => {}); // Track lstat calls per path to simulate: trash exists, dest appears after cp const lstatCallCount: Record = {}; mock.module("node:fs/promises", () => makeMock({ lstat: mock(async (p: string) => { lstatCallCount[p] = (lstatCallCount[p] ?? 0) + 1; if (p.includes(".trash")) { // trash item always exists return { isDirectory: () => false, isSymbolicLink: () => false }; } // destination: first call (pre-cp check) → ENOENT, second call (post-cp verify) → exists if ((lstatCallCount[p] ?? 0) >= 2) { return { isDirectory: () => false, isSymbolicLink: () => false }; } const err = new Error("ENOENT") as NodeJS.ErrnoException; err.code = "ENOENT"; throw err; }), rm: mock(async () => { throw new Error("rm cleanup failed"); }), readFile: mock(async () => "content"), })); const originalWarn = console.warn; console.warn = warnSpy; try { const { restore } = await import("../tools/rm.ts"); const result = await restore.execute( { trashPath: ".trash/file..123456789000" }, { directory: "/a" } as any, ); expect(result).toContain("Restored:"); expect(warnSpy).toHaveBeenCalledWith( expect.stringContaining("Failed to clean up trash"), ); } finally { console.warn = originalWarn; } }); test("throws on whitespace-only trashPath", async () => { const { restore } = await import("../tools/rm.ts"); await expect( restore.execute({ trashPath: " " }, ctx), ).rejects.toThrow("cannot be empty"); }); // Additional restore tests test("returns relative path in success message for subdirectory file", async () => { vol.mkdirSync(path.join(TEST_DIR, "subdir")); vol.writeFileSync(path.join(TEST_DIR, "subdir", "file.txt"), "content"); const { file, restore } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "subdir/file.txt" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); const restoreResult = await restore.execute( { trashPath: backupPath }, ctx, ); // Should return relative path, not absolute expect(restoreResult).toBe("Restored: subdir/file.txt"); expect(restoreResult).not.toMatch(/^\/test\//); }); test("handles multiple sequential trash and restore operations", async () => { const { file, restore } = await import("../tools/rm.ts"); // File A: trash and restore vol.writeFileSync(path.join(TEST_DIR, "fileA.txt"), "contentA"); const resultA = await file.execute( { filePath: "fileA.txt" }, ctx, ); const backupPathA = resultA.split("Backup: ")[1]!.trim(); await restore.execute({ trashPath: backupPathA }, ctx); expect(vol.readFileSync(path.join(TEST_DIR, "fileA.txt"), "utf-8")).toBe( "contentA", ); // File B: trash and restore vol.writeFileSync(path.join(TEST_DIR, "fileB.txt"), "contentB"); const resultB = await file.execute( { filePath: "fileB.txt" }, ctx, ); const backupPathB = resultB.split("Backup: ")[1]!.trim(); await restore.execute({ trashPath: backupPathB }, ctx); expect(vol.readFileSync(path.join(TEST_DIR, "fileB.txt"), "utf-8")).toBe( "contentB", ); }); test("restore recreates parent directories when they are missing", async () => { // Create and trash a directory vol.mkdirSync(path.join(TEST_DIR, "mylib")); vol.writeFileSync( path.join(TEST_DIR, "mylib", "utils.ts"), "export const utils = {}", ); const { directory: dirTool, restore } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "mylib" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); // Delete the directory completely vol.rmSync(path.join(TEST_DIR, "mylib"), { recursive: true, force: true }); await restore.execute({ trashPath: backupPath }, ctx); // Directory should be recreated expect(vol.existsSync(path.join(TEST_DIR, "mylib", "utils.ts"))).toBe(true); expect( vol.readFileSync(path.join(TEST_DIR, "mylib", "utils.ts"), "utf-8"), ).toBe("export const utils = {}"); }); test("handles trashPath with leading/trailing spaces", async () => { vol.writeFileSync(path.join(TEST_DIR, "spaced.txt"), "content"); const { file, restore } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "spaced.txt" }, ctx, ); // Get the backup path but wrap with spaces const backupPath = result.split("Backup: ")[1]!.trim(); const spacedPath = " " + backupPath + " "; const restoreResult = await restore.execute( { trashPath: spacedPath }, ctx, ); expect(restoreResult).toContain("Restored:"); expect(vol.existsSync(path.join(TEST_DIR, "spaced.txt"))).toBe(true); }); test("error message for destination already exists includes original file path", async () => { vol.writeFileSync(path.join(TEST_DIR, "exists.txt"), "original"); const { file, restore } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "exists.txt" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); // Create the file again vol.writeFileSync(path.join(TEST_DIR, "exists.txt"), "existing"); await expect( restore.execute( { trashPath: backupPath }, ctx, ), ).rejects.toThrow("exists.txt"); }); test("error message for trash item not found includes the trash arg", async () => { const { restore } = await import("../tools/rm.ts"); await expect( restore.execute( { trashPath: ".trash/missing..123456789" }, ctx, ), ).rejects.toThrow(".trash/missing..123456789"); }); }); describe("path security edge cases", () => { test("blocks symlink escape attempt", async () => { // Removing a symlink pointing outside the directory is safe: // it removes the symlink itself (within the directory), not the target. vol.mkdirSync(path.join(TEST_DIR, "trick"), { recursive: true }); vol.symlinkSync("/etc", path.join(TEST_DIR, "trick", "passwd")); const { file, safeStat } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "trick/passwd" }, ctx, ); expect(result).toContain("Removed: trick/passwd"); const exists = await safeStat(path.join(TEST_DIR, "trick", "passwd")); expect(exists.exists).toBe(false); }); test("blocks encoded path traversal", async () => { const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "../etc/passwd" }, ctx), ).rejects.toThrow("path escapes working directory"); }); test("blocks absolute path escape", async () => { const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "/etc/passwd" }, ctx), ).rejects.toThrow("path escapes working directory"); }); test("blocks path with null bytes", async () => { const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "file.txt\0" }, ctx), ).rejects.toThrow(); }); test("error message includes file path when moveToTrash fails", async () => { // When cp fails, the error message should about include context which file failed mock.module("node:fs/promises", () => makeMock({ cp: mock(async () => { throw new Error("Input/output error"); }), })); const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "myfile.txt" }, { directory: "/test" } as any), ).rejects.toThrow("Input/output error"); }); }); describe("unicode and special characters", () => { test("handles special characters in filename", async () => { vol.writeFileSync(path.join(TEST_DIR, "file-name_v1.0.txt"), "content"); const { file } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "file-name_v1.0.txt" }, ctx, ); expect(result).toContain("Removed: file-name_v1.0.txt"); }); test("handles russian characters", async () => { vol.writeFileSync(path.join(TEST_DIR, "файл.txt"), "content"); const { file, restore } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "файл.txt" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); await restore.execute( { trashPath: backupPath }, ctx, ); expect(vol.existsSync(path.join(TEST_DIR, "файл.txt"))).toBe(true); }); test("handles emoji in filename", async () => { vol.writeFileSync(path.join(TEST_DIR, "🎉.txt"), "content"); const { file } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "🎉.txt" }, ctx, ); expect(result).toContain("Removed: 🎉.txt"); }); test("handles arabic characters", async () => { vol.writeFileSync(path.join(TEST_DIR, "ملف.txt"), "محتوى"); const { file, restore } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "ملف.txt" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); await restore.execute( { trashPath: backupPath }, ctx, ); expect(vol.readFileSync(path.join(TEST_DIR, "ملف.txt"), "utf-8")).toBe( "محتوى", ); }); test("handles spaces in path", async () => { vol.mkdirSync(path.join(TEST_DIR, "my documents")); vol.writeFileSync( path.join(TEST_DIR, "my documents", "file.txt"), "content", ); const { directory: dirTool, safeStat } = await import("../tools/rm.ts"); await dirTool.execute( { directory: "my documents" }, ctx, ); const exists = await safeStat(path.join(TEST_DIR, "my documents")); expect(exists.exists).toBe(false); }); }); describe("timestamp edge cases", () => { test("generates unique timestamps for same file", async () => { const { getTrashPath } = await import("../tools/rm.ts"); const path1 = getTrashPath("/a/file.txt", "/a"); await new Promise((r) => setTimeout(r, 10)); const path2 = getTrashPath("/a/file.txt", "/a"); expect(path1).not.toBe(path2); }); test("extractTimestamp handles edge cases", async () => { const { extractTimestamp } = await import("../tools/rm.ts"); expect(extractTimestamp("..123")).toBeNull(); expect(extractTimestamp("file..")).toBeNull(); expect(extractTimestamp("file..abc")).toBeNull(); expect(extractTimestamp("..")).toBeNull(); expect(extractTimestamp(".")).toBeNull(); expect(extractTimestamp("")).toBeNull(); }); test("extractTimestamp with zero timestamp returns valid result", async () => { // timestamp = 0 passes parseInt (returns 0, not NaN), passes future check // because 0 <= now + 60000, and path replacement works const { extractTimestamp } = await import("../tools/rm.ts"); const result = extractTimestamp("file..0"); expect(result).not.toBeNull(); expect(result?.path).toBe("file"); expect(result?.timestamp).toBe(0); }); test("extractTimestamp zero is accepted despite being very old", async () => { // A timestamp of 0 is technically very old (1970) but within acceptable range const { extractTimestamp } = await import("../tools/rm.ts"); const result = extractTimestamp("test..0"); // The code only rejects timestamps > now + 60000 (future), not old timestamps expect(result).not.toBeNull(); }); test("extractTimestamp with very large number returns null (overflow)", async () => { // Very large numbers might cause issues - test that they're handled const { extractTimestamp } = await import("../tools/rm.ts"); // Number larger than Number.MAX_SAFE_INTEGER const hugeNumber = "9999999999999999999"; const result = extractTimestamp(`file..${hugeNumber}`); // parseInt of huge number might produce NaN or overflow expect(result).toBeNull(); }); }); describe("error recovery", () => { test("handles cp failure gracefully", async () => { mock.module("node:fs/promises", () => { return { lstat: async (p: string) => vol.lstatSync(p), mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts), cp: async () => { throw new Error("cp failed"); }, rm: async (p: string, opts?: any) => vol.rmSync(p, opts), symlink: async (target: string, p: string) => vol.symlinkSync(target, p), readlink: async (p: string) => vol.readlinkSync(p), readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts), writeFile: async (p: string, data: any) => vol.writeFileSync(p, data), readdir: async (p: string) => vol.readdirSync(p), stat: async (p: string) => vol.statSync(p), open: async () => ({ close: async () => {} }), }; }); vol.writeFileSync(path.join(TEST_DIR, "file.txt"), "content"); const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "file.txt" }, ctx), ).rejects.toThrow(); }); test("handles file deleted between stat and move (race condition)", async () => { // Simulate race condition: file exists when stat'd but deleted before cp let statCalled = false; mock.module("node:fs/promises", () => makeMock({ lstat: mock(async (p: string) => { // First call (in removeItem) - file exists statCalled = true; return { isDirectory: () => false, isSymbolicLink: () => false }; }), cp: mock(async () => { // Second call (in moveToTrash) - file no longer exists const err = new Error( "ENOENT: no such file or directory", ) as NodeJS.ErrnoException; err.code = "ENOENT"; throw err; }), })); const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "race.txt" }, { directory: "/a" } as any), ).rejects.toThrow("no such file or directory"); }); test("handles rm failing after successful cp (cleanup on failure)", async () => { // cp succeeds but rm fails - should clean up the backup and propagate error mock.module("node:fs/promises", () => makeMock({ rm: mock(async () => { throw new Error("EBUSY: resource busy or locked"); }), })); const { moveToTrash } = await import("../tools/rm.ts"); await expect(moveToTrash("/a/file.txt", "/a", false)).rejects.toThrow( "resource busy or locked", ); }); }); describe("full E2E symlink flow", () => { test("file tool removes symlink and restore recreates it", async () => { vol.writeFileSync(path.join(TEST_DIR, "real.txt"), "real content"); vol.symlinkSync("real.txt", path.join(TEST_DIR, "mylink")); const { file, restore, isSymlink, safeStat } = await import( "../tools/rm.ts" ); // Remove the symlink via file tool const rmResult = await file.execute( { filePath: "mylink" }, ctx, ); expect(rmResult).toContain("Removed: mylink"); expect(await safeStat(path.join(TEST_DIR, "mylink"))).toMatchObject({ exists: false, }); const backupPath = rmResult.split("Backup: ")[1]!.trim(); expect(backupPath).toMatch(/\.symlink$/); // Restore the symlink const restoreResult = await restore.execute( { trashPath: backupPath }, ctx, ); expect(restoreResult).toContain("Restored: mylink"); expect(await isSymlink(path.join(TEST_DIR, "mylink"))).toBe(true); // Original file is untouched expect(vol.readFileSync(path.join(TEST_DIR, "real.txt"), "utf-8")).toBe( "real content", ); }); }); describe("file tool on symlink to directory", () => { test("removes symlink to directory and creates .symlink backup with dir path", async () => { vol.mkdirSync(path.join(TEST_DIR, "targetdir")); vol.writeFileSync(path.join(TEST_DIR, "targetdir", "file.txt"), "content"); vol.symlinkSync( path.join(TEST_DIR, "targetdir"), path.join(TEST_DIR, "linktodir"), ); const { file, safeStat, restore, isSymlink } = await import( "../tools/rm.ts" ); const result = await file.execute( { filePath: "linktodir" }, ctx, ); expect(result).toContain("Removed: linktodir"); // Symlink should be removed const symlinkExists = await safeStat(path.join(TEST_DIR, "linktodir")); expect(symlinkExists.exists).toBe(false); // Should have created a .symlink backup file const backupPath = result.split("Backup: ")[1]!.trim(); expect(backupPath).toMatch(/\.symlink$/); const backupContent = vol.readFileSync(backupPath, "utf-8"); expect(backupContent).toBe(path.join(TEST_DIR, "targetdir")); // Restore should recreate the symlink await restore.execute( { trashPath: backupPath }, ctx, ); expect(await isSymlink(path.join(TEST_DIR, "linktodir"))).toBe(true); }); }); describe("broken symlink handling", () => { test("file tool removes broken symlink and backs up target path as string", async () => { vol.symlinkSync( path.join(TEST_DIR, "nonexistent"), path.join(TEST_DIR, "broken"), ); const { file, safeStat } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "broken" }, ctx, ); expect(result).toContain("Removed: broken"); // Symlink should be removed const exists = await safeStat(path.join(TEST_DIR, "broken")); expect(exists.exists).toBe(false); // Backup should contain the target path as string const backupPath = result.split("Backup: ")[1]!.trim(); expect(backupPath).toMatch(/\.symlink$/); const backupContent = vol.readFileSync(backupPath, "utf-8"); expect(backupContent).toBe(path.join(TEST_DIR, "nonexistent")); }); }); describe("permission error propagation", () => { test("propagates permission error from cp", async () => { mock.module("node:fs/promises", () => { return { lstat: async (p: string) => vol.lstatSync(p), mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts), cp: mock(async () => { const err = new Error( "EACCES: permission denied", ) as NodeJS.ErrnoException; err.code = "EACCES"; throw err; }), rm: async (p: string, opts?: any) => vol.rmSync(p, opts), symlink: async (target: string, p: string) => vol.symlinkSync(target, p), readlink: async (p: string) => vol.readlinkSync(p), readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts), writeFile: async (p: string, data: any) => vol.writeFileSync(p, data), readdir: async (p: string) => vol.readdirSync(p), stat: async (p: string) => vol.statSync(p), open: async () => ({ close: async () => {} }), }; }); vol.writeFileSync(path.join(TEST_DIR, "file.txt"), "content"); const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "file.txt" }, ctx), ).rejects.toThrow("permission denied"); }); test("propagates permission error from rm", async () => { mock.module("node:fs/promises", () => { return { lstat: async (p: string) => vol.lstatSync(p), mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts), cp: async (src: string, dest: string, opts?: any) => vol.cpSync(src, dest, opts), rm: mock(async () => { const err = new Error( "EACCES: permission denied", ) as NodeJS.ErrnoException; err.code = "EACCES"; throw err; }), symlink: async (target: string, p: string) => vol.symlinkSync(target, p), readlink: async (p: string) => vol.readlinkSync(p), readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts), writeFile: async (p: string, data: any) => vol.writeFileSync(p, data), readdir: async (p: string) => vol.readdirSync(p), stat: async (p: string) => vol.statSync(p), open: async () => ({ close: async () => {} }), }; }); vol.writeFileSync(path.join(TEST_DIR, "file.txt"), "content"); const { file } = await import("../tools/rm.ts"); await expect( file.execute({ filePath: "file.txt" }, ctx), ).rejects.toThrow("permission denied"); }); }); describe("path length edge cases", () => { test("handles very long filename", async () => { const longName = "a".repeat(255) + ".txt"; vol.writeFileSync(path.join(TEST_DIR, longName), "content"); const { file, safeStat } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: longName }, ctx, ); expect(result).toContain(`Removed: ${longName}`); const exists = await safeStat(path.join(TEST_DIR, longName)); expect(exists.exists).toBe(false); }); }); describe("invariants and properties", () => { test("round-trip: trashed file has byte-for-byte identical content after restore", async () => { const originalContent = "Hello, World! This is a test file.\nWith multiple lines.\nSpecial chars: émoji 🎉"; vol.writeFileSync(path.join(TEST_DIR, "roundtrip.txt"), originalContent); const { file, restore } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "roundtrip.txt" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); await restore.execute({ trashPath: backupPath }, ctx); const restoredContent = vol.readFileSync( path.join(TEST_DIR, "roundtrip.txt"), "utf-8", ); expect(restoredContent).toBe(originalContent); }); test("round-trip: all files in directory are preserved after trash+restore cycle", async () => { vol.mkdirSync(path.join(TEST_DIR, "roundtrip-dir")); vol.writeFileSync( path.join(TEST_DIR, "roundtrip-dir", "a.txt"), "content a", ); vol.writeFileSync( path.join(TEST_DIR, "roundtrip-dir", "b.txt"), "content b", ); vol.writeFileSync( path.join(TEST_DIR, "roundtrip-dir", "c.txt"), "content c", ); vol.mkdirSync(path.join(TEST_DIR, "roundtrip-dir", "subdir")); vol.writeFileSync( path.join(TEST_DIR, "roundtrip-dir", "subdir", "nested.txt"), "nested content", ); const { directory: dirTool, restore } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "roundtrip-dir" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); await restore.execute({ trashPath: backupPath }, ctx); // All files should be restored with correct content expect( vol.readFileSync(path.join(TEST_DIR, "roundtrip-dir", "a.txt"), "utf-8"), ).toBe("content a"); expect( vol.readFileSync(path.join(TEST_DIR, "roundtrip-dir", "b.txt"), "utf-8"), ).toBe("content b"); expect( vol.readFileSync(path.join(TEST_DIR, "roundtrip-dir", "c.txt"), "utf-8"), ).toBe("content c"); expect( vol.readFileSync( path.join(TEST_DIR, "roundtrip-dir", "subdir", "nested.txt"), "utf-8", ), ).toBe("nested content"); }); test("backup path returned by file.execute always contains project directory path as prefix", async () => { vol.writeFileSync(path.join(TEST_DIR, "file.txt"), "content"); const { file } = await import("../tools/rm.ts"); const result = await file.execute( { filePath: "file.txt" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); expect(backupPath.startsWith(TEST_DIR)).toBe(true); }); test("backup path returned by directory.execute always contains project directory path as prefix", async () => { vol.mkdirSync(path.join(TEST_DIR, "dir")); vol.writeFileSync(path.join(TEST_DIR, "dir", "file.txt"), "content"); const { directory: dirTool } = await import("../tools/rm.ts"); const result = await dirTool.execute( { directory: "dir" }, ctx, ); const backupPath = result.split("Backup: ")[1]!.trim(); expect(backupPath.startsWith(TEST_DIR)).toBe(true); }); }); describe("history", () => { test("Empty trash (no .trash dir) - returns 'Trash is empty.'", async () => { // Ensure .trash doesn't exist vol.rmSync(path.join(TEST_DIR, ".trash"), { recursive: true, force: true }); const { history } = await import("../tools/rm.ts"); const result = await history.execute({}, ctx); expect(result).toBe("Trash is empty."); }); test("Empty trash (.trash dir exists but has no valid entries)", async () => { // Create .trash directory but no valid entries vol.mkdirSync(path.join(TEST_DIR, ".trash"), { recursive: true }); const { history } = await import("../tools/rm.ts"); const result = await history.execute({}, ctx); expect(result).toBe("Trash is empty."); }); test("Single file in trash - shows filename, (file), deleted:, restore:", async () => { // Trash a file first vol.writeFileSync(path.join(TEST_DIR, "test.txt"), "content"); const { file, history } = await import("../tools/rm.ts"); const trashResult = await file.execute( { filePath: "test.txt" }, ctx, ); const backupPath = trashResult.split("Backup: ")[1]!.trim(); const result = await history.execute({}, ctx); expect(result).toContain("test.txt"); expect(result).toContain("(file)"); expect(result).toContain("deleted:"); expect(result).toContain("restore:"); // The restore path is relative to .trash/ directory expect(result).toContain("test.txt.."); }); test("Single directory in trash - shows (directory)", async () => { vol.mkdirSync(path.join(TEST_DIR, "mydir")); vol.writeFileSync(path.join(TEST_DIR, "mydir", "file.txt"), "content"); const { directory: dirTool, history } = await import("../tools/rm.ts"); await dirTool.execute({ directory: "mydir" }, ctx); const result = await history.execute({}, ctx); expect(result).toContain("mydir"); expect(result).toContain("(directory)"); }); test("Single symlink in trash - shows (symlink) and ends with .symlink", async () => { vol.writeFileSync(path.join(TEST_DIR, "target.txt"), "target"); vol.symlinkSync("target.txt", path.join(TEST_DIR, "link")); const { file, history } = await import("../tools/rm.ts"); await file.execute({ filePath: "link" }, ctx); const result = await history.execute({}, ctx); expect(result).toContain("(symlink)"); expect(result).toContain(".symlink"); }); test("Multiple entries sorted newest first", async () => { // Trash two files with a delay to ensure different timestamps vol.writeFileSync(path.join(TEST_DIR, "older.txt"), "older"); vol.writeFileSync(path.join(TEST_DIR, "newer.txt"), "newer"); const { file, history } = await import("../tools/rm.ts"); // Trash older first await file.execute({ filePath: "older.txt" }, ctx); // Small delay to ensure different timestamps await new Promise((r) => setTimeout(r, 10)); // Trash newer await file.execute({ filePath: "newer.txt" }, ctx); const result = await history.execute({}, ctx); // Newer should appear as [1] const newerIndex = result.indexOf("newer.txt"); const olderIndex = result.indexOf("older.txt"); expect(newerIndex).toBeLessThan(olderIndex); }); test("Count in header - starts with 'N item(s) in trash:'", async () => { vol.writeFileSync(path.join(TEST_DIR, "a.txt"), "a"); vol.writeFileSync(path.join(TEST_DIR, "b.txt"), "b"); const { file, history } = await import("../tools/rm.ts"); await file.execute({ filePath: "a.txt" }, ctx); await file.execute({ filePath: "b.txt" }, ctx); const result = await history.execute({}, ctx); expect(result).toMatch(/^2 item\(s\) in trash:/); }); test("Restore path is relative - does not start with /", async () => { vol.writeFileSync(path.join(TEST_DIR, "file.txt"), "content"); const { file, history } = await import("../tools/rm.ts"); await file.execute({ filePath: "file.txt" }, ctx); const result = await history.execute({}, ctx); // The restore path should be relative to .trash/, not absolute expect(result).toMatch(/restore: [^/]/); }); test("Content inside directory backup is NOT listed as separate entry", async () => { // Create a directory with files inside vol.mkdirSync(path.join(TEST_DIR, "parent")); vol.writeFileSync(path.join(TEST_DIR, "parent", "child1.txt"), "c1"); vol.writeFileSync(path.join(TEST_DIR, "parent", "child2.txt"), "c2"); const { directory: dirTool, history } = await import("../tools/rm.ts"); // Trash the directory await dirTool.execute({ directory: "parent" }, ctx); const result = await history.execute({}, ctx); // Should only show 1 entry (the directory), not 3 expect(result).toMatch(/^1 item\(s\) in trash:/); expect(result).toContain("parent"); expect(result).not.toContain("child1.txt"); expect(result).not.toContain("child2.txt"); }); test("File in a subdirectory - shows full path in name and restore path", async () => { vol.mkdirSync(path.join(TEST_DIR, "subdir")); vol.writeFileSync(path.join(TEST_DIR, "subdir", "file.txt"), "content"); const { file, history } = await import("../tools/rm.ts"); await file.execute( { filePath: "subdir/file.txt" }, ctx, ); const result = await history.execute({}, ctx); expect(result).toContain("file.txt"); expect(result).toContain("restore:"); expect(result).toContain("subdir/file.txt.."); }); test("After restore, entry disappears from history", async () => { vol.writeFileSync(path.join(TEST_DIR, "temp.txt"), "content"); const { file, history, restore } = await import("../tools/rm.ts"); // Trash the file const trashResult = await file.execute( { filePath: "temp.txt" }, ctx, ); const backupPath = trashResult.split("Backup: ")[1]!.trim(); // Verify it's in history let result = await history.execute({}, ctx); expect(result).toContain("temp.txt"); // Restore it await restore.execute({ trashPath: backupPath }, ctx); // Verify it's no longer in history result = await history.execute({}, ctx); expect(result).toBe("Trash is empty."); }); test("formatTimestamp produces expected YYYY-MM-DD HH:MM:SS format", async () => { // Use extractTimestamp and formatTimestamp to test const { extractTimestamp, history } = await import("../tools/rm.ts"); // Create a file with known timestamp const knownTimestamp = 1741614721000; // A specific timestamp const trashDir = path.join(TEST_DIR, ".trash"); vol.mkdirSync(trashDir, { recursive: true }); vol.writeFileSync( path.join(trashDir, `file.txt..${knownTimestamp}`), "content", ); const result = await history.execute({}, ctx); // Should match YYYY-MM-DD HH:MM:SS pattern expect(result).toMatch(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/); }); test("Invalid entries in .trash are ignored", async () => { // Place a file without valid timestamp pattern in .trash vol.mkdirSync(path.join(TEST_DIR, ".trash"), { recursive: true }); vol.writeFileSync(path.join(TEST_DIR, ".trash", "somefile"), "invalid"); const { history } = await import("../tools/rm.ts"); const result = await history.execute({}, ctx); expect(result).toBe("Trash is empty."); }); test("Mixed valid and invalid entries - only valid one appears", async () => { vol.mkdirSync(path.join(TEST_DIR, ".trash"), { recursive: true }); // Valid entry const timestamp = Date.now() - 1000; vol.writeFileSync( path.join(TEST_DIR, ".trash", `valid.txt..${timestamp}`), "valid", ); // Invalid entry vol.writeFileSync(path.join(TEST_DIR, ".trash", "invalid"), "invalid"); const { history } = await import("../tools/rm.ts"); const result = await history.execute({}, ctx); expect(result).toContain("valid.txt"); expect(result).not.toContain("invalid"); expect(result).toMatch(/^1 item\(s\) in trash:/); }); test("readdir error is propagated", async () => { mock.module("node:fs/promises", () => makeMock({ readdir: mock(async () => { throw new Error("EACCES: permission denied"); }), })); const { history } = await import("../tools/rm.ts"); await expect(history.execute({}, { directory: "/test" } as any)).rejects .toThrow( "permission denied", ); }); test("Multiple files at root and nested levels are listed correctly", async () => { vol.mkdirSync(path.join(TEST_DIR, ".trash"), { recursive: true }); const now = Date.now(); // Root level file vol.writeFileSync( path.join(TEST_DIR, ".trash", `root.txt..${now - 2000}`), "root", ); // Nested file (not inside a trashed directory) vol.mkdirSync(path.join(TEST_DIR, ".trash", "nested")); vol.writeFileSync( path.join(TEST_DIR, ".trash", `nested/nested.txt..${now - 1000}`), "nested", ); const { history } = await import("../tools/rm.ts"); const result = await history.execute({}, ctx); expect(result).toContain("root.txt"); expect(result).toContain("nested/nested.txt"); }); test("History output format has proper indentation and spacing", async () => { vol.writeFileSync(path.join(TEST_DIR, "format.txt"), "content"); const { file, history } = await import("../tools/rm.ts"); await file.execute({ filePath: "format.txt" }, ctx); const result = await history.execute({}, ctx); // Check formatting const lines = result.split("\n"); expect(lines[0]).toMatch(/^\d item\(s\) in trash:$/); expect(lines[1]).toBe(""); expect(lines[2]).toMatch(/^\s+\[\d\]/); expect(lines[3]).toMatch(/^\s+deleted:/); expect(lines[4]).toMatch(/^\s+restore:/); }); test("Files with special characters in name are displayed correctly", async () => { vol.writeFileSync(path.join(TEST_DIR, "file-name_v1.0.txt"), "content"); vol.writeFileSync(path.join(TEST_DIR, "file.name.txt"), "content"); const { file, history } = await import("../tools/rm.ts"); await file.execute( { filePath: "file-name_v1.0.txt" }, ctx, ); await file.execute({ filePath: "file.name.txt" }, ctx); const result = await history.execute({}, ctx); expect(result).toContain("file-name_v1.0.txt"); expect(result).toContain("file.name.txt"); }); test("Directory trashed multiple times shows all entries", async () => { vol.mkdirSync(path.join(TEST_DIR, "dir1")); vol.mkdirSync(path.join(TEST_DIR, "dir2")); const { directory: dirTool, history } = await import("../tools/rm.ts"); await dirTool.execute({ directory: "dir1" }, ctx); await dirTool.execute({ directory: "dir2" }, ctx); const result = await history.execute({}, ctx); expect(result).toMatch(/^2 item\(s\) in trash:/); expect(result).toContain("dir1"); expect(result).toContain("dir2"); }); test("When parent and child are independently trashed, only parent appears in history", async () => { // This tests the ancestor-based filtering fix // When "dir" is trashed to .trash/dir..timestamp1 and then "dir/file.txt" is trashed // to .trash/dir/file.txt..timestamp2, the history should only show "dir" // (not both "dir" and "dir/file.txt" as separate entries) vol.mkdirSync(path.join(TEST_DIR, ".trash"), { recursive: true }); const now = Date.now(); // Create two independently trashed entries where one path is ancestor of the other // First: directory "dir" was trashed vol.mkdirSync(path.join(TEST_DIR, ".trash", `dir..${now - 1000}`)); // Second: file "dir/file.txt" was trashed (this is the bug scenario) vol.mkdirSync( path.join(TEST_DIR, ".trash", `dir..${now - 1000}`, "subdir"), { recursive: true }, ); vol.writeFileSync( path.join(TEST_DIR, ".trash", `dir..${now - 1000}`, "subdir", "file.txt"), "content", ); // Also add a separate trashed file that should appear (not an ancestor of anything) vol.writeFileSync( path.join(TEST_DIR, ".trash", `other.txt..${now - 2000}`), "other", ); const { history } = await import("../tools/rm.ts"); const result = await history.execute({}, ctx); // Should show 2 items: "dir" and "other.txt" // "dir/file.txt" should NOT appear as a separate entry because "dir" is its ancestor expect(result).toMatch(/^2 item\(s\) in trash:/); expect(result).toContain("dir"); expect(result).toContain("other.txt"); // The file inside the trashed directory should NOT be listed separately expect(result).not.toContain("file.txt"); expect(result).not.toContain("subdir"); }); test("Deeply nested independent trashed paths - only root ancestor shown", async () => { // Test multiple levels of independently trashed nested paths vol.mkdirSync(path.join(TEST_DIR, ".trash"), { recursive: true }); const now = Date.now(); // a, a/b, a/b/c all trashed independently vol.mkdirSync(path.join(TEST_DIR, ".trash", `a..${now - 3000}`)); vol.mkdirSync(path.join(TEST_DIR, ".trash", `a..${now - 3000}`, "b")); vol.writeFileSync( path.join(TEST_DIR, ".trash", `a..${now - 3000}`, "b", "file.txt"), "content", ); const { history } = await import("../tools/rm.ts"); const result = await history.execute({}, ctx); // Only "a" should appear (the root ancestor) expect(result).toMatch(/^1 item\(s\) in trash:/); expect(result).toContain("a"); expect(result).not.toContain("b"); expect(result).not.toContain("file.txt"); }); test("Sibling independent trashed paths - both shown", async () => { // Test that sibling paths (not ancestors) are both shown vol.mkdirSync(path.join(TEST_DIR, ".trash"), { recursive: true }); const now = Date.now(); // dir1 and dir2 are siblings (neither is ancestor of other) vol.mkdirSync(path.join(TEST_DIR, ".trash", `dir1..${now - 1000}`)); vol.mkdirSync(path.join(TEST_DIR, ".trash", `dir2..${now - 2000}`)); const { history } = await import("../tools/rm.ts"); const result = await history.execute({}, ctx); expect(result).toMatch(/^2 item\(s\) in trash:/); expect(result).toContain("dir1"); expect(result).toContain("dir2"); }); });