Coverage for app / services / decisions / context.py: 94%

80 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""Finding one governed turn by its ``invocation_id``, and what it recorded. 

2 

3A turn is an answer (the user's message and the assistant's, which both 

4carry the id since migration 91), a skill run, or a task of a swarm run. Everything else the record 

5reads — rules, flags, ledger rows, svc-ai's calls — is looked up by the same 

6id once, on first use, so a section that needs none of it costs nothing. 

7""" 

8 

9from __future__ import annotations 

10 

11import logging 

12from dataclasses import dataclass 

13from functools import cached_property 

14from typing import Any 

15from uuid import UUID 

16 

17from sqlalchemy.orm import Session 

18 

19from app.db.postgres.enums import DecisionEnum, MessageEnum 

20from app.db.postgres.models import ( 

21 ChatMessage, 

22 Conversation, 

23 DecisionReadLog, 

24 GovernanceEvent, 

25 GovernanceUsage, 

26 ReviewFlag, 

27 SkillRun, 

28 SwarmRun, 

29 SwarmTask, 

30) 

31from app.services import ai_client 

32 

33logger = logging.getLogger(__name__) 

34 

35Kind = DecisionEnum.Kind 

36 

37 

38@dataclass 

39class DecisionContext: 

40 db: Session 

41 invocation_id: UUID 

42 kind: Kind 

43 owner_user_id: UUID | None 

44 conversation: Conversation | None = None 

45 #: The turn's messages in order: the user's, then the answer. 

46 messages: tuple[ChatMessage, ...] = () 

47 run: SkillRun | None = None 

48 #: A swarm task, and the run it belongs to. 

49 task: SwarmTask | None = None 

50 swarm_run: SwarmRun | None = None 

51 

52 @property 

53 def question(self) -> ChatMessage | None: 

54 return next((m for m in self.messages if m.role == MessageEnum.Role.USER), None) 

55 

56 @property 

57 def answer(self) -> ChatMessage | None: 

58 return next( 

59 (m for m in self.messages if m.role == MessageEnum.Role.ASSISTANT), None 

60 ) 

61 

62 @property 

63 def answer_meta(self) -> dict[str, Any]: 

64 meta = getattr(self.answer, "meta", None) 

65 return meta if isinstance(meta, dict) else {} 

66 

67 @property 

68 def threaded(self) -> bool: 

69 """Whether the turn was recorded under its id throughout — its ledger 

70 row, flags and svc-ai's calls. Migration 91 backfilled the id onto 

71 older answers a rule ran on (the assistant's message only), and a 

72 skill run carried one before the ledger and svc-ai did.""" 

73 if self.kind == Kind.answer: 

74 question = self.question 

75 return question is not None and question.invocation_id is not None 

76 if self.kind == Kind.swarm_task: 

77 # Swarms came after threading: every task's rows carry its id. 

78 return True 

79 run = self.run 

80 return bool(self.ledger) or not (run is not None and run.llm_calls) 

81 

82 @cached_property 

83 def events(self) -> list[GovernanceEvent]: 

84 return ( 

85 self.db.query(GovernanceEvent) 

86 .filter(GovernanceEvent.invocation_id == self.invocation_id) 

87 .order_by(GovernanceEvent.created_at.asc()) 

88 .all() 

89 ) 

90 

91 @cached_property 

92 def flags(self) -> list[ReviewFlag]: 

93 return ( 

94 self.db.query(ReviewFlag) 

95 .filter(ReviewFlag.invocation_id == self.invocation_id) 

96 .order_by(ReviewFlag.created_at.asc()) 

97 .all() 

98 ) 

99 

100 @cached_property 

101 def ledger(self) -> list[GovernanceUsage]: 

102 return ( 

103 self.db.query(GovernanceUsage) 

104 .filter(GovernanceUsage.invocation_id == self.invocation_id) 

105 .order_by(GovernanceUsage.occurred_at.asc()) 

106 .all() 

107 ) 

108 

109 @cached_property 

110 def reads(self) -> list[DecisionReadLog]: 

111 return ( 

112 self.db.query(DecisionReadLog) 

113 .filter(DecisionReadLog.invocation_id == self.invocation_id) 

114 .order_by(DecisionReadLog.read_at.asc()) 

115 .all() 

116 ) 

117 

118 @cached_property 

119 def trace(self) -> dict[str, Any] | None: 

120 """svc-ai's model and tool calls for the turn; None when svc-ai could 

121 not be reached — which the record says, rather than showing none.""" 

122 if self.owner_user_id is None: 

123 return {"invocations": [], "tool_calls": []} 

124 try: 

125 return ai_client.get_turn_trace(self.invocation_id, self.owner_user_id) 

126 except ai_client.AIServiceError: 

127 logger.warning( 

128 "svc-ai's calls for turn %s could not be read", self.invocation_id 

129 ) 

130 return None 

131 

132 

133def locate(db: Session, invocation_id: UUID) -> DecisionContext | None: 

134 """The turn with this id — an answer, else a skill run, else a swarm 

135 task — or None.""" 

136 messages = ( 

137 db.query(ChatMessage) 

138 .filter(ChatMessage.invocation_id == invocation_id) 

139 .order_by(ChatMessage.sent_at.asc()) 

140 .all() 

141 ) 

142 if messages: 

143 conversation = db.get(Conversation, messages[0].conversation_id) 

144 if not any(m.role == MessageEnum.Role.USER for m in messages): 

145 # An answer migration 91 backfilled: its question was not stamped. 

146 # It is the user's message just before it — a turn stores the 

147 # two with strictly increasing timestamps. 

148 question = ( 

149 db.query(ChatMessage) 

150 .filter( 

151 ChatMessage.conversation_id == messages[0].conversation_id, 

152 ChatMessage.role == MessageEnum.Role.USER, 

153 ChatMessage.sent_at < messages[0].sent_at, 

154 ) 

155 .order_by(ChatMessage.sent_at.desc()) 

156 .first() 

157 ) 

158 if question is not None: 

159 messages = [question, *messages] 

160 return DecisionContext( 

161 db=db, 

162 invocation_id=invocation_id, 

163 kind=Kind.answer, 

164 owner_user_id=getattr(conversation, "owner_user_id", None), 

165 conversation=conversation, 

166 messages=tuple(messages), 

167 ) 

168 run = db.query(SkillRun).filter(SkillRun.invocation_id == invocation_id).first() 

169 if run is not None: 

170 return DecisionContext( 

171 db=db, 

172 invocation_id=invocation_id, 

173 kind=Kind.skill_run, 

174 owner_user_id=run.user_id, 

175 run=run, 

176 ) 

177 task = db.query(SwarmTask).filter(SwarmTask.invocation_id == invocation_id).first() 

178 if task is not None: 

179 swarm_run = db.get(SwarmRun, task.run_id) 

180 return DecisionContext( 

181 db=db, 

182 invocation_id=invocation_id, 

183 kind=Kind.swarm_task, 

184 # The task is the person's who dispatched the run, as a skill 

185 # run is the person's who started it. 

186 owner_user_id=getattr(swarm_run, "user_id", None), 

187 task=task, 

188 swarm_run=swarm_run, 

189 ) 

190 return None