feat(sessions): keep every session, record review details, name and stamp the PDF

Sessions are now the unit of the product instead of an implicit capture run.

- Nothing is deleted by default: the fixed 10-session cap is gone. An age limit
  (Never / 7 / 14 / 30 / 90 / 180 / 365 days) is chosen in Settings > Sessions and
  applied on launch, after archiving, and by "Clean up now". Sent PDFs are never
  touched.
- Each session carries review details: lane, deployed version, commit, reviewer
  (pre-filled with the Mac user) and a free note. They persist in session.json and
  are inherited by the next session, so a review run is typed once.
- PDF file names are Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf, and every page
  carries a two-line reference footer (tool, build time, session / lane, deployed
  build, commit, reviewer, note). The PDF document info carries the same values in
  Author and Keywords.
- Verification: 159 tests, a headless panel self-test, and a LaunchServices-driven
  end-to-end run that types and clicks the real panel.
This commit is contained in:
Claude Fable 5
2026-10-31 11:32:54 +04:00
parent 542aad296b
commit 02fa791b78
26 changed files with 2780 additions and 279 deletions
+88 -44
View File
@@ -4,24 +4,26 @@ import CoreGraphics
import Darwin
public actor SpoolStore {
/// How many archived sessions (past submissions) are kept on disk. Ben's
/// retention rule (2026-10-11): "by default, retain the past 10 sessions" —
/// older session folders are removed from `archive/` once this is exceeded.
/// Any PDF a pruned session produced is not touched: it lives in the outbox
/// (or the OneDrive folder) it was sent to.
public static let defaultRetainedSessionCount = 10
private let paths: AppSupportPaths
private var openSession: CaptureSession
/// The user's age limit for kept sessions. `.never` (the default) means every
/// session is kept: nothing is deleted until an age limit is chosen in Settings.
private var retention: SessionRetention
public init(paths: AppSupportPaths) throws {
public init(paths: AppSupportPaths, retention: SessionRetention = .never) throws {
self.paths = paths
self.retention = retention
let fm = FileManager.default
try Self.supersedeSpoolArchiveOverlaps(paths: paths, fileManager: fm)
try Self.finishInterruptedArchives(paths: paths, fileManager: fm)
let remainingIDs = try Self.listUUIDDirectories(in: paths.spool, fileManager: fm)
if remainingIDs.isEmpty {
self.openSession = try Self.createFreshSession(paths: paths)
// A brand-new store: the reviewer is this Mac's user, so a session taken
// now records who took it without the user typing anything. Lane, build
// and commit stay empty until the user states them.
self.openSession = try Self.createFreshSession(
paths: paths,
context: ReviewContext(reviewer: ReviewContext.currentUser()))
} else {
var candidates: [CaptureSession] = []
for id in remainingIDs {
@@ -34,6 +36,31 @@ public actor SpoolStore {
}
}
/// Applies a new age limit to future archive/launch prunes. Does not delete
/// anything itself — a caller that just changed the setting calls
/// `pruneExpiredSessions()` when the user asked for a cleanup.
public func setRetention(_ value: SessionRetention) {
retention = value
}
/// The age limit this store is currently enforcing.
public func configuredRetention() -> SessionRetention {
retention
}
/// Records the review context (lane / deployed build / commit / reviewer / note)
/// on the open session and persists it in the manifest before returning. Fails
/// loudly if the manifest cannot be written — the in-memory session is only
/// updated after the durable write succeeds.
public func setContext(_ context: ReviewContext) throws -> CaptureSession {
let open = try ensureOpenSession()
let updated = open.withContext(context)
try AtomicFile.writeJSON(
updated, to: paths.sessionDirectory(open.id).appendingPathComponent("session.json"))
openSession = updated
return updated
}
/// The session currently accepting captures. Cheap accessor — all reconciliation already
/// happened once, inside init. A truth guard: if the stored session is no longer really
/// open on disk (its directory was archived away and the replacement session could not
@@ -54,7 +81,7 @@ public actor SpoolStore {
let staleID = openSession.id.uuidString
Log.spool.error(
"The stored open session \(staleID, privacy: .public) is not really open on disk; starting a fresh one.")
let fresh = try Self.createFreshSession(paths: paths)
let fresh = try Self.createFreshSession(paths: paths, context: openSession.context)
openSession = fresh
return fresh
}
@@ -86,10 +113,9 @@ public actor SpoolStore {
/// D-11: moves the capture's PNG into `<sessionDir>/removed/` (created lazily) and drops
/// its manifest entry. NEVER unlinks/deletes a user PNG on this path. Throws (no
/// filesystem change) if `captureID` is not present in the open session.
/// (Session retention is the one place that removes files: when a session falls
/// outside the newest `defaultRetainedSessionCount`, its WHOLE folder — including
/// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11),
/// not this remove path.)
/// (The one place that removes files is the age limit the user chose in Settings:
/// when a session is older than that limit, its WHOLE folder — including
/// `removed/` — is pruned. Nothing is pruned while the limit is "Never".)
public func remove(captureID: UUID) throws -> CaptureSession {
let open = try ensureOpenSession()
guard let capture = open.captures.first(where: { $0.id == captureID }) else {
@@ -129,7 +155,7 @@ public actor SpoolStore {
underlying: "cannot archive an empty session")
}
let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
openSession = try Self.createFreshSession(paths: paths, context: open.context)
applyRetention()
return archived
}
@@ -141,31 +167,46 @@ public actor SpoolStore {
/// the Past submissions list shows as "Not sent"). An empty open session is
/// simply replaced — there is nothing to keep. Returns the archived session, or
/// nil when the open session was empty.
///
/// The new session inherits the closed session's review context: one review run
/// spans several sessions in the same lane and build, so retyping it each time
/// would only add errors.
public func closeCurrentSession() throws -> CaptureSession? {
let open = try ensureOpenSession()
guard !open.isEmpty else {
openSession = try Self.createFreshSession(paths: paths)
openSession = try Self.createFreshSession(paths: paths, context: open.context)
return nil
}
let archived = try moveOpenSessionToArchive(
open.markArchived(pdfFileName: open.pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
openSession = try Self.createFreshSession(paths: paths, context: open.context)
applyRetention()
return archived
}
/// Keeps the newest `limit` archived sessions and removes the rest of the session
/// folders from archive/ (the single folder all sessions live in). Returns the
/// removed ids. Only UUID session folders directly under archive/ are ever
/// touched — never spool/, never anything else. This is the requested retention
/// policy (Ben, 2026-10-11: "retain the past 10 sessions"): a session folder
/// dropped here is gone for good, while any PDF it produced stays in the
/// outbox/OneDrive folder it was sent to.
public func pruneArchivedSessions(keeping limit: Int) throws -> [UUID] {
let sessions = try archivedSessions()
guard sessions.count > limit else { return [] }
/// Removes archived sessions created before the current age limit's cutoff and
/// returns their ids. With `.never` this removes nothing and returns `[]`, so
/// "keep everything" needs no separate code path. Only UUID session folders
/// directly under archive/ are ever touched — never spool/, never a PDF.
public func pruneExpiredSessions(now: Date = Date()) throws -> [UUID] {
guard let cutoff = retention.cutoff(now: now) else { return [] }
return try removeArchivedSessions(createdBefore: cutoff)
}
/// The ids `pruneExpiredSessions()` would remove right now — what Settings shows
/// before the user commits to a cleanup. Empty under `.never`.
public func expiredSessionIDs(now: Date = Date()) throws -> [UUID] {
guard let cutoff = retention.cutoff(now: now) else { return [] }
return try archivedSessions().filter { $0.createdAt < cutoff }.map(\.id)
}
/// Deletes the archived session folders created before `cutoff` and returns their
/// ids. Only archive/ is scanned, so an open session can never match.
private func removeArchivedSessions(createdBefore cutoff: Date) throws -> [UUID] {
let expired = try archivedSessions().filter { $0.createdAt < cutoff }
guard !expired.isEmpty else { return [] }
var removed: [UUID] = []
for session in sessions.dropFirst(limit) {
for session in expired {
let dir = paths.archiveDirectory(session.id)
do {
try FileManager.default.removeItem(at: dir)
@@ -177,26 +218,23 @@ public actor SpoolStore {
removed.append(session.id)
}
try AtomicFile.fsyncDirectory(at: paths.archive)
Log.spool.warning(
"Session retention (\(self.retention.displayName, privacy: .public)): removed \(removed.count, privacy: .public) archived session(s) older than \(DubaiTime.stamp(cutoff), privacy: .public).")
return removed
}
/// The retention policy every archive path funnels through, so it can never be
/// forgotten: sessions over the default count are pruned. A retention failure is
/// logged loudly (with the exact path) and never thrown — the archive it follows
/// already succeeded, and converting a completed send into a reported failure
/// would be a lie (the safe direction of a failed prune is keeping too much, never
/// losing data). The visible symptom of a failed prune is simply more than 10
/// sessions in the Past submissions list.
/// forgotten. A retention failure is logged loudly (with the exact path) and
/// never thrown — the archive it follows already succeeded, and converting a
/// completed send into a reported failure would be a lie (the safe direction of a
/// failed prune is keeping too much, never losing data). The visible symptom of a
/// failed prune is simply an old session still in the Past sessions list.
private func applyRetention() {
do {
let removed = try pruneArchivedSessions(keeping: Self.defaultRetainedSessionCount)
if !removed.isEmpty {
Log.spool.warning(
"Session retention: removed \(removed.count, privacy: .public) archived session(s) beyond the newest \(Self.defaultRetainedSessionCount, privacy: .public).")
}
_ = try pruneExpiredSessions()
} catch {
Log.spool.error(
"Session retention failed — past sessions were kept beyond \(Self.defaultRetainedSessionCount, privacy: .public): \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)")
"Session retention failed — expired sessions were kept: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)")
}
}
@@ -224,7 +262,7 @@ public actor SpoolStore {
path: paths.sessionDirectory(open.id).path,
underlying: "cannot start a new session: \(open.captures.count) capture(s) present in the open session")
}
let fresh = try Self.createFreshSession(paths: paths)
let fresh = try Self.createFreshSession(paths: paths, context: open.context)
openSession = fresh
return fresh
}
@@ -389,7 +427,8 @@ public actor SpoolStore {
createdAt: session.createdAt,
state: session.state,
captures: finalCaptures,
pdfFileName: session.pdfFileName)
pdfFileName: session.pdfFileName,
context: session.context)
try AtomicFile.writeJSON(updated, to: manifestURL)
Log.spool.warning("Reconciled session \(id.uuidString, privacy: .public): dropped \(missingCount) missing PNG(s), recovered \(recoveredOrphans.count) orphan(s).")
return updated
@@ -474,7 +513,10 @@ public actor SpoolStore {
}
}
private static func createFreshSession(paths: AppSupportPaths) throws -> CaptureSession {
private static func createFreshSession(
paths: AppSupportPaths,
context: ReviewContext
) throws -> CaptureSession {
let id = UUID()
let createdAt = Date()
let dir = paths.sessionDirectory(id)
@@ -483,7 +525,9 @@ public actor SpoolStore {
} catch {
throw ShotdeckError.spoolWriteFailed(path: dir.path, underlying: error.localizedDescription)
}
let session = CaptureSession(id: id, createdAt: createdAt, state: .open, captures: [], pdfFileName: nil)
let session = CaptureSession(
id: id, createdAt: createdAt, state: .open, captures: [], pdfFileName: nil,
context: context)
try AtomicFile.writeJSON(session, to: dir.appendingPathComponent("session.json"))
return session
}