Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Sources/AgentPetCore/Diagnostics/EventCapture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = [
"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",
Expand Down
38 changes: 32 additions & 6 deletions Sources/AgentPetCore/Integration/ConfigTransaction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
/// `"<file>.<timestamp>.<fingerprint>"`, 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<URLResourceKey> = [.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)
}
}
Expand Down
32 changes: 32 additions & 0 deletions Tests/AgentPetCoreTests/ConfigTransactionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
40 changes: 40 additions & 0 deletions Tests/AgentPetCoreTests/EventSpoolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,46 @@ 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 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: "generic-cli",
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()
Expand Down