Repository navigation
Expand file tree
/
Copy pathTranscriptFrontmatterReader.swift
More file actions
266 lines (248 loc) · 11 KB
/
Copy pathTranscriptFrontmatterReader.swift
File metadata and controls
266 lines (248 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import Foundation
/// Restores a TranscriptContext + status + attempts count from an on-disk
/// transcript.md. Used by SessionSupervisor on app relaunch so resumed sessions
/// preserve the original title, attendees, language, and retry attempt count
/// instead of reverting to a placeholder context.
///
/// Limitations: line-by-line parser, not a real YAML parser. Trusts that the
/// frontmatter was produced by `TranscriptWriter` (or the matching stub format
/// from `CaptureSession.writeTranscriptStub`). Returns `nil` for malformed
/// input rather than crashing.
public enum TranscriptFrontmatterReader {
public struct Frontmatter: Sendable {
public let status: TranscriptStatus
public let context: TranscriptContext
/// Number of failed attempts already persisted. 0 for pending / complete /
/// failed; non-zero only for `retrying` transcripts.
public let attempts: Int
}
public static func read(at url: URL) -> Frontmatter? {
guard let content = try? String(contentsOf: url, encoding: .utf8) else { return nil }
return readFromString(content)
}
/// Codex rc2-audit PRIVACY-1: streaming reader that opens the file
/// and reads byte-by-byte until the second `---` line. Stops the
/// stream there — never loads transcript bodies, attendees, or
/// titles into memory. Returns ONLY (status, attempts) for the
/// diagnostics aggregate-counts surface; the full Frontmatter
/// reader stays available for the supervisor's resume path.
static func readStatusAndAttemptsStreaming(at url: URL) -> (status: TranscriptStatus, attempts: Int)? {
readDiagnosticsFrontmatterStreaming(at: url).map { ($0.status, $0.attempts) }
}
/// Diagnostics-only frontmatter reader. It extracts only safe enum/count
/// fields plus normalized engine provenance, and still stops at the
/// frontmatter delimiter without reading transcript bodies.
static func readDiagnosticsFrontmatterStreaming(at url: URL) -> (status: TranscriptStatus, attempts: Int, engine: String)? {
guard let stream = InputStream(url: url) else { return nil }
stream.open()
defer { stream.close() }
var lineBuffer = Data()
var lineCount = 0
var sawOpener = false
var statusRaw: String?
var engineRaw: String?
var attempts = 0
let chunkSize = 256
var byte: UInt8 = 0
while stream.hasBytesAvailable {
let n = stream.read(&byte, maxLength: 1)
if n <= 0 { break }
if byte == 0x0A { // newline
lineCount += 1
let line = String(data: lineBuffer, encoding: .utf8)?
.trimmingCharacters(in: .whitespaces) ?? ""
lineBuffer.removeAll(keepingCapacity: true)
if !sawOpener {
if line == "---" { sawOpener = true; continue }
// Anything before the opening "---" is malformed.
return nil
}
if line == "---" {
// Closing delimiter — distinguish missing status (statusless
// success: .complete) from present-but-unrecognized status
// (malformed: nil), matching TranscriptStatusReader.
let parsedStatus: TranscriptStatus
if let raw = statusRaw {
guard let parsed = TranscriptStatus(rawValue: raw) else { return nil }
parsedStatus = parsed
} else {
parsedStatus = .complete
}
return (parsedStatus, attempts, normalizeDiagnosticsEngine(engineRaw))
}
if line.hasPrefix("status:") {
statusRaw = scalarValue(String(line.dropFirst("status:".count)))
}
if line.hasPrefix("engine:") {
engineRaw = scalarValue(String(line.dropFirst("engine:".count)))
}
if line.hasPrefix("attempts:") && statusRaw == "retrying" {
let v = String(line.dropFirst("attempts:".count))
.trimmingCharacters(in: .whitespaces)
attempts = Int(v) ?? 0
}
} else {
lineBuffer.append(byte)
// Per-line cap: a frontmatter line should be at most a
// couple hundred bytes. If we're not seeing newlines,
// bail rather than loading half the file.
if lineBuffer.count > chunkSize * 4 { return nil }
}
// Hard cap on number of lines read: spec frontmatters are
// ~10-15 lines; 100 is generous and stops us walking the
// body in the no-closing-delimiter case.
if lineCount > 100 { return nil }
}
return nil
}
private static func normalizeDiagnosticsEngine(_ raw: String?) -> String {
guard let raw, let mode = EngineMode(persistedIdentifier: raw) else { return "unknown" }
return mode.persistedIdentifier
}
static func readFromString(_ content: String) -> Frontmatter? {
let lines = content.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
guard lines.first?.trimmingCharacters(in: .whitespaces) == "---" else { return nil }
var inFrontmatter = true
var fields: [String: String] = [:]
var audioPaths: [String] = []
var attendees: [TranscriptPerson] = []
var organizer: TranscriptPerson?
var i = 1
var foundEnd = false
while i < lines.count, inFrontmatter {
let raw = lines[i]
let trimmed = raw.trimmingCharacters(in: .whitespaces)
if trimmed == "---" {
foundEnd = true
inFrontmatter = false
break
}
// List opener: `audio:` followed by ` - <path>` lines, or `attendees:` similarly.
if trimmed == "audio:" {
i += 1
while i < lines.count {
let item = lines[i]
if item.hasPrefix(" - ") {
audioPaths.append(scalarValue(String(item.dropFirst(4))))
i += 1
} else {
break
}
}
continue
}
if trimmed == "attendees:" {
i += 1
while i < lines.count {
let item = lines[i]
if item.hasPrefix(" - name:") {
let name = value(after: " - name:", in: item)
var email: String?
if i + 1 < lines.count, lines[i + 1].hasPrefix(" email:") {
email = value(after: " email:", in: lines[i + 1])
i += 1
}
attendees.append(TranscriptPerson(name: name, email: email))
i += 1
} else if item.hasPrefix(" - ") {
attendees.append(TranscriptPerson(name: value(after: " - ", in: item)))
i += 1
} else {
break
}
}
continue
}
if trimmed == "organizer:" {
var name = ""
var email: String?
i += 1
while i < lines.count {
let item = lines[i]
if item.hasPrefix(" name:") {
name = value(after: " name:", in: item)
i += 1
} else if item.hasPrefix(" email:") {
email = value(after: " email:", in: item)
i += 1
} else {
break
}
}
if !name.isEmpty { organizer = TranscriptPerson(name: name, email: email) }
continue
}
if let colon = trimmed.firstIndex(of: ":") {
let key = String(trimmed[..<colon])
let value = scalarValue(String(trimmed[trimmed.index(after: colon)...]))
fields[key] = value
}
i += 1
}
guard foundEnd else { return nil }
let status: TranscriptStatus
if let statusRaw = fields["status"] {
guard let parsed = TranscriptStatus(rawValue: statusRaw) else { return nil }
status = parsed
} else {
status = .complete
}
// `audio:` may have been a single inline value (single-track case).
if audioPaths.isEmpty, let single = fields["audio"], !single.isEmpty {
audioPaths = [single]
}
let context = TranscriptContext(
title: fields["title"] ?? "(untitled)",
date: fields["date"] ?? "",
engine: fields["engine"] ?? "unknown",
audioRelativePaths: audioPaths,
scheduledStart: fields["scheduled_start"],
scheduledEnd: fields["scheduled_end"],
actualStart: fields["actual_start"],
actualEnd: fields["actual_end"],
startedAt: fields["started_at"],
endedAt: fields["ended_at"],
organizer: organizer,
location: fields["location"],
calendarEventID: fields["calendar_event_id"],
joinedLate: fields["joined_late"].flatMap(Bool.init),
elapsedAtStartSeconds: fields["elapsed_at_start_seconds"].flatMap(Int.init),
attendees: attendees,
language: fields["language"]
)
let attempts = fields["attempts"].flatMap(Int.init) ?? 0
return Frontmatter(status: status, context: context, attempts: attempts)
}
private static func value(after prefix: String, in line: String) -> String {
scalarValue(String(line.dropFirst(prefix.count)))
}
private static func scalarValue(_ raw: String) -> String {
let trimmed = raw.trimmingCharacters(in: .whitespaces)
guard trimmed.count >= 2, trimmed.first == "\"", trimmed.last == "\"" else { return trimmed }
let inner = trimmed.dropFirst().dropLast()
var result = ""
var iterator = inner.makeIterator()
while let character = iterator.next() {
if character == "\\", let escaped = iterator.next() {
switch escaped {
case "\"":
result.append("\"")
case "\\":
result.append("\\")
case "n":
result.append("\n")
case "r":
result.append("\r")
case "t":
result.append("\t")
default:
result.append("\\")
result.append(escaped)
}
} else {
result.append(character)
}
}
return result
}
}