forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcandidates.py
More file actions
370 lines (331 loc) · 14.9 KB
/
Copy pathcandidates.py
File metadata and controls
370 lines (331 loc) · 14.9 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
"""Canonical Candidate lifecycle API."""
from datetime import datetime, timezone
from typing import Annotated, Literal, Optional
from fastapi import APIRouter, Depends, Header, HTTPException, Query, status
import database.candidates as candidates_db
import database.task_recommendations as recommendation_db
import database.task_intelligence_control as task_control_db
from models.action_item import TaskCreatePayload
from models.candidate import (
CandidateAction,
CandidateCreate,
CandidateListResponse,
CandidateMigrationReport,
CandidateMigrationRequest,
CandidateRecord,
CandidateResolutionReceipt,
CandidateResolutionRequest,
CandidateStatus,
CandidateSubjectKind,
)
from models.task_intelligence import TaskWorkflowControl, TaskWorkflowMode
from utils.other import endpoints as auth
from utils.task_intelligence import candidate_service
from utils.task_intelligence.capture_policy import MINIMUM_CAPTURE_CONFIDENCE
from utils.task_intelligence.recommendations import candidate_recommendation_dedupe_key
from utils.task_intelligence.rollout import (
effective_task_workflow_control,
resolve_chat_first_ui,
resolve_task_intelligence_for_user,
)
from utils.task_intelligence import chat_first_e2e_fixture
from utils.task_intelligence.task_links import TaskLinkValidationError
from utils.task_intelligence.staged_migration import migrate_staged_tasks
router = APIRouter()
IdempotencyHeader = Annotated[str, Header(alias='Idempotency-Key', min_length=1, max_length=512)]
AccountGenerationHeader = Annotated[int, Header(alias='X-Account-Generation', ge=0)]
SUGGESTED_CANDIDATE_LIMIT = 5
SUGGESTED_CANDIDATE_RAW_LIMIT = 500
SUGGESTED_CANDIDATE_TTL = candidates_db.SUGGESTION_TTL
def _require_candidate_write_control(uid: str, account_generation: int) -> None:
control = task_control_db.get_task_workflow_control(uid)
rollout = resolve_task_intelligence_for_user(
uid=uid,
workflow_mode=control.workflow_mode,
account_generation=control.account_generation,
)
if not rollout.intelligence_product_enabled:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Not found')
if control.account_generation != account_generation:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail='Account generation mismatch')
def _raise_store_error(exc: candidates_db.CandidateStoreError) -> None:
if isinstance(exc, candidates_db.CandidateNotFoundError):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Candidate or task not found') from exc
if isinstance(exc, candidates_db.CandidateGenerationMismatchError):
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail='Account generation mismatch') from exc
if isinstance(exc, candidates_db.WorkstreamCandidateResolverUnavailableError):
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
def _require_suggested_rollout(uid: str):
control = task_control_db.get_task_workflow_control(uid)
rollout = resolve_task_intelligence_for_user(
uid=uid,
workflow_mode=control.workflow_mode,
account_generation=control.account_generation,
)
if not rollout.intelligence_product_enabled:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Not found')
return rollout
def _has_suggested_candidate_shape(
candidate: CandidateRecord,
*,
now: datetime,
enforce_freshness: bool = True,
) -> bool:
if candidate.proposed_action != CandidateAction.create:
return False
if candidate.subject_kind == CandidateSubjectKind.task:
if not isinstance(candidate.task_change, TaskCreatePayload):
return False
elif candidate.subject_kind == CandidateSubjectKind.workstream:
if candidate.workstream_proposal is None:
return False
else:
return False
if (
candidate.capture_confidence < MINIMUM_CAPTURE_CONFIDENCE
or candidate.ownership_confidence < MINIMUM_CAPTURE_CONFIDENCE
or not candidate.evidence_refs
):
return False
created_at = candidate.created_at
if created_at.tzinfo is None:
return False
return not enforce_freshness or not candidates_db.candidate_has_lapsed(candidate, now=now)
def _is_suggested_candidate(candidate: CandidateRecord, *, now: datetime) -> bool:
return candidate.status == CandidateStatus.pending and _has_suggested_candidate_shape(candidate, now=now)
def _suggested_candidates(
candidates: list[CandidateRecord],
*,
limit: int,
suppressed_dedupe_keys: set[str],
now: Optional[datetime] = None,
) -> list[CandidateRecord]:
current_time = now or datetime.now(timezone.utc)
eligible = [candidate for candidate in candidates if _is_suggested_candidate(candidate, now=current_time)]
eligible.sort(key=lambda candidate: candidate.created_at, reverse=True)
eligible_with_identity = [
(candidate, candidates_db.suggested_candidate_semantic_identity(candidate.as_proposal()))
for candidate in eligible
]
terminal_resolutions: dict[str, list[datetime]] = {}
for candidate in candidates:
if (
candidate.status not in {CandidateStatus.accepted, CandidateStatus.rejected}
or candidate.resolved_at is None
or candidate.resolved_at.tzinfo is None
or not _has_suggested_candidate_shape(candidate, now=current_time, enforce_freshness=False)
):
continue
semantic_identity = candidates_db.suggested_candidate_semantic_identity(candidate.as_proposal())
if semantic_identity is not None:
terminal_resolutions.setdefault(semantic_identity, []).append(candidate.resolved_at)
suppressed_semantic_identities = {
semantic_identity
for candidate in candidates
if _has_suggested_candidate_shape(candidate, now=current_time, enforce_freshness=False)
and (semantic_identity := candidates_db.suggested_candidate_semantic_identity(candidate.as_proposal()))
is not None
and candidate_recommendation_dedupe_key(candidate.candidate_id) in suppressed_dedupe_keys
}
projection: list[CandidateRecord] = []
seen: set[str] = set()
for candidate, semantic_identity in eligible_with_identity:
if candidate_recommendation_dedupe_key(candidate.candidate_id) in suppressed_dedupe_keys:
continue
if semantic_identity is not None and semantic_identity in suppressed_semantic_identities:
continue
if semantic_identity is not None and any(
candidate.created_at <= resolved_at for resolved_at in terminal_resolutions.get(semantic_identity, [])
):
continue
dedupe_key = semantic_identity or candidate.candidate_id
if dedupe_key in seen:
continue
seen.add(dedupe_key)
projection.append(candidate)
if len(projection) == min(limit, SUGGESTED_CANDIDATE_LIMIT):
break
return projection
@router.post('/v1/candidates', response_model=CandidateRecord, tags=['candidates'])
def create_candidate(
request: CandidateCreate,
idempotency_key: IdempotencyHeader,
account_generation: AccountGenerationHeader,
uid: str = Depends(auth.get_current_user_uid),
):
_require_candidate_write_control(uid, account_generation)
try:
return candidate_service.create_candidate(
uid,
request,
idempotency_key=idempotency_key,
account_generation=account_generation,
)
except candidates_db.CandidateStoreError as exc:
_raise_store_error(exc)
@router.get('/v1/candidates', response_model=CandidateListResponse, tags=['candidates'])
def list_candidates(
candidate_status: Optional[CandidateStatus] = Query(default=None, alias='status'),
limit: int = Query(default=100, ge=1, le=500),
offset: int = Query(default=0, ge=0),
surface: Optional[Literal['suggested']] = Query(default=None),
uid: str = Depends(auth.get_current_user_uid),
):
rollout = _require_suggested_rollout(uid)
if surface == 'suggested':
records = candidates_db.list_candidates(
uid,
status=None,
account_generation=rollout.account_generation,
limit=SUGGESTED_CANDIDATE_RAW_LIMIT,
offset=0,
)
now = datetime.now(timezone.utc)
suppressed = recommendation_db.list_active_override_dedupe_keys(
uid,
now=now,
account_generation=rollout.account_generation,
)
refreshed_rollout = _require_suggested_rollout(uid)
if refreshed_rollout.account_generation != rollout.account_generation:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Not found')
return CandidateListResponse(
candidates=_suggested_candidates(
records,
limit=limit,
suppressed_dedupe_keys=suppressed,
now=now,
),
has_more=False,
)
records = candidates_db.list_candidates(
uid,
status=candidate_status,
account_generation=rollout.account_generation,
limit=limit + 1,
offset=offset,
)
return CandidateListResponse(candidates=records[:limit], has_more=len(records) > limit)
@router.post('/v1/candidates/migrate-staged', response_model=CandidateMigrationReport, tags=['candidates'])
def migrate_staged_candidates(
request: CandidateMigrationRequest,
uid: str = Depends(auth.get_current_user_uid),
):
control = task_control_db.get_task_workflow_control(uid)
rollout = resolve_task_intelligence_for_user(
uid=uid,
workflow_mode=control.workflow_mode,
account_generation=control.account_generation,
)
if not rollout.intelligence_product_enabled:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Not found')
return migrate_staged_tasks(
uid,
effective_task_workflow_control(control, rollout),
after_id=request.after_id,
limit=request.limit,
)
@router.get('/v1/candidates/control', response_model=TaskWorkflowControl, tags=['candidates'])
def get_candidate_workflow_control(uid: str = Depends(auth.get_current_user_uid)) -> TaskWorkflowControl:
# The named E2E bundle exercises the real desktop transport failure path,
# rather than accepting a client-supplied capability override. This is
# false for every non-local/offline account and unavailable in production.
if chat_first_e2e_fixture.is_control_unreachable(uid):
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail='Control temporarily unavailable')
try:
control = task_control_db.get_task_workflow_control(uid)
except Exception:
# This endpoint selects a shell. An unavailable control record must not
# expose a partial new experience or hide the legacy-safe response.
return TaskWorkflowControl()
try:
rollout = resolve_task_intelligence_for_user(
uid=uid,
workflow_mode=control.workflow_mode,
account_generation=control.account_generation,
)
chat_first_ui = resolve_chat_first_ui(rollout)
except Exception:
# Control resolution is intentionally fail-closed: a backend outage or
# malformed generation fence keeps this user in the existing shell.
return control.model_copy(
update={
'workflow_mode': TaskWorkflowMode.off,
'chat_first_ui': False,
}
)
# Desktop samples both fields as one generation-bound projection. Preserve
# the raw generation, but never let a stale workflow record select the
# legacy shell for a universally entitled account.
effective_control = effective_task_workflow_control(control, rollout)
return effective_control.model_copy(update={'chat_first_ui': chat_first_ui})
@router.post('/v1/candidates/integrations/drain', tags=['candidates'])
def drain_candidate_integrations(
account_generation: AccountGenerationHeader,
limit: int = Query(default=100, ge=1, le=500),
uid: str = Depends(auth.get_current_user_uid),
) -> dict[str, int]:
_require_candidate_write_control(uid, account_generation)
return {
'scheduled': candidate_service.drain_candidate_integrations(
uid,
account_generation=account_generation,
limit=limit,
)
}
@router.get('/v1/candidates/{candidate_id}', response_model=CandidateRecord, tags=['candidates'])
def get_candidate(candidate_id: str, uid: str = Depends(auth.get_current_user_uid)):
rollout = _require_suggested_rollout(uid)
candidate = candidates_db.get_candidate(uid, candidate_id)
if candidate is None or candidate.account_generation != rollout.account_generation:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Candidate not found')
return candidate
@router.post('/v1/candidates/{candidate_id}/accept', response_model=CandidateResolutionReceipt, tags=['candidates'])
def accept_candidate(
candidate_id: str,
account_generation: AccountGenerationHeader,
uid: str = Depends(auth.get_current_user_uid),
):
_require_candidate_write_control(uid, account_generation)
try:
return candidate_service.accept_candidate(uid, candidate_id, account_generation=account_generation)
except TaskLinkValidationError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
except candidates_db.CandidateStoreError as exc:
_raise_store_error(exc)
@router.post('/v1/candidates/{candidate_id}/reject', response_model=CandidateResolutionReceipt, tags=['candidates'])
def reject_candidate(
candidate_id: str,
request: CandidateResolutionRequest,
account_generation: AccountGenerationHeader,
uid: str = Depends(auth.get_current_user_uid),
):
_require_candidate_write_control(uid, account_generation)
try:
return candidate_service.reject_candidate(
uid,
candidate_id,
reason=request.reason,
account_generation=account_generation,
)
except candidates_db.CandidateStoreError as exc:
_raise_store_error(exc)
@router.post('/v1/candidates/{candidate_id}/expire', response_model=CandidateResolutionReceipt, tags=['candidates'])
def expire_candidate(
candidate_id: str,
request: CandidateResolutionRequest,
account_generation: AccountGenerationHeader,
uid: str = Depends(auth.get_current_user_uid),
):
_require_candidate_write_control(uid, account_generation)
try:
return candidate_service.expire_candidate(
uid,
candidate_id,
reason=request.reason,
account_generation=account_generation,
)
except candidates_db.CandidateStoreError as exc:
_raise_store_error(exc)
__all__ = ['router']