forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContextProactivityEngine.swift
More file actions
1437 lines (1399 loc) · 66.3 KB
/
Copy pathContextProactivityEngine.swift
File metadata and controls
1437 lines (1399 loc) · 66.3 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
@preconcurrency import GRDB
struct ContextDirectorDecision: Codable, Equatable, Sendable {
let decision: String
let title: String
let message: String
let reasoning: String
let bucketEntryRefs: [String]
let factIDs: [String]
/// Request for the single retrieval hop; empty or absent means none.
///
/// Optional so a response predating this field still decodes: synthesized
/// `Decodable` uses `decodeIfPresent` for optionals. `var` with a default
/// keeps the memberwise initializer source-compatible for existing callers
/// (same pattern as `BucketExtraction.destination`).
var lookupQuery: String? = nil
/// Open tasks this notification is about, as supplied `task:<id>` handles.
///
/// Optional for the same reason as `lookupQuery`: a response predating the
/// field still decodes. Always filtered through
/// `ContextDirectorTaskRefs.resolvable` before it is stored or rendered.
var taskRefs: [String]? = nil
enum CodingKeys: String, CodingKey {
case decision, title, message, reasoning
case bucketEntryRefs = "bucket_entry_refs"
case factIDs = "fact_ids"
case lookupQuery = "lookup_query"
case taskRefs = "task_refs"
}
/// Retrieved-ref citations belong in `bucket_entry_refs`; the model
/// occasionally inlines them into the visible text ("... omi.me/desktop.
/// [memory:3fe5b70f-...]"), where they read as debris. Stripped
/// deterministically rather than re-prompted.
private static func strippingInlineRefs(_ text: String) -> String {
text.replacingOccurrences(
of: #"\s*\[(?:memory|conversation|chunk|entry|fact|task):[^\]]{1,200}\]"#,
with: "",
options: .regularExpression
).trimmingCharacters(in: .whitespacesAndNewlines)
}
func clamped(copyBudget: InterjectCopyBudget.Limits? = nil) -> ContextDirectorDecision {
let titleLimit = InterjectCopyBudget.clampedTitleLimit(copyBudget?.titleLimit ?? 120)
let messageLimit = InterjectCopyBudget.clampedMessageLimit(copyBudget?.messageLimit ?? 600)
return ContextDirectorDecision(
decision: decision,
title: String(Self.strippingInlineRefs(title).prefix(titleLimit)),
message: String(Self.strippingInlineRefs(message).prefix(messageLimit)),
reasoning: String(reasoning.prefix(1_200)),
bucketEntryRefs: bucketEntryRefs.prefix(20).map { String($0.prefix(200)) },
factIDs: factIDs.prefix(20).map { String($0.prefix(200)) },
lookupQuery: lookupQuery.map {
String($0.prefix(ContextDirectorRetrievalHop.maximumQueryLength))
},
taskRefs: taskRefs.map {
$0.prefix(ContextDirectorTaskRefs.maximumCount).map { String($0.prefix(200)) }
})
}
}
enum ContextDirectorEligibility {
static func permitsEvaluation(of snapshot: ContextBucketSnapshot) -> Bool {
snapshot.notifyWorthiness > 0 && !snapshot.validatedFacts.isEmpty
}
/// Planned JIT matching is grounded on validated facts, not director worthiness.
/// A standing Safari trigger still has to see a Safari fact whose
/// `notifyWorthiness` is 0. Ambient nano keeps the worthiness gate via
/// `JITAmbientRuntimeContext.locallyRelevant`.
static func permitsJITEvaluation(of snapshot: ContextBucketSnapshot) -> Bool {
!snapshot.validatedFacts.isEmpty
}
}
enum ContextProactivityVisitRoute: Equatable, Sendable {
case skip
case jitOnly
case jitThenLegacyDirector
}
enum ContextProactivityAdmissionOutcome: Equatable, Sendable {
case skipped
case jitConsumed
case legacyDirector
}
enum ContextProactivityVisitAdmission {
static func route(for snapshot: ContextBucketSnapshot) -> ContextProactivityVisitRoute {
guard ContextDirectorEligibility.permitsJITEvaluation(of: snapshot) else { return .skip }
if ContextDirectorEligibility.permitsEvaluation(of: snapshot) {
return .jitThenLegacyDirector
}
return .jitOnly
}
}
enum ContextDirectorGrounding {
/// Grounding requirement, per decision type.
///
/// The old rule demanded a bucket-entry ref AND a validated-fact ref for every
/// non-silence decision. But a resurface grounds on an *open task* — supplied
/// in the prompt, not citable as a bucket entry — connected to the current
/// context, so its natural citation is the validated fact(s) evidencing the
/// connection, with no entry ref at all. Measured on two independent
/// installations: every suppressed row with non-empty fact_ids is a decision
/// the model made to speak that this guard overrode (the silence path forcibly
/// empties fact_ids), and there were 9 of them in our dogfood window and 7 of
/// 76 on an independent beta install — including "This is an overdue open task
/// with a timely connection to the active overnight fleetctl workflow", the
/// exact class resurface exists for. Cross-workstream pooling being enabled
/// did not prevent the vetoes, so the guard itself was the cause.
///
/// Deliberately NOT relaxed to a blanket OR: insight, suggest, and
/// task_candidate make new claims about bucket content and keep the full
/// anti-hallucination invariant (at least one entry ref and one fact ref).
/// Resurface requires at least one citation of either kind — never zero.
///
/// Retrieved refs are the one exception, for insight and suggest only. A
/// retrieved ref validates against the allowlist of items the retrieval hop
/// quoted to this very call, so it carries the same anti-hallucination
/// guarantee as a bucket citation — but for content that by construction has
/// no bucket entry or fact (the answer to a question the user is writing
/// lives in their history, not in this screen's bucket). Before this
/// exception, every retrieval-hop answer was structurally undeliverable:
/// 10 of 10 hop evaluations in one 48h dogfood window ended suppressed,
/// including one whose reasoning said the retrieved context "directly helps".
/// task_candidate and resurface stay bucket-grounded: neither is the
/// answer-delivery case, so each keeps its existing invariant unchanged.
static func permitsNonSilence(
decision: String, entryRefs: [String], factIDs: [String], retrievedRefs: [String] = []
) -> Bool {
if decision == "resurface" {
return !entryRefs.isEmpty || !factIDs.isEmpty
}
if decision == "insight" || decision == "suggest", !retrievedRefs.isEmpty {
return true
}
return !entryRefs.isEmpty && !factIDs.isEmpty
}
}
enum ContextDirectorTaskSelection {
static let maximumCount = 20
static let futureHorizon: TimeInterval = 48 * 60 * 60
static func select(from tasks: [TaskActionItem], now: Date) -> [ContextDirectorTaskContext] {
let cutoff = now.addingTimeInterval(futureHorizon)
return
tasks
.filter { task in
!task.completed && !task.isRetired && !task.isPendingSuggestion
}
.sorted { lhs, rhs in
let leftIsReference = lhs.dueAt.map { $0 > cutoff } ?? false
let rightIsReference = rhs.dueAt.map { $0 > cutoff } ?? false
if leftIsReference != rightIsReference { return !leftIsReference }
let left = lhs.dueAt ?? .distantFuture
let right = rhs.dueAt ?? .distantFuture
if left != right { return left < right }
return lhs.createdAt > rhs.createdAt
}
.prefix(maximumCount)
.map { ContextDirectorTaskContext(id: $0.id, description: $0.description, dueAt: $0.dueAt) }
}
}
actor ContextProactivityEngine {
static let shared = ContextProactivityEngine(client: .shared, store: .shared)
typealias JITHandle =
@Sendable (
ContextVisitFence, ContextBucketSnapshot, CapturedFrame, RuntimeOwnerAuthorizationSnapshot
) async -> Bool
private let client: ProactiveLaneClient
private let store: ContextBucketStore
private let presentationPreflight: @Sendable (String) async -> OwnerBoundNotificationPresentationResult
private let retrieve: @Sendable (String, RuntimeOwnerAuthorizationSnapshot) async -> [ContextRetrievedItem]
private let jitHandle: JITHandle
private var dwellAdmission = ContextVisitDwellAdmission()
private let dwellNanoseconds: UInt64
init(
client: ProactiveLaneClient,
store: ContextBucketStore,
dwellNanoseconds: UInt64 = 2_000_000_000,
presentationPreflight: @escaping @Sendable (String) async -> OwnerBoundNotificationPresentationResult = {
ownerID in
await NotificationService.shared.contextDirectorPresentationPreflight(ownerID: ownerID)
},
retrieve: @escaping @Sendable (String, RuntimeOwnerAuthorizationSnapshot) async -> [ContextRetrievedItem] = {
query, authorizationSnapshot in
await ContextDirectorRetrievalExecutor.retrieve(
query: query, authorizationSnapshot: authorizationSnapshot)
},
jitHandle: @escaping JITHandle = { fence, snapshot, frame, authorizationSnapshot in
await JITProactivityCoordinator.shared.handle(
fence: fence, snapshot: snapshot, frame: frame,
authorizationSnapshot: authorizationSnapshot)
}
) {
self.client = client
self.store = store
self.dwellNanoseconds = dwellNanoseconds
self.presentationPreflight = presentationPreflight
self.retrieve = retrieve
self.jitHandle = jitHandle
}
func contextEntered(_ fence: ContextVisitFence) async {
guard fence.bucketID != nil else { return }
guard let authorizationSnapshot = RuntimeOwnerIdentity.captureAuthorizationSnapshot() else { return }
guard dwellAdmission.begin(visitID: fence.visitID) else { return }
defer { dwellAdmission.finish(visitID: fence.visitID) }
do { try await Task.sleep(nanoseconds: dwellNanoseconds) } catch { return }
guard RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot) else { return }
do { try await store.markVisitSettled(fence) } catch { return }
guard RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot) else { return }
let gate = await MainActor.run { Self.liveDeliveryGateInput() }
// Settle the visit so quiet-period activity remains part of the context ledger, then stop
// before snapshot assembly, frame lookup, task projection, or the director model request.
let preflightReason = ContextDeliveryBudget.freeGate(input: gate)
guard preflightReason == .allowed else {
log("Context director suppressed before preparation: \(preflightReason.rawValue)")
await ContextProactivityTelemetry.recordGateRejection(reason: preflightReason, stage: .preflight)
return
}
// Run-to-completion: a settled visit's evaluation survives a context switch
// for a bounded window (the visit stays "fresh" while active or briefly
// after a completed departure), so fast task-switchers can still receive
// what their quota already paid for. Every later stage re-checks freshness.
let freshness = await store.fenceFreshness(fence)
guard
RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot),
freshness.fresh,
let snapshot = await store.snapshot(for: fence)
else { return }
// Validated facts are enough to run planned JIT matching. A bucket of
// ambient narrative alone still cannot purchase a frontier-model call;
// `admitJITThenLegacyDirector` keeps that worthiness gate on the director.
guard ContextProactivityVisitAdmission.route(for: snapshot) != .skip else { return }
// After a departure the latest tracked frame can be the NEXT context's
// screen. Sample the frame first, then re-read freshness and bound the
// sample against it: the transition persists `endedAt` before the next
// context's frame is tracked, so a bound applied to a post-sampling
// freshness read cannot admit the wrong screen — while a bound computed
// from the pre-snapshot read above could, when the switch lands between
// that read and this lookup.
guard
let frameSample = await MainActor.run(body: {
AssistantCoordinator.shared.trackedFrameForDirector(startedAt: fence.startedAt)
})
else { return }
let frameFreshness = await store.fenceFreshness(fence)
guard
frameFreshness.fresh,
AssistantCoordinator.frameMayGroundDirector(
captureTime: frameSample.frame.captureTime,
storedAt: frameSample.storedAt,
startedAt: fence.startedAt,
endedAt: frameFreshness.endedAt)
else { return }
await admitJITThenLegacyDirector(
fence: fence,
snapshot: snapshot,
frame: frameSample.frame,
authorizationSnapshot: authorizationSnapshot)
}
/// Departure-triggered evaluation: a departure extraction that just validated
/// a notify-worthy fact evaluates the departed bucket immediately, grounded
/// on the departing frame the extraction already holds, instead of waiting
/// for the next revisit's dwell. Callers gate on
/// `ContextDepartureEvaluationPolicy`; every delivery gate below and the
/// freshness window still apply, so a departure older than the validity
/// window dies exactly like any other stale evaluation. The dwell admission
/// set serializes this against a still-running `contextEntered` evaluation of
/// the same visit.
func evaluateAfterDeparture(fence: ContextVisitFence, departingFrame: CapturedFrame) async {
guard fence.bucketID != nil else { return }
guard let authorizationSnapshot = RuntimeOwnerIdentity.captureAuthorizationSnapshot() else {
log("DepartureEvalDebug: no authorization snapshot")
return
}
guard dwellAdmission.begin(visitID: fence.visitID) else {
log("DepartureEvalDebug: dwell admission refused for visit \(fence.visitID)")
return
}
defer { dwellAdmission.finish(visitID: fence.visitID) }
let gate = await MainActor.run { Self.liveDeliveryGateInput() }
let preflightReason = ContextDeliveryBudget.freeGate(input: gate)
guard preflightReason == .allowed else {
log("Context director suppressed before departure evaluation: \(preflightReason.rawValue)")
return
}
let freshness = await store.fenceFreshness(fence)
guard RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot) else {
log("DepartureEvalDebug: authorization changed")
return
}
guard freshness.fresh else {
log("DepartureEvalDebug: fence stale")
return
}
guard let snapshot = await store.snapshot(for: fence) else {
log("DepartureEvalDebug: no snapshot")
return
}
let route = ContextProactivityVisitAdmission.route(for: snapshot)
guard route != .skip else {
log(
"DepartureEvalDebug: ineligible snapshot worthiness=\(snapshot.notifyWorthiness) facts=\(snapshot.validatedFacts.count)"
)
return
}
_ = await admitJITThenLegacyDirector(
fence: fence,
snapshot: snapshot,
frame: departingFrame,
authorizationSnapshot: authorizationSnapshot)
}
/// Shared post-snapshot tail: planned JIT may run on validated facts even at
/// zero worthiness; the legacy director still requires positive worthiness.
@discardableResult
func admitJITThenLegacyDirector(
fence: ContextVisitFence,
snapshot: ContextBucketSnapshot,
frame: CapturedFrame,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async -> ContextProactivityAdmissionOutcome {
let route = ContextProactivityVisitAdmission.route(for: snapshot)
guard route != .skip else { return .skipped }
if await jitHandle(fence, snapshot, frame, authorizationSnapshot) {
return .jitConsumed
}
guard route == .jitThenLegacyDirector else { return .skipped }
await evaluateAndDeliver(
fence: fence,
snapshot: snapshot,
currentFrame: frame,
authorizationSnapshot: authorizationSnapshot)
return .legacyDirector
}
/// The shared post-settle tail of the director pipeline: presentation
/// preflight, gate rebuilds, budget reservation, the model call (plus the
/// bounded retrieval hop), grounding validation, and the presentation
/// handoff. `contextEntered` reaches it after dwell/settle/frame lookup;
/// `evaluateAfterDeparture` reaches it with the departing frame.
private func evaluateAndDeliver(
fence: ContextVisitFence,
snapshot: ContextBucketSnapshot,
currentFrame: CapturedFrame,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async {
guard let ownerID = await MainActor.run(body: { RuntimeOwnerIdentity.currentOwnerId() }) else { return }
let attemptPreflight = await presentationPreflight(ownerID)
guard Self.presentationSurfaceAvailable(attemptPreflight) else {
log("Context director suppressed before attempt: presentation_unavailable")
return
}
let attemptGate = await MainActor.run { Self.liveDeliveryGateInput() }
let attemptReason = ContextDeliveryBudget.freeGate(input: attemptGate)
guard attemptReason == .allowed else {
log("Context director suppressed before attempt: \(attemptReason.rawValue)")
await ContextProactivityTelemetry.recordGateRejection(reason: attemptReason, stage: .attempt)
return
}
let attempt: ContextDeliveryAttempt
do {
attempt = try await store.beginDeliveryAttempt(fence: fence, snapshot: snapshot, gate: attemptGate)
} catch { return }
guard attempt.reason == .allowed, let deliveryID = attempt.id else {
log("Context director suppressed: \(attempt.reason.rawValue)")
await ContextProactivityTelemetry.recordGateRejection(reason: attempt.reason, stage: .reservation)
return
}
guard RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot) else {
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"stale_owner\"}",
state: "failed")
return
}
let taskContext = await MainActor.run {
ContextDirectorTaskSelection.select(
from: TasksStore.shared.incompleteTasks,
now: currentFrame.captureTime)
}
var recentDeliveries = await store.recentDeliveredForBucket(
bucketID: snapshot.bucketID, now: currentFrame.captureTime)
// The related-workstream section: validated facts from sibling buckets of
// the visit's live workstream, quality-gated and quoted as non-citable
// context. Read the flag once so section, dedup, and provenance agree; with
// the flag off (or no live tag) the prompt is byte-identical to today.
let workstreamPoolingEnabled = await MainActor.run {
ContextBucketsFeature.isWorkstreamPoolingEnabled
}
var workstreamSection: String? = nil
var workstreamProvenance: [String: Any]? = nil
var pooledFactIDs: Set<String> = []
if workstreamPoolingEnabled,
let liveTag = await store.liveWorkstreamTag(for: fence, now: currentFrame.captureTime)
{
let selected = ContextWorkstreamPooling.select(
await store.workstreamPool(
tag: liveTag, excludingBucketID: snapshot.bucketID, now: currentFrame.captureTime),
now: currentFrame.captureTime)
if !selected.isEmpty {
workstreamSection = ContextWorkstreamPooling.promptSection(
tag: liveTag, items: selected, now: currentFrame.captureTime)
pooledFactIDs = Set(selected.map(\.factID))
workstreamProvenance = [
"tag": liveTag,
"pooled_fact_ids": selected.map(\.factID),
]
}
// Tag-aware dedup: with pooling, the same cross-app point is reachable
// from every bucket carrying this tag, so sibling deliveries join the
// bucket's own under the same prompt cap.
let workstreamDeliveries = await store.recentDeliveredForWorkstream(
tag: liveTag, excludingBucketID: snapshot.bucketID, now: currentFrame.captureTime)
recentDeliveries = Array(
(recentDeliveries + workstreamDeliveries)
.sorted { $0.deliveredAt > $1.deliveredAt }
.prefix(ContextBucketRecentDelivery.promptCap))
}
let candidatesEnabled = await MainActor.run {
ContextBucketsFeature.isProactiveCandidatesEnabled
}
if candidatesEnabled {
let tags = await store.workstreamTags(for: snapshot.bucketID)
if !tags.isEmpty {
// Lookup is cross-bucket by durable assignment; bucket-scoped delivery
// memory would re-send a sibling's already-shown point.
let assignedDeliveries = await store.recentDeliveredForAssignedWorkstreams(
tags: tags, excludingBucketID: snapshot.bucketID, now: currentFrame.captureTime)
recentDeliveries = Array(
(recentDeliveries + assignedDeliveries)
.sorted { $0.deliveredAt > $1.deliveredAt }
.prefix(ContextBucketRecentDelivery.promptCap))
}
let armed = await store.armedCandidates(
bucketID: snapshot.bucketID, tags: tags, now: currentFrame.captureTime)
// A candidate can sit armed for up to 12 hours; the fact(s) it was
// grounded in at write time may since have expired, been rejected, or
// been superseded. Revalidate every grounding id against the current
// bucket_facts state before treating a candidate as deliverable, so a
// decayed candidate falls through to the director instead of gating
// and presenting stale text with stale citations. Decline the stale
// row so it cannot block the reconciler from writing a replacement.
var grounded: [ContextProactiveCandidate] = []
for candidate in armed {
if await store.groundingFactIDsAreCurrentlyValid(
candidate.groundingFactIDs, bucketID: candidate.bucketID, now: currentFrame.captureTime)
{
grounded.append(candidate)
} else {
await store.declineCandidate(id: candidate.id, now: currentFrame.captureTime)
}
}
let recentMessages = recentDeliveries.compactMap(\.message)
// A question the user is typing RIGHT NOW outranks resurfacing an armed
// candidate: the candidate short-circuit used to consume the evaluation
// (and with the candidate show ceiling exhausted, silence it), so the
// typed question never reached the director or its forced retrieval —
// the bucket went permanently mute for answers while any candidate
// stayed armed. The candidate stays armed for the next quiet evaluation.
let pendingUserQuestion =
await MainActor.run { ContextBucketsFeature.isRetrievalHopEnabled }
&& ContextDirectorRetrievalHop.forcedLookupQuery(
validatedFacts: snapshot.validatedFacts) != nil
if !pendingUserQuestion,
let candidate = ContextProactiveCandidateLookup.firstDeliverable(
candidates: grounded, recentMessages: recentMessages)
{
await evaluateCandidateAndDeliver(
candidate: candidate,
deliveryID: deliveryID,
fence: fence,
snapshot: snapshot,
currentFrame: currentFrame,
recentDeliveries: recentDeliveries,
authorizationSnapshot: authorizationSnapshot,
ownerID: ownerID)
return
}
}
// Read once and use for the whole visit: schema, prompt, and hop admission
// must agree, and a mid-visit flag flip must not desynchronize them. With
// the flag off, schema and prompt are byte-identical to the pre-hop build.
let retrievalHopEnabled = await MainActor.run { ContextBucketsFeature.isRetrievalHopEnabled }
let interjectCopyBudgets = await MainActor.run { InterjectFeature.isEnabled }
if !retrievalHopEnabled {
let diag = await MainActor.run {
"enabled=\(ContextBucketsFeature.isEnabled) nonprod=\(AppBuild.isNonProduction) env=\(ProcessInfo.processInfo.environment["OMI_FORCE_BUCKET_RETRIEVAL"] ?? "unset")"
}
log("ForcedLookupDebug: retrieval hop DISABLED (\(diag))")
}
let prompt = ContextProactivityPromptBuilder.directorStablePrompt(
snapshot: snapshot,
allowLookup: retrievalHopEnabled,
includeInterjectCopyBudgets: interjectCopyBudgets)
let envSignal = await MainActor.run {
EnvironmentalSpeakerAnalyzer.analyze(segments: LiveTranscriptMonitor.shared.segments)
}
var volatileExtras = workstreamSection.map { "\n\n" + $0 } ?? ""
if candidatesEnabled {
let selected = ContextWorkstreamPooling.selectRecent(
await store.recentContextPool(
excludingBucketID: snapshot.bucketID, now: currentFrame.captureTime),
now: currentFrame.captureTime)
let fresh = selected.filter { !pooledFactIDs.contains($0.factID) }
if let section = ContextWorkstreamPooling.recentContextPromptSection(
items: fresh, now: currentFrame.captureTime)
{
volatileExtras += "\n\n" + section
}
}
let uncachedPrompt =
ContextProactivityPromptBuilder.directorVolatilePrompt(
tasks: taskContext,
frame: currentFrame,
recentDeliveries: recentDeliveries,
visitCount: snapshot.visitCount,
environmentalSignal: envSignal)
+ volatileExtras
guard
RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot),
await store.fenceFreshness(fence).fresh
else {
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"stale_visit\"}",
state: "failed")
return
}
// Settings can change while snapshot/frame/task context is assembled. Rebuild the
// free gate immediately before the paid model call so disabling notifications,
// snoozing, or becoming paywalled never spends director budget.
let evaluationGate = await MainActor.run { Self.liveDeliveryGateInput() }
let evaluationReason = ContextDeliveryBudget.freeGate(input: evaluationGate)
guard evaluationReason == .allowed else {
log("Context director suppressed before model: \(evaluationReason.rawValue)")
await ContextProactivityTelemetry.recordGateRejection(reason: evaluationReason, stage: .preModel)
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"pre_model_gate\"}",
state: "suppressed")
return
}
let cacheKey = ContextPromptCacheKey.director
// Forced retrieval: a validated user-authored-question fact skips the
// first bare call and evaluates once WITH the retrieved answer attached.
// The bare first call proved stochastically willing to silence a typed
// question on the repetition/already-visible checks across live runs,
// while the retrieval-attached form delivered every time — so when the
// client can already see the question in the validated facts, asking the
// model whether to look it up is a coin flip that costs the delivery.
var forcedRetrievalAllowlist: Set<String> = []
var forcedRetrievalItems: [ContextRetrievedItem] = []
var forcedRetrievalProvenance: [String: Any]? = nil
var forcedLookup: ContextDirectorRetrievalHop.ForcedLookup? = nil
var effectiveUncachedPrompt = uncachedPrompt
if retrievalHopEnabled {
log("ForcedLookupDebug: facts=\(snapshot.validatedFacts.count)")
}
if retrievalHopEnabled,
let lookup = ContextDirectorRetrievalHop.forcedLookupQuery(
validatedFacts: snapshot.validatedFacts)
{
log(
"ForcedLookupDebug: firing queryChars=\(lookup.query.count) questionFacts=\(lookup.questionFactIDs.count)"
)
forcedLookup = lookup
let items = await retrieve(lookup.query, authorizationSnapshot)
if let section = ContextDirectorRetrievalHop.promptSection(query: lookup.query, items: items) {
// A direct question invalidates the anti-nagging guard by design, and
// in live runs the model kept reading the identical answer cards in
// the recent-deliveries list as "delivered repeatedly" and silencing.
// The forced evaluation therefore omits that list mechanically instead
// of asking the model to discount it. Every other volatile section
// (workstream, recent-context pool) is preserved so pooling context
// and its provenance stay truthful.
let answerPrompt = ContextProactivityPromptBuilder.directorVolatilePrompt(
tasks: taskContext,
frame: currentFrame,
recentDeliveries: [],
visitCount: snapshot.visitCount,
environmentalSignal: envSignal)
effectiveUncachedPrompt = answerPrompt + volatileExtras + "\n\n" + section
forcedRetrievalAllowlist = Set(items.map(\.ref))
forcedRetrievalItems = items
forcedRetrievalProvenance = ContextDirectorRetrievalHop.provenance(
query: lookup.query, items: items, citedRefs: [], hopCompleted: true, failure: nil)
}
}
do {
var result = try await client.complete(
operation: ModelQoS.Proactivity.reasoningOperation,
prompt: prompt,
uncachedPrompt: effectiveUncachedPrompt,
imageData: currentFrame.jpegData,
jsonSchema: Self.schema(allowLookup: retrievalHopEnabled),
cacheKey: cacheKey,
maxCompletionTokens: ProactiveLaneClient.backendCompatibleReasoningMinimumCompletionTokens,
authorizationSnapshot: authorizationSnapshot)
await ContextProactivityTelemetry.record(result)
guard
RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot),
await store.fenceFreshness(fence).fresh
else {
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"stale_visit\"}",
state: "failed")
return
}
let firstRaw = try JSONDecoder().decode(
ContextDirectorDecision.self, from: Data(result.content.utf8))
let firstDecision = firstRaw.clamped(
copyBudget: interjectCopyBudgets ? InterjectCopyBudget.limits(for: firstRaw.decision) : nil)
var decision = firstDecision
var retrievedRefAllowlist: Set<String> = forcedRetrievalAllowlist
var retrievalProvenance: [String: Any]? = forcedRetrievalProvenance
// The single bounded retrieval hop: at most one retrieval and one further
// director call per visit, and only when the director asked for one.
// `plan` is the sole admission and this is the sole second call site, so
// a second response requesting another lookup has nowhere to loop to.
if let lookupQuery = ContextDirectorRetrievalHop.plan(
lookupQuery: firstDecision.lookupQuery,
flagEnabled: retrievalHopEnabled,
priorHops: forcedLookup == nil ? 0 : 1)
{
let hop = await performRetrievalHop(
query: lookupQuery,
stablePrompt: prompt,
volatilePrompt: uncachedPrompt,
imageData: currentFrame.jpegData,
cacheKey: cacheKey,
fence: fence,
authorizationSnapshot: authorizationSnapshot,
includeInterjectCopyBudgets: interjectCopyBudgets)
// A failed, empty, or gated hop keeps the first decision untouched:
// retrieval may upgrade a decision, never lose one.
decision = ContextDirectorRetrievalHop.finalDecision(
first: firstDecision, second: hop.decision)
retrievedRefAllowlist = hop.allowedRefs
retrievalProvenance = hop.provenance
if let secondResult = hop.result { result = secondResult }
// The owner/fence guard above ran before the hop, and the hop spans a
// retrieval round trip plus a second model call. Ownership can be revoked
// or the visit can end inside that window, so the same guard must run
// again before anything is persisted — otherwise falling back to the
// first decision would deliver against context the pre-hop code would
// have refused. Re-checked here rather than trusting the hop to report
// staleness, so a future failure path cannot quietly bypass it.
guard
RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot),
await store.fenceFreshness(fence).fresh
else {
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"stale_visit\"}",
state: "failed")
return
}
}
// Bucket refs keep today's validation path untouched; retrieved-namespace
// refs validate only against the allowlist of items quoted to this very
// call, which is empty unless the hop completed.
let citedRefs = ContextDirectorRetrievalHop.partitionCitedRefs(decision.bucketEntryRefs)
let entryRefs = await store.validatedEntryRefs(
citedRefs.bucket, bucketID: snapshot.bucketID)
var retrievedRefs = ContextDirectorRetrievalHop.validatedRetrievedRefs(
citedRefs.retrieved, allowed: retrievedRefAllowlist)
// Forced-question answers: attribute the citation the model omitted when
// the message provably carries retrieved content (see impliedCitations).
if retrievedRefs.isEmpty, !forcedRetrievalItems.isEmpty,
decision.decision == "insight" || decision.decision == "suggest"
{
retrievedRefs = ContextDirectorRetrievalHop.impliedCitations(
message: decision.message, items: forcedRetrievalItems,
question: forcedLookup?.query ?? "")
}
let factIDs =
decision.decision == "silence"
? []
: await store.validatedFactIDs(
decision.factIDs,
snapshotFacts: snapshot.validatedFacts,
bucketID: snapshot.bucketID)
// Filtered against the tasks actually supplied on this visit. An invented
// handle would render in chat as a "Task is no longer available"
// tombstone instead of failing visibly, so an unresolvable ref is dropped
// here rather than stored. Silence carries none, matching `factIDs`.
let taskRefs =
decision.decision == "silence"
? []
: ContextDirectorTaskRefs.resolvable(decision.taskRefs ?? [], supplied: taskContext)
var provenance: [String: Any] = [
"bucket_id": snapshot.bucketID,
"bucket_version_id": snapshot.versionID,
"bucket_entry_refs": entryRefs,
"fact_ids": factIDs,
"task_refs": taskRefs,
"reasoning": decision.reasoning,
"provider_model": ContextProactivityTelemetry.boundedProviderModel(result.providerModel),
"cached_tokens": result.usage.cachedTokens,
"cache_write_tokens": result.usage.cacheWriteTokens,
]
if var hopProvenance = retrievalProvenance {
hopProvenance["cited_refs"] = retrievedRefs
provenance["retrieval"] = hopProvenance
}
if let workstreamProvenance {
provenance["workstream"] = workstreamProvenance
}
let provenanceData = try JSONSerialization.data(withJSONObject: provenance, options: [.sortedKeys])
let provenanceJSON = String(data: provenanceData, encoding: .utf8) ?? "{}"
try await store.completeDelivery(
id: deliveryID, decisionType: decision.decision, provenanceJSON: provenanceJSON,
message: decision.message, state: "model_completed")
await ContextProactivityTelemetry.recordDirectorDecision(decision.decision)
if decision.decision == "silence" {
try await store.completeDelivery(
id: deliveryID, decisionType: decision.decision, provenanceJSON: provenanceJSON,
message: nil, state: "suppressed")
if forcedLookup == nil {
// Silence with no forced lookup right after typing is the signature
// of an extraction that missed the typed question; the plugin may
// grant one re-extraction for the burst (see
// ContextDwellRefreshPolicy.questionRescueGrant).
await MainActor.run {
NotificationCenter.default.post(
name: ProactiveAssistantsPlugin.contextEvalSilentWithoutLookup, object: nil)
}
}
return
}
// Retrieved refs are hop-allowlist-validated above, so an insight or
// suggest citing one is grounded in content actually quoted to the model
// — the answer-delivery case bucket refs cannot cover. When the guard
// vetoes, the row records what the model actually decided and why it was
// suppressed — a forced silence was previously indistinguishable from a
// model-chosen one, which made the veto rate invisible until it was
// recovered from the fact_ids side effect.
guard
ContextDirectorGrounding.permitsNonSilence(
decision: decision.decision, entryRefs: entryRefs, factIDs: factIDs,
retrievedRefs: retrievedRefs)
else {
provenance["suppression_reason"] = "grounding_veto"
provenance["model_decision"] = decision.decision
let vetoData = try JSONSerialization.data(withJSONObject: provenance, options: [.sortedKeys])
try await store.completeDelivery(
id: deliveryID, decisionType: "silence",
provenanceJSON: String(data: vetoData, encoding: .utf8) ?? provenanceJSON,
message: nil, state: "suppressed")
return
}
try await store.completeDelivery(
id: deliveryID, decisionType: decision.decision, provenanceJSON: provenanceJSON,
message: decision.message, state: "policy_approved")
guard
RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot),
await store.fenceFreshness(fence).fresh,
let ownerID = await MainActor.run(body: { RuntimeOwnerIdentity.currentOwnerId() })
else {
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"stale_visit\"}",
state: "failed")
return
}
// Rebuild free-gate inputs immediately before presentation so a mid-flight
// master-off / quiet-hours / snooze / paywall change still suppresses.
let presentationGate = await MainActor.run { Self.liveDeliveryGateInput() }
let presentationReason = ContextDeliveryBudget.freeGate(input: presentationGate)
guard presentationReason == .allowed else {
log("Context director suppressed before presentation: \(presentationReason.rawValue)")
await ContextProactivityTelemetry.recordGateRejection(
reason: presentationReason, stage: .presentation)
try await store.completeDelivery(
id: deliveryID, decisionType: decision.decision, provenanceJSON: provenanceJSON,
message: decision.message, state: "suppressed")
return
}
let finalPresentationPreflight = await presentationPreflight(ownerID)
guard finalPresentationPreflight == .queued else {
log("Context director suppressed before graduation: presentation_unavailable")
try await store.completeDelivery(
id: deliveryID,
decisionType: decision.decision,
provenanceJSON: provenanceJSON,
message: decision.message,
state: "suppressed")
return
}
// Durable canonical candidates must exist before an interactive
// task_candidate notification can be queued or tapped.
var graduation = CandidateGraduationReason.graduated
if decision.decision == "task_candidate" {
graduation = await CandidateSink.shared.graduateValidatedFacts(
deliveryID: deliveryID,
factIDs: factIDs,
authorizationSnapshot: authorizationSnapshot)
}
guard
CandidateSinkDeliveryGate.mayPresentInteractively(
decisionType: decision.decision,
graduation: graduation)
else {
await recordGraduationFailure(
deliveryID: deliveryID,
decisionType: decision.decision,
provenanceJSON: provenanceJSON,
message: decision.message,
reason: graduation)
return
}
// Graduation and system-surface preflight can both await. Rebuild every
// free gate once more at the actual handoff so master-off, snooze, paywall,
// or another proactive presentation wins the race.
let handoffGate = await MainActor.run { Self.liveDeliveryGateInput() }
let handoffReason = ContextDeliveryBudget.freeGate(input: handoffGate)
guard handoffReason == .allowed else {
await ContextProactivityTelemetry.recordGateRejection(reason: handoffReason, stage: .handoff)
try await store.completeDelivery(
id: deliveryID, decisionType: decision.decision, provenanceJSON: provenanceJSON,
message: decision.message, state: "suppressed")
return
}
// The bounded hop is the last writer of `decision`, so hand the main actor
// the settled value rather than this actor's mutable binding: the callbacks
// below outlive the handoff, and capturing the variable makes their reads
// race with any later write to it.
let answeredQuestionFactIDs = ContextDirectorRetrievalHop.consumableQuestionFacts(
forced: forcedLookup,
retrievalCompleted: forcedRetrievalProvenance != nil,
citedRetrievedRefs: retrievedRefs)
let presentedDecision = decision
let presentation = await MainActor.run {
let context = FloatingBarNotificationContext(
sourceTitle: presentedDecision.title,
assistantId: "context-director",
contextSummary: presentedDecision.reasoning,
detail: (entryRefs + retrievedRefs).joined(separator: ", "),
provenanceRef: deliveryID)
return NotificationService.shared.presentContextDirectorNotification(
ownerID: ownerID,
title: presentedDecision.title,
message: presentedDecision.message,
decisionType: presentedDecision.decision,
context: context,
onPresented: { [weak self] in
guard let self else { return }
Task {
await self.completePresentedDelivery(
deliveryID: deliveryID,
decisionType: presentedDecision.decision,
provenanceJSON: provenanceJSON,
message: presentedDecision.message,
authorizationSnapshot: authorizationSnapshot,
consumeFactIDs: answeredQuestionFactIDs)
}
},
onDropped: { [weak self] in
guard let self else { return }
Task {
await self.terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"notification_dropped\"}",
state: "failed")
}
})
}
switch presentation {
case .presented:
// Immediate presentation invokes onPresented; queued presentation invokes it later.
return
case .queued:
// Keep the row policy-approved until the floating bar actually presents it.
return
case .suppressed, .windowUnavailable, .rejectedOwnerChange:
// showNotification invokes onDropped exactly once for these refusal paths.
return
}
} catch {
await recordDirectorFailure(deliveryID: deliveryID, error: error)
// Network and model failures stay user-silent; provenance carries the class.
}
}
/// Deterministic candidate + small yes/no gate. `show == false` (or a
/// malformed/failed gate) suppresses and returns — the director is not also
/// run, so one visit never pays for two decisions.
private func evaluateCandidateAndDeliver(
candidate: ContextProactiveCandidate,
deliveryID: String,
fence: ContextVisitFence,
snapshot: ContextBucketSnapshot,
currentFrame: CapturedFrame,
recentDeliveries: [ContextBucketRecentDelivery],
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot,
ownerID: String
) async {
let evaluationGate = await MainActor.run { Self.liveDeliveryGateInput() }
let evaluationReason = ContextDeliveryBudget.freeGate(input: evaluationGate)
guard evaluationReason == .allowed else {
log("Context candidate gate suppressed before model: \(evaluationReason.rawValue)")
await ContextProactivityTelemetry.recordGateRejection(reason: evaluationReason, stage: .preModel)
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"pre_model_gate\"}",
state: "suppressed")
return
}
// Candidate-mix ceiling, checked before the gate's model call so a capped
// candidate costs no tokens. The candidate is deliberately NOT declined:
// it stays armed for a window with headroom, unlike a gate refusal, which
// retires it. The visit's delivery row still terminates as suppressed.
let candidateShows = await store.candidateDeliveriesInWindow(now: currentFrame.captureTime)
guard candidateShows < ContextDeliveryBudget.candidateDailyShowCeiling else {
log("Context candidate suppressed before model: candidate_show_ceiling")
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"candidate_show_ceiling\"}",
state: "suppressed")
// A ceiling-capped candidate consumed an evaluation that may have been
// owed to a typed question the extraction missed — the same rescue as a
// silent director evaluation applies.
await MainActor.run {
NotificationCenter.default.post(
name: ProactiveAssistantsPlugin.contextEvalSilentWithoutLookup, object: nil)
}
return
}
guard
RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot),
await store.fenceFreshness(fence).fresh
else {
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"stale_visit\"}",
state: "failed")
return
}
// The facts the candidate was written from, not just this visit's facts:
// the gate is judging a claim made at write time, and without its original
// evidence it could only compare the claim against the current screen —
// which is how 13 of 14 live rejections came to read "not supported by the
// current screen" for candidates that were correct when written.
let groundingFacts = await store.groundingFactStatements(
candidate.groundingFactIDs, bucketID: candidate.bucketID)
do {
let result = try await client.complete(
operation: ModelQoS.Proactivity.reasoningOperation,
prompt: ContextProactiveCandidateGate.prompt(
message: candidate.message,
groundingFacts: groundingFacts,
validatedFacts: snapshot.validatedFacts,
recentDeliveries: recentDeliveries),
imageData: currentFrame.jpegData,
jsonSchema: ContextProactiveCandidateGate.schema,
// The backend-compatible floor applies to every reasoning request. The
// reasoning model bills its thinking into completion tokens, so a small
// client cap can finish with `finish_reason=length` and empty content,
// which parses as malformed and silently suppresses the
maxCompletionTokens: ProactiveLaneClient.backendCompatibleReasoningMinimumCompletionTokens,
authorizationSnapshot: authorizationSnapshot)
await ContextProactivityTelemetry.record(result)
// The gate awaited the model; ownership can be revoked or the visit can
// end inside that window, exactly as for the director's own call.
// Re-check before parsing or persisting anything.
guard
RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot),
await store.fenceFreshness(fence).fresh
else {
await terminalize(
deliveryID: deliveryID,
decisionType: "silence",
provenanceJSON: "{\"failure\":\"stale_visit\"}",
state: "failed")