Skip to content
Open
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
19 changes: 17 additions & 2 deletions Sources/App/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -853,6 +853,12 @@ final class AppState: ObservableObject {
// writers racing into `explanationText`). The streaming workers below stream
// deltas straight into `explanationText` and finalize (strip + cache) at end.

private func recordExplanation(_ text: String, kind: ExplanationJournal.Kind, origin: ExplanationJournal.Origin) {
let directory = URL(fileURLWithPath: Secrets.appSupportDir).appendingPathComponent("explanation-journal", isDirectory: true)
do { try ExplanationJournal(directory: directory).record(text, kind: kind, origin: origin) }
catch { statusText = "해설은 생성됐지만 기록 저장에 실패했습니다" }
}

func generateExplanation(force: Bool = false) {
cancelActiveWork()
explainTask = Task { [weak self] in _ = await self?.runExplain(force: force) }
Expand Down Expand Up @@ -913,7 +919,8 @@ final class AppState: ObservableObject {
temperature: explainer.temperature, reasoning: explainer.reasoningLevel.rawValue)
if !force, let cached = normCache.script(forKey: nk) {
guard !Task.isCancelled, explanationHistory.commit(request, output: cached) else { return nil }
explanationText = cached; lastExplainedCode = code; lastSegment = cached; return cached
explanationText = cached; lastExplainedCode = code; lastSegment = cached
recordExplanation(cached, kind: .full, origin: .cache); return cached
}
explanationText = ""
statusText = "해설 생성 중…"
Expand All @@ -940,6 +947,7 @@ final class AppState: ObservableObject {
lastExplainedCode = code // baseline for "이어서 해설"
lastSegment = out
statusText = ""
recordExplanation(out, kind: .full, origin: .generated)
return out
}

Expand All @@ -962,7 +970,12 @@ final class AppState: ObservableObject {
model: explainer.model, temperature: explainer.temperature,
reasoning: explainer.reasoningLevel)
if !force, let cached = normCache.script(forKey: nk) {
applyContinuation(cached, newBaseline: current); return cached
guard !Task.isCancelled else { return nil }
applyContinuation(cached, newBaseline: current)
if !cached.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix(CodeExplanation.noChange) {
recordExplanation(cached, kind: .continuation, origin: .cache)
}
return cached
}
explaining = true
defer { explaining = false }
Expand All @@ -984,6 +997,7 @@ final class AppState: ObservableObject {
statusText = "이어서 해설 오류: \(error.localizedDescription)"
return nil
}
guard !Task.isCancelled else { explanationText = original; return nil }
let out = CodeExplanation.stripMarkdown(acc)
if out.isEmpty || out.hasPrefix(CodeExplanation.noChange) {
explanationText = original // nothing to add → restore
Expand All @@ -996,6 +1010,7 @@ final class AppState: ObservableObject {
lastSegment = out
lastExplainedCode = current
statusText = "이어서 해설 추가됨"
recordExplanation(out, kind: .continuation, origin: .generated)
return out
}

Expand Down
52 changes: 52 additions & 0 deletions Sources/Core/ExplanationJournal.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import Foundation

/// Text-only completed explanation events, independent of audio and disposable cache.
struct ExplanationJournal {
enum Kind: String, Codable { case full, continuation }
enum Origin: String, Codable { case generated, cache }
struct Entry: Codable {
let version: Int
let id: UUID
let createdAt: Date
let kind: Kind
let origin: Origin
let text: String
}
let directory: URL
@discardableResult func record(_ text: String, kind: Kind, origin: Origin,
now: Date = Date()) throws -> URL? {
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }
let fm = FileManager.default
if fm.fileExists(atPath: directory.path) {
let a = try fm.attributesOfItem(atPath: directory.path)
guard a[.type] as? FileAttributeType == .typeDirectory,
(a[.posixPermissions] as? NSNumber)?.intValue == 0o700 else {
throw CocoaError(.fileWriteNoPermission)
}
} else {
try fm.createDirectory(at: directory, withIntermediateDirectories: false,
attributes: [.posixPermissions: 0o700])
}
let entry = Entry(version: 1, id: UUID(), createdAt: now, kind: kind, origin: origin, text: text)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .custom { date, encoder in
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
var value = encoder.singleValueContainer()
try value.encode(formatter.string(from: date))
}
let data = try encoder.encode(entry)
let file = directory.appendingPathComponent(entry.id.uuidString + ".json")
// Unique immutable events: temporary file has restrictive mode before bytes are written.
let temporary = directory.appendingPathComponent("." + UUID().uuidString + ".tmp")
guard fm.createFile(atPath: temporary.path, contents: nil, attributes: [.posixPermissions: 0o600]) else {
throw CocoaError(.fileWriteUnknown)
}
defer { try? fm.removeItem(at: temporary) }
let handle = try FileHandle(forWritingTo: temporary)
do { try handle.write(contentsOf: data); try handle.synchronize(); try handle.close() }
catch { try? handle.close(); throw error }
try fm.moveItem(at: temporary, to: file)
return file
}
}
41 changes: 41 additions & 0 deletions Tests/ExplanationJournalTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import Foundation
@main struct JournalTests {
static func main() throws {
let fm = FileManager.default
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try fm.createDirectory(at: root, withIntermediateDirectories: false)
defer { try? fm.removeItem(at: root) }
let dir = root.appendingPathComponent("events")
let journal = ExplanationJournal(directory: dir)
let date = Date(timeIntervalSince1970: 1700000000.125)
let a = try journal.record("해설\n본문", kind: .full, origin: .generated, now: date)!
let b = try journal.record("해설\n본문", kind: .full, origin: .cache, now: date)!
precondition(a != b)
let data = try Data(contentsOf: a)
let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
precondition(Set(json.keys) == Set(["version","id","createdAt","kind","origin","text"]))
precondition(json["text"] as? String == "해설\n본문")
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom { decoder in
let value = try decoder.singleValueContainer().decode(String.self)
let formatter = ISO8601DateFormatter(); formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
guard let date = formatter.date(from: value) else { throw CocoaError(.fileReadCorruptFile) }
return date
}
let entry = try decoder.decode(ExplanationJournal.Entry.self, from: data)
precondition(entry.createdAt == date && entry.kind == .full && entry.origin == .generated)
let cached = try decoder.decode(ExplanationJournal.Entry.self, from: Data(contentsOf: b))
precondition(cached.origin == .cache)
let empty = try journal.record(" \n", kind: .full, origin: .cache); precondition(empty == nil)
let c = try journal.record("추가", kind: .continuation, origin: .generated)!
let continuation = try decoder.decode(ExplanationJournal.Entry.self, from: Data(contentsOf: c)); precondition(continuation.kind == .continuation)
let fileMode = try fm.attributesOfItem(atPath: a.path)[.posixPermissions] as! NSNumber; precondition(fileMode.intValue == 0o600)
let dirMode = try fm.attributesOfItem(atPath: dir.path)[.posixPermissions] as! NSNumber; precondition(dirMode.intValue == 0o700)
let link = root.appendingPathComponent("link")
try fm.createSymbolicLink(at: link, withDestinationURL: dir)
do { _ = try ExplanationJournal(directory: link).record("bad",kind:.full,origin:.cache); fatalError("symlink accepted") } catch {}
try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
do { _ = try journal.record("bad",kind:.full,origin:.cache); fatalError("unsafe permissions accepted") } catch {}
print("ExplanationJournal: schema, Unicode, timestamps, repeated/cache events, continuation, empty, modes, symlink and permission failure PASS")
}
}
3 changes: 3 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ case "${1:-install}" in
test)
echo "==> Compiling + running unit tests"
mkdir -p "$BUILD_DIR"
swiftc -O "$HERE/Sources/Core/ExplanationJournal.swift" "$HERE/Tests/ExplanationJournalTests.swift" -o "$BUILD_DIR/journal-tests"
"$BUILD_DIR/journal-tests"
mkdir -p "$BUILD_DIR"
swiftc -O "$HERE/Sources/Core/TextSplitter.swift" "$HERE/Sources/Core/CrawlLayout.swift" \
"$HERE/Sources/App/Endpoints.swift" "$HERE/Tests/main.swift" -o "$BUILD_DIR/tests"
"$BUILD_DIR/tests"
Expand Down