SPB Git

Repository Public License

FilesystemToolsTests.swift 21.2 KB 322 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX OS Automation9// File             : Packages/ORIXToolRegistry/Tests/ORIXToolRegistryTests/FilesystemToolsTests.swift10// Description      : Integration tests of every filesystem.* tool through the11//                    real executor, on real files in temp directories.12// Module           : ORIXToolRegistryTests13// Repository       : https://git.spboucher.ai/orix-automation14// Created          : 2026-11-2115// Last Modified    : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : Proprietary, all rights reserved (see license file)82// License File     : LICENSE83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import Testing92import ORIXCore93import ORIXTestingSupport94@testable import ORIXToolRegistry9596@Suite("filesystem.* tools (integration, real files)")97struct FilesystemToolsTests {98    @Test func listFlatRecursiveHiddenAndLimit() async throws {99        let h = try await Harness(); defer { h.tmp.remove() }100        try h.tmp.write("a.txt", "A"); try h.tmp.write("sub/b.txt", "BB"); try h.tmp.write("sub/deep/c.txt", "CCC"); try h.tmp.write(".hidden", "h")101        let flat = await h.call("filesystem.list", ["path": "."])102        let names = flat.output["entries"]?.arrayValue?.compactMap { $0["name"]?.stringValue } ?? []103        #expect(flat.status == .succeeded && names == ["a.txt", "sub"] && flat.untrusted)104        let recursive = await h.call("filesystem.list", ["path": ".", "recursive": true, "includeHidden": true])105        let all = Set(recursive.output["entries"]?.arrayValue?.compactMap { $0["name"]?.stringValue } ?? [])106        #expect(all == [".hidden", "a.txt", "sub", "sub/b.txt", "sub/deep", "sub/deep/c.txt"])107        let shallow = await h.call("filesystem.list", ["path": ".", "recursive": true, "maxDepth": 2])108        #expect(shallow.output["count"] == 4)109        let limited = await h.call("filesystem.list", ["path": ".", "recursive": true, "limit": 2])110        #expect(limited.output["count"] == 2 && limited.truncated && limited.output["truncated"] == true)111        let entry = flat.output["entries"]?[0]112        #expect(entry?["type"] == "file" && entry?["size"] == 1 && entry?["modified"]?.stringValue != nil)113        #expect(await h.call("filesystem.list", ["path": "missing"]).failure?.code == "not_found")114        #expect(await h.call("filesystem.list", ["path": "a.txt"]).status == .invalidInput)115    }116117    @Test func searchByNameAndContent() async throws {118        let h = try await Harness(); defer { h.tmp.remove() }119        try h.tmp.write("notes/todo.md", "buy milk\nCall Alice\n"); try h.tmp.write("notes/done.md", "paid rent\n")120        try h.tmp.write("report.PDF", "x"); try h.tmp.write("src/main.swift", "let total = 42\n// TODO: refactor\n")121        try Data([0, 1, 2, 0x54, 0x4f, 0x44, 0x4f]).write(to: h.tmp.file("blob.bin"))122        let byName = await h.call("filesystem.search", ["path": ".", "pattern": "*.md"])123        #expect(byName.output["count"] == 2)124        #expect(await h.call("filesystem.search", ["path": ".", "pattern": "*.pdf"]).output["count"] == 1)125        let content = await h.call("filesystem.search", ["path": ".", "content": "todo"])126        let hit = content.output["matches"]?[0]127        #expect(content.output["count"] == 1 && hit?["line"] == 2 && hit?["path"]?.stringValue?.hasSuffix("main.swift") == true, "binary files are skipped, names are not content")128        #expect(await h.call("filesystem.search", ["path": ".", "content": "todo", "caseSensitive": true]).output["count"] == 0)129        let regex = await h.call("filesystem.search", ["path": ".", "content": "^let \\w+ = \\d+$", "regex": true, "pattern": "*.swift"])130        #expect(regex.output["count"] == 1)131        let bounded = await h.call("filesystem.search", ["path": ".", "content": "a", "maxResults": 1])132        #expect(bounded.output["count"] == 1 && bounded.truncated)133        #expect(await h.call("filesystem.search", ["path": "."]).status == .invalidInput)134        #expect(await h.call("filesystem.search", ["path": ".", "content": "(", "regex": true]).status == .invalidInput)135    }136137    @Test func readTextWindowsAndBinary() async throws {138        let h = try await Harness(); defer { h.tmp.remove() }139        try h.tmp.write("t.txt", "héllo wörld — fin")140        let whole = await h.call("filesystem.read", ["path": "t.txt"])141        #expect(whole.output["content"] == "héllo wörld — fin" && whole.output["truncated"] == false && whole.untrusted)142        let head = await h.call("filesystem.read", ["path": "t.txt", "maxBytes": 2])143        #expect(head.output["content"] == "h" && head.truncated, "a cut inside é drops the partial character")144        let tail = await h.call("filesystem.read", ["path": "t.txt", "offset": 7, "maxBytes": 6])145        #expect(tail.output["content"] == "wörld")146        try Data([0xff, 0xfe, 0x00, 0x80, 0x01]).write(to: h.tmp.file("b.bin"))147        #expect(await h.call("filesystem.read", ["path": "b.bin"]).status == .unsupported)148        let b64 = await h.call("filesystem.read", ["path": "b.bin", "encoding": "base64"])149        #expect(b64.output["content"] == .string(Data([0xff, 0xfe, 0x00, 0x80, 0x01]).base64EncodedString()) && b64.output["bytesRead"] == 5)150        #expect(await h.call("filesystem.read", ["path": "nope.txt"]).failure?.code == "not_found")151    }152153    @Test func writeCreateOverwriteWithBackupAppendAndDryRun() async throws {154        let h = try await Harness(); defer { h.tmp.remove() }155        let created = await h.call("filesystem.write", ["path": "out/new.txt", "content": "v1"])156        #expect(created.status == .succeeded && created.output["created"] == true && h.read("out/new.txt") == "v1")157        let refused = await h.call("filesystem.write", ["path": "out/new.txt", "content": "v2"])158        #expect(refused.status == .invalidInput && h.read("out/new.txt") == "v1")159        let dry = await h.call("filesystem.write", ["path": "out/new.txt", "content": "v2", "overwrite": true], dryRun: true)160        #expect(dry.status == .simulated && dry.output["wouldBackup"] == true && h.read("out/new.txt") == "v1")161        let replaced = await h.call("filesystem.write", ["path": "out/new.txt", "content": "v2", "overwrite": true])162        let backup = try #require(replaced.output["backupPath"]?.stringValue)163        try #expect(h.read("out/new.txt") == "v2" && (try String(contentsOfFile: backup, encoding: .utf8)) == "v1")164        #expect(backup.hasPrefix(h.path("artifacts/backups/")) && replaced.artifacts.first?.path == backup)165        let appended = await h.call("filesystem.write", ["path": "out/new.txt", "content": "+3", "mode": "append"])166        #expect(appended.status == .succeeded && h.read("out/new.txt") == "v2+3" && appended.output["backupPath"]?.stringValue != nil)167        let binary = await h.call("filesystem.write", ["path": "b.bin", "content": .string(Data([1, 2, 3]).base64EncodedString()), "encoding": "base64"])168        try #expect(binary.output["bytesWritten"] == 3 && (try Data(contentsOf: h.tmp.file("b.bin"))) == Data([1, 2, 3]))169        #expect(await h.call("filesystem.write", ["path": "b2.bin", "content": "%%%", "encoding": "base64"]).status == .invalidInput)170        #expect(await h.call("filesystem.write", ["path": "out", "content": "x", "overwrite": true]).status == .invalidInput)171    }172173    @Test func mkdirCopyMove() async throws {174        let h = try await Harness(); defer { h.tmp.remove() }175        let made = await h.call("filesystem.mkdir", ["path": "a/b/c"])176        #expect(made.output["created"] == true && h.exists("a/b/c"))177        #expect(await h.call("filesystem.mkdir", ["path": "a/b/c"]).output["created"] == false)178        try h.tmp.write("a/file.txt", "payload"); try h.tmp.write("existing.txt", "old")179        #expect(await h.call("filesystem.copy", ["source": "a/file.txt", "destination": "copy.txt"]).status == .succeeded)180        #expect(h.read("copy.txt") == "payload" && h.exists("a/file.txt"))181        #expect(await h.call("filesystem.copy", ["source": "a/file.txt", "destination": "existing.txt"]).status == .invalidInput)182        #expect(h.read("existing.txt") == "old")183        let over = await h.call("filesystem.copy", ["source": "a/file.txt", "destination": "existing.txt", "overwrite": true])184        #expect(h.read("existing.txt") == "payload" && over.output["backupPath"]?.stringValue != nil)185        #expect(await h.call("filesystem.copy", ["source": "a", "destination": "tree-copy"]).status == .succeeded)186        #expect(h.read("tree-copy/file.txt") == "payload" && h.exists("tree-copy/b/c"))187        #expect(await h.call("filesystem.copy", ["source": "a", "destination": "a/inside"]).status == .invalidInput)188189        let dry = await h.call("filesystem.move", ["source": "copy.txt", "destination": "moved/renamed.txt"], dryRun: true)190        #expect(dry.status == .simulated && h.exists("copy.txt"))191        #expect(await h.call("filesystem.move", ["source": "copy.txt", "destination": "moved/renamed.txt"]).status == .succeeded)192        #expect(!h.exists("copy.txt") && h.read("moved/renamed.txt") == "payload")193        try h.tmp.write("other.txt", "other")194        let clash = await h.call("filesystem.move", ["source": "other.txt", "destination": "existing.txt"])195        #expect(clash.status == .invalidInput && h.read("existing.txt") == "payload" && h.read("other.txt") == "other", "move never overwrites")196        #expect(await h.call("filesystem.move", ["source": "ghost.txt", "destination": "x.txt"]).failure?.code == "not_found")197    }198199    @Test func metadataChecksumCompare() async throws {200        let h = try await Harness(); defer { h.tmp.remove() }201        try h.tmp.write("m.json", "{}"); try h.tmp.write("abc.txt", "abc")202        let meta = await h.call("filesystem.metadata", ["path": "m.json"])203        #expect(meta.output["type"] == "file" && meta.output["size"] == 2 && meta.output["contentType"] == "public.json" && meta.output["permissions"] == "644")204        #expect(await h.call("filesystem.metadata", ["path": "."]).output["type"] == "directory")205        let sum = await h.call("filesystem.checksum", ["path": "abc.txt"])206        #expect(sum.output["digest"] == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" && sum.output["bytes"] == 3)207        #expect(await h.call("filesystem.checksum", ["path": "."]).status == .invalidInput)208209        try h.tmp.write("same.txt", "abc"); try h.tmp.write("diff.txt", "abd")210        #expect(await h.call("filesystem.compare", ["source": "abc.txt", "destination": "same.txt"]).output["identical"] == true)211        #expect(await h.call("filesystem.compare", ["source": "abc.txt", "destination": "diff.txt"]).output["identical"] == false)212        try h.tmp.write("L/keep.txt", "k"); try h.tmp.write("L/gone.txt", "g"); try h.tmp.write("L/mod.txt", "old!"); try h.tmp.write("L/d/n.txt", "n")213        try h.tmp.write("R/keep.txt", "k"); try h.tmp.write("R/new.txt", "n"); try h.tmp.write("R/mod.txt", "new!"); try h.tmp.write("R/d/n.txt", "n")214        let trees = await h.call("filesystem.compare", ["source": "L", "destination": "R"])215        #expect(trees.output["kind"] == "directories" && trees.output["identical"] == false)216        #expect(trees.output["added"] == ["new.txt"] && trees.output["removed"] == ["gone.txt"] && trees.output["changed"] == ["mod.txt"])217        #expect(await h.call("filesystem.compare", ["source": "L", "destination": "L"]).output["identical"] == true)218        #expect(await h.call("filesystem.compare", ["source": "L", "destination": "abc.txt"]).status == .invalidInput)219    }220221    @Test func trashMovesToTheTrashAndReportsWhere() async throws {222        let h = try await Harness(); defer { h.tmp.remove() }223        try h.tmp.write("old-report.txt", "bye")224        let dry = await h.call("filesystem.trash", ["path": "old-report.txt"], dryRun: true)225        #expect(dry.status == .simulated && h.exists("old-report.txt"))226        let r = await h.call("filesystem.trash", ["path": "old-report.txt"])227        guard r.status == .succeeded else {228            print("SKIPPED(FileManager.trashItem is not available for the temp volume in this session: \(r.failure?.message ?? "?"))")229            #expect(r.failure?.code == "io")230            return231        }232        #expect(!h.exists("old-report.txt"))233        let trashed = try #require(r.output["trashPath"]?.stringValue)234        #expect(FileManager.default.fileExists(atPath: trashed) && trashed.contains("Trash"))235        try? FileManager.default.removeItem(atPath: trashed)  // remove the one item this test put in the Trash236        #expect(await h.call("filesystem.trash", ["path": "~"]).status == .unsupported)237        #expect(await h.call("filesystem.trash", ["path": "/"]).status == .unsupported)238    }239240    @Test func deleteIsPermanentTierThreeAndGuarded() async throws {241        let policy = ApprovalPolicy()242        let h = try await Harness(policy: policy, approvals: ScriptedApprovalBroker(fallback: .approveOnce)); defer { h.tmp.remove() }243        try h.tmp.write("d/a.txt", "a"); try h.tmp.write("d/sub/b.txt", "b"); try h.tmp.write("single.txt", "s")244        let dry = await h.call("filesystem.delete", ["path": "d", "recursive": true], dryRun: true)245        #expect(dry.status == .simulated && dry.output["items"] == 4 && h.exists("d/a.txt"))246        #expect(await h.call("filesystem.delete", ["path": "d"]).status == .invalidInput)247        #expect(h.exists("d/a.txt"))248        #expect(await h.call("filesystem.delete", ["path": "d", "recursive": true]).status == .succeeded)249        #expect(!h.exists("d"))250        #expect(await h.call("filesystem.delete", ["path": "single.txt"]).output["deleted"] == true)251        let last = await policy.requests.last252        #expect(last?.tier == .highRisk && last?.sideEffect == .destructive && last?.capabilities == [.fileDelete(path: h.path("single.txt"))])253        for broad in ["/", "~", "~/Documents", "/Users", "/Applications"] {254            #expect(await h.call("filesystem.delete", ["path": .string(broad), "recursive": true]).status == .unsupported, "\(broad)")255        }256    }257258    @Test func archiveAndUnarchiveRoundTrip() async throws {259        let h = try await Harness(); defer { h.tmp.remove() }260        try h.tmp.write("project/readme.md", "# hi"); try h.tmp.write("project/src/x.txt", "x"); try h.tmp.write("lonely.txt", "one")261        let zipped = await h.call("filesystem.archive", ["source": "project", "destination": "out/project.zip"])262        #expect(zipped.status == .succeeded && (zipped.output["bytes"]?.intValue ?? 0) > 0, "\(zipped.failure?.message ?? "")")263        #expect(await h.call("filesystem.archive", ["source": "project", "destination": "out/project.zip"]).status == .invalidInput)264        #expect(await h.call("filesystem.archive", ["source": "project", "destination": "out/project.tar"]).status == .invalidInput)265        let dry = await h.call("filesystem.unarchive", ["source": "out/project.zip", "destination": "restored"], dryRun: true)266        #expect(dry.status == .simulated && !h.exists("restored"))267        let unzipped = await h.call("filesystem.unarchive", ["source": "out/project.zip", "destination": "restored"])268        #expect(unzipped.status == .succeeded, "\(unzipped.failure?.message ?? "")")269        #expect(h.read("restored/project/readme.md") == "# hi" && h.read("restored/project/src/x.txt") == "x")270        #expect(await h.call("filesystem.compare", ["source": "project", "destination": "restored/project"]).output["identical"] == true)271        let again = await h.call("filesystem.unarchive", ["source": "out/project.zip", "destination": "restored"])272        #expect(again.status == .invalidInput, "extraction never replaces existing items")273        #expect(await h.call("filesystem.archive", ["source": "lonely.txt", "destination": "one.zip"]).status == .succeeded)274        #expect(await h.call("filesystem.unarchive", ["source": "one.zip", "destination": "single"]).status == .succeeded)275        #expect(h.read("single/lonely.txt") == "one")276        #expect(await h.call("filesystem.unarchive", ["source": "lonely.txt", "destination": "bad"]).status == .unsupported)277        // No staging leftovers next to the archive.278        let leftovers = try FileManager.default.contentsOfDirectory(atPath: h.path("out"))279        #expect(leftovers == ["project.zip"])280    }281282    @Test func waitForChangeSeesDirectoryAndFileChangesAndTimesOut() async throws {283        let h = try await Harness(); defer { h.tmp.remove() }284        try h.tmp.write("watched/seed.txt", "s"); try h.tmp.write("single.txt", "1")285        let quiet = await h.call("filesystem.waitForChange", ["path": "watched", "timeoutSeconds": 0.4])286        #expect(quiet.status == .succeeded && quiet.output["changed"] == false && quiet.output["timedOut"] == true)287288        // The writers keep producing changes until the watcher answers, so the test does not depend on how fast the289        // watcher starts on a busy machine.290        let tmp = h.tmp291        let dirWriter = Task {292            var n = 0293            while !Task.isCancelled {294                try? await Task.sleep(for: .milliseconds(250))295                n += 1296                _ = try? tmp.write("watched/sub/created-\(n).txt", "new")297            }298        }299        let dirResult = await h.call("filesystem.waitForChange", ["path": "watched", "timeoutSeconds": 30])300        dirWriter.cancel()301        let paths = dirResult.output["events"]?.arrayValue?.compactMap { $0["path"]?.stringValue } ?? []302        #expect(dirResult.output["changed"] == true && paths.contains { $0.contains("/watched/sub") }, "\(dirResult.output.serialized())")303304        let fileWriter = Task {305            while !Task.isCancelled {306                try? await Task.sleep(for: .milliseconds(250))307                if let handle = try? FileHandle(forWritingTo: tmp.file("single.txt")) {308                    _ = try? handle.seekToEnd(); try? handle.write(contentsOf: Data("2".utf8)); try? handle.close()309                }310            }311        }312        let fileResult = await h.call("filesystem.waitForChange", ["path": "single.txt", "timeoutSeconds": 30])313        fileWriter.cancel()314        #expect(fileResult.output["changed"] == true && fileResult.output["events"]?[0]?["change"]?.stringValue?.contains("modified") == true)315316        let task = Task { await h.call("filesystem.waitForChange", ["path": "watched", "timeoutSeconds": 60]) }317        try await Task.sleep(for: .milliseconds(300))318        task.cancel()319        #expect(await task.value.status == .canceled)320    }321}322
Files main
Menu

Theme