WP-5a: AnnotationInspector + ReturnLedger per SPEC-A1c with review corrections

This commit is contained in:
2026-08-31 14:58:34 +04:00
parent cee4c93dd5
commit 3dfb703834
4 changed files with 782 additions and 0 deletions
@@ -0,0 +1,110 @@
import Foundation
import PDFKit
public struct ReturnedDocument: Codable, Sendable, Identifiable, Equatable {
public var id: URL { fileURL }
public let fileURL: URL
/// Session UUID recovered from the PDF's subject attribute, when present and valid.
public let sessionID: UUID?
public let pageCount: Int
/// 1-based page numbers that carry at least one human mark, ascending, no duplicates.
public let annotatedPages: [Int]
public let detectedAt: Date
public var isCommented: Bool { !annotatedPages.isEmpty }
public init(
fileURL: URL,
sessionID: UUID?,
pageCount: Int,
annotatedPages: [Int],
detectedAt: Date
) {
self.fileURL = fileURL
self.sessionID = sessionID
self.pageCount = pageCount
self.annotatedPages = annotatedPages
self.detectedAt = detectedAt
}
}
public enum AnnotationInspector {
private static let humanMarkTypes: Set<String> = [
PDFAnnotationSubtype.ink.rawValue,
PDFAnnotationSubtype.highlight.rawValue,
PDFAnnotationSubtype.underline.rawValue,
PDFAnnotationSubtype.strikeOut.rawValue,
// PDFKit has no PDFAnnotationSubtype.squiggly member (unsupported renderer),
// but Apple Markup still writes Adobe /Squiggly objects that we must count.
PDFAnnotationSubtype(rawValue: "/Squiggly").rawValue,
PDFAnnotationSubtype.freeText.rawValue,
PDFAnnotationSubtype.square.rawValue,
PDFAnnotationSubtype.circle.rawValue,
PDFAnnotationSubtype.line.rawValue,
PDFAnnotationSubtype.stamp.rawValue,
PDFAnnotationSubtype.text.rawValue,
]
// .link ignored: a PDF hyperlink is structural, not a human mark.
// .popup ignored: it is always the companion of another annotation; counting it
// would double-count a single human mark as two.
// .widget ignored: a form field. Shotdeck's own PASS/FAIL boxes are page content
// (drawn by WP-2), never PDFAnnotation objects a widget seen here can only be
// introduced by a third-party tool flattening/reopening the file, and is not a
// human mark either way.
/// PDFKit's `PDFAnnotation.type` may omit the leading slash that
/// `PDFAnnotationSubtype.rawValue` includes; compare against the slash form.
private static func pdfTypeName(_ type: String) -> String {
type.hasPrefix("/") ? type : "/" + type
}
private static func isHumanMark(_ annotation: PDFAnnotation) -> Bool {
guard let raw = annotation.type else { return false }
let type = pdfTypeName(raw)
guard humanMarkTypes.contains(type) else { return false }
if type == PDFAnnotationSubtype.ink.rawValue {
let b = annotation.bounds
return b.width > 0 && b.height > 0 // zero-area ink = an undone stroke, not a mark
}
return true
}
/// Opens the PDF at fileURL and reports which pages carry a genuine human mark.
/// Throws ShotdeckError.manifestCorrupt(path: fileURL.path) if PDFDocument cannot open it.
/// File modification date is never consulted; only persisted PDFAnnotation objects count.
public static func inspect(fileURL: URL) throws -> ReturnedDocument {
guard let document = PDFDocument(url: fileURL) else {
throw ShotdeckError.manifestCorrupt(path: fileURL.path)
}
var annotatedPages: [Int] = []
for index in 0..<document.pageCount {
guard let page = document.page(at: index) else { continue }
if page.annotations.contains(where: isHumanMark) {
annotatedPages.append(index + 1) // 1-based
}
}
var sessionID: UUID?
if let subject = document.documentAttributes?[PDFDocumentAttribute.subjectAttribute] as? String {
sessionID = UUID(uuidString: subject) // nil (not thrown) if it doesn't parse
}
return ReturnedDocument(
fileURL: fileURL, sessionID: sessionID, pageCount: document.pageCount,
annotatedPages: annotatedPages, detectedAt: Date()
)
}
/// True when this PDF was produced by Shotdeck. Creator attribute is authoritative;
/// the filename fallback applies ONLY when the creator attribute is absent.
public static func isShotdeckDocument(_ document: PDFDocument) -> Bool {
if let creator = document.documentAttributes?[PDFDocumentAttribute.creatorAttribute] as? String {
return creator == "Shotdeck" // present creator is authoritative, full stop
}
// Creator ABSENT (some apps rewrite metadata on save) -> filename fallback only here.
guard let name = document.documentURL?.lastPathComponent else { return false }
// .lastPathComponent on a file URL is already percent-decoded; do not use .absoluteString.
return name.wholeMatch(of: /^Shotdeck-\d{8}-\d{6}( \d+)?\.pdf$/) != nil
// Case-sensitive by construction (Swift Regex literals are case-sensitive by default).
// The optional "( \d+)?" is macOS's duplicate-name suffix AirDrop adds when a file of
// the same name already exists in the watch folder the normal case for a return.
}
}
@@ -0,0 +1,60 @@
import Foundation
public actor ReturnLedger {
private let fileURL: URL
private var entries: [URL: ReturnedDocument]
/// Loads `returns.json` under paths.root if it exists; starts empty otherwise.
/// A file that cannot be decoded is renamed (never deleted) and the ledger starts empty.
public init(paths: AppSupportPaths) throws {
self.fileURL = paths.root.appendingPathComponent("returns.json")
if FileManager.default.fileExists(atPath: fileURL.path) {
let data = try Data(contentsOf: fileURL)
do {
let decoded = try JSONDecoder().decode([ReturnedDocument].self, from: data)
entries = Dictionary(decoded.map { ($0.fileURL, $0) }, uniquingKeysWith: { _, new in new })
} catch {
let stamp = DubaiTime.fileStamp(Date())
let corruptURL = fileURL.deletingLastPathComponent()
.appendingPathComponent("returns.json.corrupt-\(stamp)")
try FileManager.default.moveItem(at: fileURL, to: corruptURL)
Log.returns.error(
"returns.json could not be decoded; moved to \(corruptURL.path, privacy: .public): \(error.localizedDescription, privacy: .public)"
)
entries = [:]
}
} else {
entries = [:]
}
}
/// Upserts by fileURL recording the same URL again replaces the prior entry
/// (the most recently recorded call wins, regardless of its detectedAt value).
public func record(_ document: ReturnedDocument) throws {
entries[document.fileURL] = document
try persist()
}
/// Every recorded return, newest detectedAt first.
public func all() throws -> [ReturnedDocument] {
entries.values.sorted { $0.detectedAt > $1.detectedAt }
}
/// Commented returns (isCommented == true), newest detectedAt first.
public func commented() throws -> [ReturnedDocument] {
try all().filter(\.isCommented)
}
/// Absolute POSIX paths of commented returns, newest first, one per line, no
/// trailing newline. Throws ShotdeckError.noCommentedReturns when commented() is empty.
public func clipboardText() throws -> String {
let paths = try commented().map { $0.fileURL.path }
guard !paths.isEmpty else { throw ShotdeckError.noCommentedReturns }
return paths.joined(separator: "\n")
}
private func persist() throws {
let data = try JSONEncoder().encode(Array(entries.values))
try AtomicFile.write(data, to: fileURL)
}
}