From a8e9765db31d726c78300c36be62b7ac9d634c9a Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:18:56 +0000 Subject: [PATCH 1/3] CC-390: keep both Muse alerts visible; bound standard-session detector state (24h TTL + 512 cap) --- Sources/CodeCaps/MuseCodePluginView.swift | 5 +- .../MuseCodeStandardSessionDetector.swift | 52 ++++++++++++++++++- Tests/CodeCapsTests/MuseCodePluginTests.swift | 15 ++++++ ...MuseCodeStandardSessionDetectorTests.swift | 28 ++++++++++ 4 files changed, 98 insertions(+), 2 deletions(-) diff --git a/Sources/CodeCaps/MuseCodePluginView.swift b/Sources/CodeCaps/MuseCodePluginView.swift index fc11385d..30ad12d2 100644 --- a/Sources/CodeCaps/MuseCodePluginView.swift +++ b/Sources/CodeCaps/MuseCodePluginView.swift @@ -111,9 +111,12 @@ struct MuseCodeMonitorPage: View { if let report = model.museCodeReport { row("Last Read", report.generatedAt.formatted(date: .omitted, time: .standard)) } + // Burn and standard-session alerts are independent findings: + // both stay visible when both are present. if let alert = model.museCodeBurnAlert { row("Burn Alert", alert.body) - } else if let alert = model.museCodeStandardSessionAlert { + } + if let alert = model.museCodeStandardSessionAlert { row("Standard Session Alert", alert.body) } } diff --git a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift index f7752a31..70910af9 100644 --- a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift +++ b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift @@ -92,8 +92,29 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { /// here has never been observed with a model. public private(set) var lastKnownModels: [String: String] - public init(lastKnownModels: [String: String] = [:]) { + /// When each tracked session was last observed, for staleness eviction. + /// Blobs persisted before the cap existed carry no stamps; those sessions + /// are kept and stamped on their next observation. + public private(set) var lastObservedAt: [String: Date] + + /// A session not observed for this long is no longer live: the reader's + /// window is ninety minutes, so a full day absent means it ended. + public static let sessionStateTTL: TimeInterval = 24 * 3_600 + /// Backstop bound on tracked sessions; the least recently observed are + /// evicted first. + public static let maxTrackedSessions = 512 + + public init(lastKnownModels: [String: String] = [:], lastObservedAt: [String: Date] = [:]) { self.lastKnownModels = lastKnownModels + self.lastObservedAt = lastObservedAt + } + + private enum CodingKeys: String, CodingKey { case lastKnownModels, lastObservedAt } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + lastKnownModels = try container.decode([String: String].self, forKey: .lastKnownModels) + lastObservedAt = try container.decodeIfPresent([String: Date].self, forKey: .lastObservedAt) ?? [:] } /// A contributor model is a model id ending in `-contributor`. @@ -121,6 +142,7 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { public mutating func observe( _ observations: [MuseCodeSessionModelObservation] ) -> [MuseCodeStandardSessionEvent] { + evictExpiredSessions(relativeTo: observations.map(\.observedAt).max()) var events: [MuseCodeStandardSessionEvent] = [] for observation in observations { guard let modelId = observation.modelId, !modelId.isEmpty else { continue } @@ -132,10 +154,38 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { observedAt: observation.observedAt)) } lastKnownModels[observation.sessionId] = modelId + lastObservedAt[observation.sessionId] = observation.observedAt } + trimToCap() return events } + /// Drops sessions whose last observation is older than the TTL. Runs + /// before the poll so an evicted session that returns fires once as + /// first-observed, which a day-long absence warrants. + private mutating func evictExpiredSessions(relativeTo newest: Date?) { + guard let newest else { return } + let cutoff = newest.addingTimeInterval(-Self.sessionStateTTL) + for (sessionId, observedAt) in lastObservedAt where observedAt < cutoff { + lastKnownModels.removeValue(forKey: sessionId) + lastObservedAt.removeValue(forKey: sessionId) + } + } + + /// Trims the state to the cap by evicting the least recently observed. + /// Unstamped legacy sessions sort newest, so they are evicted last. + private mutating func trimToCap() { + guard lastKnownModels.count > Self.maxTrackedSessions else { return } + let overflow = lastKnownModels.count - Self.maxTrackedSessions + let oldest = lastKnownModels.keys.sorted { + (lastObservedAt[$0] ?? .distantFuture) < (lastObservedAt[$1] ?? .distantFuture) + }.prefix(overflow) + for sessionId in oldest { + lastKnownModels.removeValue(forKey: sessionId) + lastObservedAt.removeValue(forKey: sessionId) + } + } + /// The sessions in one poll whose current model is standard, as events /// with no firing semantics: the presence test the burn rule uses. A /// standard session that has been running for an hour still counts here diff --git a/Tests/CodeCapsTests/MuseCodePluginTests.swift b/Tests/CodeCapsTests/MuseCodePluginTests.swift index 648fb99a..6f9abada 100644 --- a/Tests/CodeCapsTests/MuseCodePluginTests.swift +++ b/Tests/CodeCapsTests/MuseCodePluginTests.swift @@ -10,9 +10,24 @@ private final class SpyAlertChannel: CodeCapsAlertChannel { @MainActor final class MuseCodePluginTests: XCTestCase { + private static var repoRoot: URL { + URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + } + private var suiteName = "" private var defaults: UserDefaults! + func testBothMuseAlertsStayVisibleTogether() throws { + let source = try String( + contentsOf: Self.repoRoot.appendingPathComponent("Sources/CodeCaps/MuseCodePluginView.swift"), + encoding: .utf8) + XCTAssertFalse(source.contains("} else if let alert = model.museCodeStandardSessionAlert"), + "the standard-session alert must not hide behind a burn alert; both stay visible") + } + override func setUp() { super.setUp() suiteName = "MuseCodePluginTests." + UUID().uuidString diff --git a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift index 334ceeb7..2268b864 100644 --- a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift @@ -124,4 +124,32 @@ final class MuseCodeStandardSessionDetectorTests: XCTestCase { XCTAssertEqual(present.map(\.sessionId), ["s2"]) XCTAssertEqual(present.first?.modelId, standardModel) } + + func testSessionUnobservedPastTTLIsEvictedAndRefiresAsNew() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", contributorModel)]).count, 0) + let later = MuseCodeStandardSessionDetector.sessionStateTTL + 600 + let events = detector.observe([observation("s2", contributorModel, at: later), + observation("s1", standardModel, at: later)]) + XCTAssertEqual(events.map(\.sessionId), ["s1"], + "a session silent past the TTL is evicted, so returning on a standard model fires as first-observed") + } + + func testTrackedStateIsCappedByEvictingLeastRecentlyObserved() { + var detector = MuseCodeStandardSessionDetector() + for i in 0.. Date: Tue, 10 Nov 2026 05:44:49 +0000 Subject: [PATCH 2/3] CC-390: address Kody review - nil-model liveness, idle-poll TTL fallback, legacy sessions evict first at cap --- .../MuseCodeStandardSessionDetector.swift | 14 ++++--- ...MuseCodeStandardSessionDetectorTests.swift | 38 +++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift index 70910af9..cfecb6ed 100644 --- a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift +++ b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift @@ -145,6 +145,7 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { evictExpiredSessions(relativeTo: observations.map(\.observedAt).max()) var events: [MuseCodeStandardSessionEvent] = [] for observation in observations { + lastObservedAt[observation.sessionId] = observation.observedAt guard let modelId = observation.modelId, !modelId.isEmpty else { continue } let previous = lastKnownModels[observation.sessionId] let wasContributor = previous.map { Self.isContributor(modelId: $0) } ?? false @@ -154,7 +155,6 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { observedAt: observation.observedAt)) } lastKnownModels[observation.sessionId] = modelId - lastObservedAt[observation.sessionId] = observation.observedAt } trimToCap() return events @@ -162,10 +162,10 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { /// Drops sessions whose last observation is older than the TTL. Runs /// before the poll so an evicted session that returns fires once as - /// first-observed, which a day-long absence warrants. + /// first-observed, which a day-long absence warrants. An empty poll + /// falls back to the wall clock so idle periods still advance expiry. private mutating func evictExpiredSessions(relativeTo newest: Date?) { - guard let newest else { return } - let cutoff = newest.addingTimeInterval(-Self.sessionStateTTL) + let cutoff = (newest ?? Date()).addingTimeInterval(-Self.sessionStateTTL) for (sessionId, observedAt) in lastObservedAt where observedAt < cutoff { lastKnownModels.removeValue(forKey: sessionId) lastObservedAt.removeValue(forKey: sessionId) @@ -173,12 +173,14 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { } /// Trims the state to the cap by evicting the least recently observed. - /// Unstamped legacy sessions sort newest, so they are evicted last. + /// Sessions without a liveness stamp predate the stamp field: any session + /// still live after the first poll of this version has been stamped, so + /// an unstamped entry is stale and sorts oldest, evicted first. private mutating func trimToCap() { guard lastKnownModels.count > Self.maxTrackedSessions else { return } let overflow = lastKnownModels.count - Self.maxTrackedSessions let oldest = lastKnownModels.keys.sorted { - (lastObservedAt[$0] ?? .distantFuture) < (lastObservedAt[$1] ?? .distantFuture) + (lastObservedAt[$0] ?? .distantPast) < (lastObservedAt[$1] ?? .distantPast) }.prefix(overflow) for sessionId in oldest { lastKnownModels.removeValue(forKey: sessionId) diff --git a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift index 2268b864..b5ae16c9 100644 --- a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift @@ -147,6 +147,44 @@ final class MuseCodeStandardSessionDetectorTests: XCTestCase { XCTAssertNotNil(detector.lastKnownModels["overflow"]) } + func testModelLessPollsKeepASessionAlive() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1) + let ttl = MuseCodeStandardSessionDetector.sessionStateTTL + // Model-less polls every ten minutes for over a day: the session is + // present, so its liveness advances even without a model reading. + var t = TimeInterval(600) + while t <= ttl + 600 { + XCTAssertTrue(detector.observe([observation("s1", nil, at: t)]).isEmpty) + t += 600 + } + XCTAssertTrue(detector.observe([observation("s1", standardModel, at: t)]).isEmpty, + "a session kept alive by model-less polls is not evicted, so its model returning does not refire") + } + + func testEmptyPollStillEvictsSessionsPastTTL() { + var detector = MuseCodeStandardSessionDetector() + let stale = Date().addingTimeInterval(-MuseCodeStandardSessionDetector.sessionStateTTL - 600) + _ = detector.observe([MuseCodeSessionModelObservation(sessionId: "s1", modelId: contributorModel, + observedAt: stale)]) + XCTAssertEqual(detector.lastKnownModels.count, 1) + _ = detector.observe([]) + XCTAssertEqual(detector.lastKnownModels.count, 0, + "an idle poll still advances expiry against the wall clock") + } + + func testUnstampedLegacySessionsEvictBeforeStampedOnesAtCap() throws { + let legacy = try JSONSerialization.data(withJSONObject: ["lastKnownModels": ["old": standardModel]]) + var detector = try JSONDecoder().decode(MuseCodeStandardSessionDetector.self, from: legacy) + for i in 0.. Date: Tue, 10 Nov 2026 06:30:59 +0000 Subject: [PATCH 3/3] CC-390: cap model-less lastObservedAt orphan stamps (Kody round 2) --- .../MuseCodeStandardSessionDetector.swift | 30 ++++++++++++++----- ...MuseCodeStandardSessionDetectorTests.swift | 15 ++++++++++ 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift index cfecb6ed..565cf246 100644 --- a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift +++ b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift @@ -177,14 +177,28 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { /// still live after the first poll of this version has been stamped, so /// an unstamped entry is stale and sorts oldest, evicted first. private mutating func trimToCap() { - guard lastKnownModels.count > Self.maxTrackedSessions else { return } - let overflow = lastKnownModels.count - Self.maxTrackedSessions - let oldest = lastKnownModels.keys.sorted { - (lastObservedAt[$0] ?? .distantPast) < (lastObservedAt[$1] ?? .distantPast) - }.prefix(overflow) - for sessionId in oldest { - lastKnownModels.removeValue(forKey: sessionId) - lastObservedAt.removeValue(forKey: sessionId) + if lastKnownModels.count > Self.maxTrackedSessions { + let overflow = lastKnownModels.count - Self.maxTrackedSessions + let oldest = lastKnownModels.keys.sorted { + (lastObservedAt[$0] ?? .distantPast) < (lastObservedAt[$1] ?? .distantPast) + }.prefix(overflow) + for sessionId in oldest { + lastKnownModels.removeValue(forKey: sessionId) + lastObservedAt.removeValue(forKey: sessionId) + } + } + // Model-less sessions never enter lastKnownModels, so without this + // their liveness stamps would accumulate unbounded until the TTL. + // Evict the oldest orphan stamps once the map itself passes the cap; + // stamps that back a tracked session are left alone. + let orphanOverflow = lastObservedAt.count - Self.maxTrackedSessions + if orphanOverflow > 0 { + let orphans = lastObservedAt.keys + .filter { lastKnownModels[$0] == nil } + .sorted { (lastObservedAt[$0] ?? .distantPast) < (lastObservedAt[$1] ?? .distantPast) } + for sessionId in orphans.prefix(orphanOverflow) { + lastObservedAt.removeValue(forKey: sessionId) + } } } diff --git a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift index b5ae16c9..7c56f42a 100644 --- a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift @@ -147,6 +147,21 @@ final class MuseCodeStandardSessionDetectorTests: XCTestCase { XCTAssertNotNil(detector.lastKnownModels["overflow"]) } + func testModelLessOrphanStampsAreCappedToo() { + var detector = MuseCodeStandardSessionDetector() + let cap = MuseCodeStandardSessionDetector.maxTrackedSessions + for i in 0..<(cap + 100) { + _ = detector.observe([observation("orphan\(i)", nil, at: TimeInterval(i))]) + } + XCTAssertEqual(detector.lastKnownModels.count, 0, + "model-less sessions still record no model state") + XCTAssertEqual(detector.lastObservedAt.count, cap, + "orphan liveness stamps are capped like tracked sessions") + XCTAssertNil(detector.lastObservedAt["orphan0"], + "the least recently observed orphan stamp is evicted first") + XCTAssertNotNil(detector.lastObservedAt["orphan\(cap + 99)"]) + } + func testModelLessPollsKeepASessionAlive() { var detector = MuseCodeStandardSessionDetector() XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1)