From 01062eeea982b38a8cd8fd6019cd3fc18f5a33d3 Mon Sep 17 00:00:00 2001 From: CaffreySun Date: Tue, 15 Sep 2026 18:16:27 +0800 Subject: [PATCH 1/3] Prune backups by age rather than by file name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The backup directory is shared by every integration, and a backup's name starts with the name of the file it came from: settings.json.1789440066.d62d57de agentpet.ts.1789446695.aa1d698b Sorting those names is chronological only while every backup in the directory comes from the same file. With two integrations writing here — which is the case on main today — one integration's backups sort ahead of the other's however new they are, so the backup taken during a call was the first one that call pruned, and the path the caller had just been handed was already gone. Age now comes from the filesystem (.contentModificationDate), with the name settling ties inside a single clock tick. The new test takes a backup under a second name and asserts the reported path still exists afterwards; against the old ordering it fails with that path already removed. --- .../Integration/ConfigTransaction.swift | 38 ++++++++++++++++--- .../ConfigTransactionTests.swift | 32 ++++++++++++++++ 2 files changed, 64 insertions(+), 6 deletions(-) diff --git a/Sources/AgentPetCore/Integration/ConfigTransaction.swift b/Sources/AgentPetCore/Integration/ConfigTransaction.swift index d8d1a08..4917a3d 100644 --- a/Sources/AgentPetCore/Integration/ConfigTransaction.swift +++ b/Sources/AgentPetCore/Integration/ConfigTransaction.swift @@ -396,17 +396,43 @@ public struct ConfigTransaction: Sendable { return target } - /// Keeps backup growth bounded. Named with a timestamp, so lexical order is - /// chronological. + /// Keeps backup growth bounded, oldest first. + /// + /// Age comes from the filesystem, not from the name. The name is + /// `".."`, so sorting names *is* + /// chronological — but only while every backup in this directory came from + /// the same file. A second integration writing here broke that: the name + /// starts with the name of the file the backup came from, so one + /// integration's backups sort ahead of another's however new they are. The + /// backup taken a moment earlier was then the first one pruned, and the + /// path the caller had just been handed no longer existed. private func pruneBackups() { let fileManager = FileManager.default + let keys: Set = [.contentModificationDateKey] guard let entries = try? fileManager.contentsOfDirectory( - at: backupDirectory, includingPropertiesForKeys: nil + at: backupDirectory, includingPropertiesForKeys: Array(keys) ) else { return } + guard entries.count > maxBackups else { return } + + func age(_ url: URL) -> Date? { + (try? url.resourceValues(forKeys: keys))?.contentModificationDate + } + + let ordered = entries.sorted { left, right in + switch (age(left), age(right)) { + case let (leftDate?, rightDate?): + // Two writes inside the same clock tick are still distinct + // files; the name settles the order the clock cannot. + return leftDate == rightDate + ? left.lastPathComponent < right.lastPathComponent + : leftDate < rightDate + case (_?, nil): return true + case (nil, _?): return false + case (nil, nil): return left.lastPathComponent < right.lastPathComponent + } + } - let sorted = entries.sorted { $0.lastPathComponent < $1.lastPathComponent } - guard sorted.count > maxBackups else { return } - for url in sorted.prefix(sorted.count - maxBackups) { + for url in ordered.prefix(ordered.count - maxBackups) { try? fileManager.removeItem(at: url) } } diff --git a/Tests/AgentPetCoreTests/ConfigTransactionTests.swift b/Tests/AgentPetCoreTests/ConfigTransactionTests.swift index 08f7c6b..fc29f92 100644 --- a/Tests/AgentPetCoreTests/ConfigTransactionTests.swift +++ b/Tests/AgentPetCoreTests/ConfigTransactionTests.swift @@ -256,6 +256,38 @@ struct ConfigTransactionBackupTests { #expect(kept.count <= 3, "backups grew unbounded: \(kept.count)") } + @Test("a backup taken under a second file name survives the pruning it triggers") + func pruningFollowsAgeNotTheFileName() throws { + // The regression this exists for: backups were pruned by name, and a + // backup's name starts with the name of the file it came from — so one + // integration's backups sorted ahead of another's however new they + // were. Once two integrations share this directory, the backup taken + // during a call was the first one that call deleted, and the path it + // had just reported was already gone. + let sandbox = try Sandbox() + let settings = try sandbox.file("settings.json", "{}") + let second = try sandbox.file("second.json", "{}") + let tx = ConfigTransaction(backupDirectory: sandbox.backups, maxBackups: 3) + + for index in 0..<4 { + try tx.perform(on: settings) { $0["n"] = index } + Thread.sleep(forTimeInterval: 0.02) + } + + // The second file's backup is the newest thing in the directory, and + // its name sorts first (`second.json` < `settings.json`): under the old + // ordering this is the backup the call itself threw away. + let outcome = try tx.perform(on: second) { $0["n"] = 1 } + let backup = try #require(outcome.backupURL) + #expect(FileManager.default.fileExists(atPath: backup.path), + "the backup this call reported was pruned by the same call") + + let kept = (try? FileManager.default.contentsOfDirectory( + at: sandbox.backups, includingPropertiesForKeys: nil + )) ?? [] + #expect(kept.count <= 3, "backups grew past the limit: \(kept.count)") + } + @Test("a backup directory that does not exist yet is created") func backupDirectoryCreated() throws { let sandbox = try Sandbox() From ca997656460fb505a761a5e864a4381213d04f50 Mon Sep 17 00:00:00 2001 From: CaffreySun Date: Tue, 15 Sep 2026 18:16:28 +0800 Subject: [PATCH 2/3] Keep the second spelling of a session id and a tool name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The capture and spool allowlist knew Claude Code's `session_id` and `tool_name` only. The in-process extensions send the camelCase names their own API uses — Pi's extension already sends `toolName` beside a snake-case session id — so those fields were dropped on the way to disk. Dropping the tool name costs a label. Dropping the session id costs the row: an event spooled while the app was down replays with no session, falls back to the shim's parent pid, and draws a second row for a session that is already on screen under its real one. Both spellings are kept. The list stays hand-written rather than derived from the profiles: a profile's `summaryField` is the user's own prompt on `UserPromptSubmit`, and an allowlist that followed profiles would follow prompts onto disk. The test spools a camelCase payload and asserts the session id and the tool name survive while tool arguments and prompt text do not; without the fix the record reads {"cwd":…,"_omitted_keys":["args","sessionId","text","toolName"]}. --- .../Diagnostics/EventCapture.swift | 13 +++++++ Tests/AgentPetCoreTests/EventSpoolTests.swift | 39 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/Sources/AgentPetCore/Diagnostics/EventCapture.swift b/Sources/AgentPetCore/Diagnostics/EventCapture.swift index d55e16a..e267362 100644 --- a/Sources/AgentPetCore/Diagnostics/EventCapture.swift +++ b/Sources/AgentPetCore/Diagnostics/EventCapture.swift @@ -19,10 +19,23 @@ public enum EventCapture { /// /// Each is here because some diagnosis needs it. Anything whose value is /// user content is not, however useful it might be for debugging. + /// + /// Two spellings of the same two facts, because two agents name them + /// differently: Claude Code's hooks send `session_id` / `tool_name`, while + /// the in-process extensions send the camelCase names their own API uses + /// (`sessionId` / `toolName` — Pi's extension uses the camelCase tool name + /// next to the snake-case session id today). Missing a spelling is not + /// cosmetic: an event spooled without its session id replays as a second + /// row under a process-derived name, beside the real one. The list stays + /// hand-written rather than derived from the profiles — a profile's + /// `summaryField` is the user's own prompt on `UserPromptSubmit`, and an + /// allowlist that followed profiles would follow prompts onto disk. public static let capturableKeys: Set = [ "session_id", // opaque id; tells concurrent sessions apart + "sessionId", // the same, as the in-process extensions spell it "hook_event_name", "tool_name", // "Bash", "Read" — a label, not content + "toolName", // the same, as the in-process extensions spell it "notification_type", "permission_mode", "cwd", diff --git a/Tests/AgentPetCoreTests/EventSpoolTests.swift b/Tests/AgentPetCoreTests/EventSpoolTests.swift index db93099..c1859ba 100644 --- a/Tests/AgentPetCoreTests/EventSpoolTests.swift +++ b/Tests/AgentPetCoreTests/EventSpoolTests.swift @@ -92,6 +92,45 @@ struct EventSpoolTests { #expect(!text.contains("I read the file"), "model output is not ours to keep") } + @Test("a payload written in an extension's own spelling keeps its identity") + func extensionSpellingKeepsItsIdentity() throws { + // The regression this exists for: the allowlist knew only Claude Code's + // `session_id` / `tool_name`, so an event spooled from an in-process + // extension — those send the camelCase names their own API uses — lost + // its session, and replaying it after a restart drew that session under + // a process-derived name, beside the real one. + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + + EventSpool.write( + BridgeEnvelope( + agentID: "pi", + eventName: "tool_execution_start", + receivedAt: origin, + proc: BridgeProcessInfo(pid: 100, ppid: 50, tty: nil), + rawPayload: (try? JSONSerialization.data(withJSONObject: [ + "sessionId": "01a0a2d8-1028-7000-a617-ffb53b950be5", + "cwd": "/tmp/project", + "toolName": "bash", + "args": ["command": "cat ~/.ssh/id_rsa"], + "text": "the user's own words", + ])) ?? Data() + ), + to: directory + ) + + var replayed: [BridgeEnvelope] = [] + EventSpool.drain(from: directory) { replayed.append($0) } + let text = String(decoding: try #require(replayed.first).rawPayload, as: UTF8.self) + + #expect(text.contains("01a0a2d8-1028-7000-a617-ffb53b950be5"), + "a replayed event must keep its own session, not fall back to a pid") + #expect(text.contains("bash"), "the tool name is a label, not content") + // And the added spellings did not open the door to content. + #expect(!text.contains("id_rsa"), "tool arguments are not ours to keep") + #expect(!text.contains("the user's own words"), "prompt text is not ours to keep") + } + @Test("a burst cannot grow the spool without bound") func capHolds() throws { let directory = try makeDirectory() From 1a0bad57c61bfb6afb92032d4b37b42a28a56f69 Mon Sep 17 00:00:00 2001 From: CaffreySun Date: Tue, 15 Sep 2026 20:14:27 +0800 Subject: [PATCH 3/3] Say what the capture test actually covers Its comment credited the loss to "an in-process extension", which is not where the camelCase spelling comes from: Pi's extension sends `session_id` and only its tool name is camelCase, so nothing of ours has ever lost a session this way. What the test covers is a payload that spells the session id only in camelCase; the redaction path does not care which agent sent it, so the envelope's agent is `generic-cli` rather than a named one whose wire someone might go and check. Found while reviewing the rebase of the Oh My Pi branch, which carries the same test and got the same correction. 511 tests. --- Tests/AgentPetCoreTests/EventSpoolTests.swift | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Tests/AgentPetCoreTests/EventSpoolTests.swift b/Tests/AgentPetCoreTests/EventSpoolTests.swift index c1859ba..df5ea5b 100644 --- a/Tests/AgentPetCoreTests/EventSpoolTests.swift +++ b/Tests/AgentPetCoreTests/EventSpoolTests.swift @@ -95,16 +95,17 @@ struct EventSpoolTests { @Test("a payload written in an extension's own spelling keeps its identity") func extensionSpellingKeepsItsIdentity() throws { // The regression this exists for: the allowlist knew only Claude Code's - // `session_id` / `tool_name`, so an event spooled from an in-process - // extension — those send the camelCase names their own API uses — lost - // its session, and replaying it after a restart drew that session under - // a process-derived name, beside the real one. + // `session_id` / `tool_name`, so a payload that spelled its session id + // only in camelCase was spooled without one, and replaying it after a + // restart drew that session under a process-derived name, beside the + // real one. The envelope below is shaped like such a payload; the + // redaction path itself does not care which agent it came from. let directory = try makeDirectory() defer { try? FileManager.default.removeItem(at: directory) } EventSpool.write( BridgeEnvelope( - agentID: "pi", + agentID: "generic-cli", eventName: "tool_execution_start", receivedAt: origin, proc: BridgeProcessInfo(pid: 100, ppid: 50, tty: nil),