Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / WorkContext.swift

1import CSQLite
2import Darwin
3import Foundation
4
5struct WorkReference: Sendable {
6 enum Origin: String, Sendable {
7 case git = "Git commit"
8 case claude = "Claude Code recap"
9 case codex = "Codex recap"
10 case notes = "Obsidian notes"
11 }
12
13 let title: String
14 var text: String
15 let origin: Origin
16 let at: Date
17
18 init(_ title: String, _ text: String, _ origin: Origin, _ at: Date) {
19 self.title = String(title.trimmingCharacters(in: .whitespacesAndNewlines).prefix(200))
20 self.text = String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(750))
21 self.origin = origin
22 self.at = at
23 }
24}
25
26struct WorkContext {
27 struct Result: Sendable {
28 var items: [WorkReference] = []
29 var unavailable: [String] = []
30 }
31
32 private let cutoff: Date
33 private let claudeRoot: URL
34 private let codexRoot: URL
35
36 init(now: Date = .now, home: URL = FileManager.default.homeDirectoryForCurrentUser) {
37 cutoff = now.addingTimeInterval(-48 * 60 * 60)
38 claudeRoot = home.appending(path: "Library/Application Support/Claude/claude-code-sessions")
39 codexRoot = home.appending(path: ".codex")
40 }
41
42 func collect(code: URL?, notes: URL?, limit: Int = 36) -> Result {
43 var result = Result()
44 func add(_ name: String, _ scan: () throws -> [WorkReference]) {
45 do { result.items += try scan() }
46 catch { result.unavailable.append(name) }
47 }
48 if let code {
49 let folder = code.resolvingSymlinksInPath().standardizedFileURL
50 add("Git") { try git(folder) }
51 add("Claude") { try claude(folder) }
52 add("Codex") { try codex(folder) }
53 }
54 if let notes {
55 add("Obsidian notes") {
56 let vault = try ObsidianVault(notes.path)
57 return try vault.list(query: "").notes.compactMap { row -> (String, Date)? in
58 guard let id = row["id"] as? String, let value = row["modifiedAt"] as? String,
59 let date = scheduleDate(value), date >= cutoff else { return nil }
60 return (id, date)
61 }.prefix(8).compactMap { id, date in
62 guard let note = try? vault.preview([id]).notes.first,
63 let title = note["title"], let text = note["text"] else { return nil }
64 return WorkReference(title, text, .notes, date)
65 }
66 }
67 }
68 result.items = Array(result.items.filter { !$0.title.isEmpty && !$0.text.isEmpty }
69 .sorted { $0.at > $1.at }.prefix(limit))
70 return result
71 }
72
73 private func git(_ folder: URL) throws -> [WorkReference] {
74 let child = Process()
75 let pipe = Pipe()
76 child.executableURL = URL(fileURLWithPath: "/usr/bin/git")
77 child.arguments = ["--no-optional-locks", "-C", folder.path, "log",
78 "--since=" + workspaceTimestamp(cutoff), "--no-merges", "-n", "12",
79 "--format=%aI%x1f%s", "--", "."]
80 child.standardOutput = pipe
81 child.standardError = FileHandle.nullDevice
82 child.standardInput = FileHandle.nullDevice
83 let output = pipe.fileHandleForReading
84 let descriptor = output.fileDescriptor
85 guard fcntl(descriptor, F_SETFL, O_NONBLOCK) != -1 else {
86 throw WorkspaceError("Couldn’t read recent Git activity.")
87 }
88 try child.run()
89 defer {
90 if child.isRunning { child.terminate() }
91 try? output.close()
92 }
93 let deadline = ContinuousClock.now + .seconds(3)
94 var data = Data()
95 var bytes = [UInt8](repeating: 0, count: 4096)
96 while ContinuousClock.now < deadline, data.count <= 64_000 {
97 let count = read(descriptor, &bytes, bytes.count)
98 if count > 0 {
99 data.append(contentsOf: bytes.prefix(count))
100 } else if count == 0 {
101 child.waitUntilExit()
102 guard child.terminationStatus == 0 else { break }
103 return String(decoding: data, as: UTF8.self).split(separator: "\n").compactMap { line in
104 let values = line.split(separator: "\u{1f}", maxSplits: 1)
105 guard values.count == 2, let date = scheduleDate(String(values[0])), date >= cutoff else { return nil }
106 return WorkReference(String(values[1]), String(values[1]), .git, date)
107 }
108 } else if errno == EAGAIN || errno == EINTR {
109 Thread.sleep(forTimeInterval: 0.02)
110 } else { break }
111 }
112 throw WorkspaceError("Couldn’t read recent Git activity.")
113 }
114
115 private func claude(_ folder: URL) throws -> [WorkReference] {
116 let keys: Set<URLResourceKey> = [.isSymbolicLinkKey, .isRegularFileKey, .fileSizeKey, .contentModificationDateKey]
117 guard let files = FileManager.default.enumerator(at: claudeRoot, includingPropertiesForKeys: Array(keys),
118 options: [.skipsHiddenFiles]) else {
119 throw WorkspaceError("Couldn’t read Claude recaps.")
120 }
121 var items: [WorkReference] = []
122 var scanned = 0
123 while let file = files.nextObject() as? URL, scanned < 1500 {
124 scanned += 1
125 guard let attributes = try? file.resourceValues(forKeys: keys) else { continue }
126 if attributes.isSymbolicLink == true || files.level > 3 {
127 files.skipDescendants()
128 continue
129 }
130 guard attributes.isRegularFile == true, file.lastPathComponent.hasPrefix("local_"), file.pathExtension == "json",
131 (attributes.fileSize ?? Int.max) <= 2 * 1024 * 1024,
132 (attributes.contentModificationDate ?? .distantPast) >= cutoff,
133 let bytes = try? Self.readRegular(file, limit: 2 * 1024 * 1024),
134 let session = (try? JSONSerialization.jsonObject(with: bytes)) as? [String: Any],
135 let cwd = session["cwd"] as? String, Self.contains(cwd, in: folder),
136 let timestamp = session["lastActivityAt"] as? Double, timestamp.isFinite,
137 let title = session["title"] as? String else { continue }
138 let date = Date(timeIntervalSince1970: timestamp / 1000)
139 let recap = (session["turnWrapUp"] as? [String: Any])?["description"] as? String
140 ?? (session["postTurnSummary"] as? [String: Any])?["status_detail"] as? String
141 if let recap, date >= cutoff { items.append(WorkReference(title, recap, .claude, date)) }
142 }
143 return Array(items.sorted { $0.at > $1.at }.prefix(12))
144 }
145
146 private func codex(_ folder: URL) throws -> [WorkReference] {
147 let files = try FileManager.default.contentsOfDirectory(at: codexRoot, includingPropertiesForKeys: nil)
148 let states = files.compactMap { url -> (URL, Int)? in
149 let name = url.deletingPathExtension().lastPathComponent
150 guard url.pathExtension == "sqlite", name.hasPrefix("state_"), let number = Int(name.dropFirst(6)) else { return nil }
151 return (url, number)
152 }
153 guard let file = states.max(by: { $0.1 < $1.1 })?.0 else { return [] }
154 var db: OpaquePointer?
155 defer { if let db { sqlite3_close(db) } }
156 guard sqlite3_open_v2(file.path, &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOFOLLOW, nil) == SQLITE_OK, let db else {
157 throw WorkspaceError("Couldn’t open Codex’s local history.")
158 }
159 sqlite3_busy_timeout(db, 500)
160 var statement: OpaquePointer?
161 let sql = """
162 SELECT title, cwd, rollout_path, updated_at FROM threads
163 WHERE (cwd = ? OR instr(cwd, ?) = 1) AND updated_at >= ?
164 ORDER BY updated_at DESC LIMIT 12
165 """
166 guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK, let statement else {
167 throw WorkspaceError("Couldn’t read Codex’s local history.")
168 }
169 defer { sqlite3_finalize(statement) }
170 let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
171 let prefix = folder.path == "/" ? "/" : folder.path + "/"
172 sqlite3_bind_text(statement, 1, folder.path, -1, transient)
173 sqlite3_bind_text(statement, 2, prefix, -1, transient)
174 sqlite3_bind_int64(statement, 3, Int64(cutoff.timeIntervalSince1970))
175 let root = codexRoot.resolvingSymlinksInPath().standardizedFileURL
176 var items: [WorkReference] = []
177 while true {
178 switch sqlite3_step(statement) {
179 case SQLITE_DONE: return items
180 case SQLITE_ROW:
181 guard let title = sqlite3_column_text(statement, 0), let cwd = sqlite3_column_text(statement, 1),
182 let path = sqlite3_column_text(statement, 2), Self.contains(String(cString: cwd), in: folder),
183 let recap = Self.codexRecap(String(cString: path), root: root) else { continue }
184 let date = Date(timeIntervalSince1970: Double(sqlite3_column_int64(statement, 3)))
185 items.append(WorkReference(String(cString: title), recap, .codex, date))
186 default: throw WorkspaceError("Couldn’t read Codex’s local history.")
187 }
188 }
189 }
190
191 private static func codexRecap(_ path: String, root: URL) -> String? {
192 guard contains(path, in: root) else { return nil }
193 let file = URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL
194 guard contains(file.path, in: root), let bytes = try? readRegular(file, limit: 192_000, tail: true) else { return nil }
195 for line in bytes.split(separator: 10).reversed() {
196 guard let row = (try? JSONSerialization.jsonObject(with: Data(line))) as? [String: Any],
197 let payload = row["payload"] as? [String: Any] else { continue }
198 if row["type"] as? String == "event_msg", payload["type"] as? String == "task_complete",
199 let text = payload["last_agent_message"] as? String { return text }
200 if row["type"] as? String == "response_item", payload["role"] as? String == "assistant",
201 payload["channel"] as? String == "final", let parts = payload["content"] as? [[String: Any]] {
202 return parts.filter { $0["type"] as? String == "output_text" }.compactMap { $0["text"] as? String }.joined(separator: "\n")
203 }
204 }
205 return nil
206 }
207
208 private static func contains(_ path: String, in folder: URL) -> Bool {
209 guard path.hasPrefix("/") else { return false }
210 return URL(fileURLWithPath: path).standardizedFileURL.pathComponents.starts(with: folder.pathComponents)
211 }
212
213 private static func readRegular(_ url: URL, limit: Int, tail: Bool = false) throws -> Data {
214 let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC)
215 guard descriptor >= 0 else { throw WorkspaceError("Couldn’t open a work recap.") }
216 let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
217 var info = stat()
218 guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFREG,
219 tail || info.st_size <= limit else { throw WorkspaceError("A work recap is unavailable or too large.") }
220 if tail { try handle.seek(toOffset: UInt64(max(0, info.st_size - Int64(limit)))) }
221 return try handle.read(upToCount: limit) ?? Data()
222 }
223}