github-actions[bot] commited on
Commit
ffb9fd9
·
1 Parent(s): 9210696

Automated Deploy: d73abbec668c068321b615dd48348d44b6de0443

Browse files
AI-coach-agent/src/ai_coach/group_review.py CHANGED
@@ -13,7 +13,7 @@ from pydantic import BaseModel, ConfigDict, Field
13
  from .cost import compute_cost
14
  from .schemas import Usage
15
 
16
- VERSION = 'sam-groups-v2'
17
  ASPECTS = {
18
  'rotation': {
19
  'hip_shoulder_differentiation': ('Hip and shoulder turning', {'hip_heading_deg','shoulder_heading_deg','hip_shoulder_separation_deg'}),
@@ -161,6 +161,7 @@ def available_facts(groups):
161
 
162
  def _text(text,*,suggestion=False):
163
  value=' '.join(text.split())
 
164
  if (len(value.split())>35 or re.search(r'\d|\b(injury|pain|injured|diagnos\w*|elite|normal|optimal|ideal|mph|degrees?|milliseconds?|torque|force)\b',value,re.I)):
165
  raise ValueError('Unsupported quantities, benchmark or medical claim in coaching prose')
166
  if re.search(r'\b(accelerat\w*|decelerat\w*|symmetr\w*|productive|explosive|efficient|jerky|unstable|abrupt\w*)\b',value,re.I):
@@ -172,6 +173,57 @@ def _text(text,*,suggestion=False):
172
  return value[0].upper()+value[1:]+('' if value[-1] in '.!?' else '.')
173
 
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  def build_reviews(parsed,facts,evidence,model):
176
  """Reject changed/missing aspect IDs or unsupported evidence, then compute scores."""
177
  expected={g['key']:g for g in facts};ratings={g.key:g for g in parsed.groups}
@@ -185,19 +237,35 @@ def build_reviews(parsed,facts,evidence,model):
185
  aspect_map={a['key']:a for a in fact['aspects']}
186
  if {a.key for a in rating.aspects}!=set(aspect_map) or len(rating.aspects)!=len(aspect_map):
187
  raise ValueError('Aspect IDs differ')
188
- aspects=[{'key':a.key,'label':aspect_map[a.key]['label'],'grade':a.grade,'max_grade':4,
189
- 'explanation':_text(a.explanation),'evidence':resolved(a.evidence_ids,set(aspect_map[a.key]['evidence_ids']))}
190
- for a in rating.aspects]
 
 
 
 
 
 
 
 
 
 
191
  value=round(10*sum(a['grade'] for a in aspects)/(4*len(aspects)),1)
192
  band=next(label for minimum,label in [(9,'Strong pattern'),(7,'Solid foundation'),(5,'Developing'),(3,'Needs practice'),(0,'Priority for practice')] if value>=minimum)
193
- def point(p,*,suggestion=False):return {'text':_text(p.text,suggestion=suggestion),'evidence':resolved(p.evidence_ids)}
 
 
 
 
 
 
 
194
  result[key]={'score':{'name':'Estimated coaching score','value':value,'max_value':10,
195
  'status':'estimated','band':band,'basis':'available_measurement_ai_rubric',
196
  'rubric_version':VERSION,'source':'coach_agent','model':model,'aspects':aspects,
197
  'reason_code':None,'accuracy_validated':False},
198
- 'coaching':{'summary':_text(rating.summary),'what_went_well':[point(p) for p in rating.what_went_well],
199
- 'what_needs_work':[point(p,suggestion=True) for p in rating.what_needs_work],'next_step':point(rating.next_step,suggestion=True),
200
- 'source':'coach_agent','model':model}}
201
  return result
202
 
203
 
 
13
  from .cost import compute_cost
14
  from .schemas import Usage
15
 
16
+ VERSION = 'sam-groups-v3'
17
  ASPECTS = {
18
  'rotation': {
19
  'hip_shoulder_differentiation': ('Hip and shoulder turning', {'hip_heading_deg','shoulder_heading_deg','hip_shoulder_separation_deg'}),
 
161
 
162
  def _text(text,*,suggestion=False):
163
  value=' '.join(text.split())
164
+ if not value:raise ValueError('Empty coaching text')
165
  if (len(value.split())>35 or re.search(r'\d|\b(injury|pain|injured|diagnos\w*|elite|normal|optimal|ideal|mph|degrees?|milliseconds?|torque|force)\b',value,re.I)):
166
  raise ValueError('Unsupported quantities, benchmark or medical claim in coaching prose')
167
  if re.search(r'\b(accelerat\w*|decelerat\w*|symmetr\w*|productive|explosive|efficient|jerky|unstable|abrupt\w*)\b',value,re.I):
 
173
  return value[0].upper()+value[1:]+('' if value[-1] in '.!?' else '.')
174
 
175
 
176
+ def _fact_text(rows):
177
+ """Source-defined facts, independent of a model's temporal/quality claims."""
178
+ for rep in sorted({r['rep'] for r in rows}):
179
+ by={r['key']:r for r in rows if r['rep']==rep}
180
+ for first,second,a,b in [('hip_peak_time_ms','hands_peak_time_ms','hip rotation-speed','hand-speed'),
181
+ ('hip_peak_time_ms','shoulder_peak_time_ms','hip rotation-speed','shoulder rotation-speed')]:
182
+ if first in by and second in by and by[first]['reference']==by[second]['reference']:
183
+ relation='before' if by[first]['value']<by[second]['value'] else 'after' if by[first]['value']>by[second]['value'] else 'at the same sampled time as'
184
+ return f'The reported {a} peak occurs {relation} the {b} peak in the selected forward interval.'
185
+ r=rows[0];key=r['key'];v=r['value']
186
+ if key=='hip_shoulder_separation_deg':
187
+ return 'The hip and shoulder lines have '+('matching' if v==0 else 'different')+' headings at the reported separation sample.'
188
+ if key in ('hip_to_shoulder_ms','shoulder_to_hands_ms'):
189
+ first,second=('hip rotation-speed','shoulder rotation-speed') if key=='hip_to_shoulder_ms' else ('shoulder rotation-speed','hand-speed')
190
+ relation='after' if v>0 else 'before' if v<0 else 'at the same sampled time as'
191
+ return f'The reported {second} peak occurs {relation} the {first} peak.'
192
+ if key=='head_excursion_ground_cm':
193
+ return 'The reported excursion compares the ear midpoint with its baseline in the supplied ground reference.'
194
+ if key.startswith('head_'):
195
+ return 'This measurement describes the ear midpoint relative to the hip midpoint and its selected baseline.'
196
+ if key in ('forward_lean_deg','side_lean_deg'):
197
+ return 'The reported lean describes the torso centerline relative to the anatomical pelvis axes in the selected interval.'
198
+ if key=='stance_span_cm':
199
+ return 'The reported ankle span describes the horizontal distance between the ankles at the selected baseline.'
200
+ if key=='stance_width_baseline_cm':
201
+ return 'The reported stance width describes the ankle separation projected onto the starting hip axis.'
202
+ if key.endswith('foot_heading_deg'):
203
+ return 'The foot heading is described relative to the fixed analysis reference at the selected baseline or reviewed landing.'
204
+ if key.startswith('stride_'):
205
+ return 'This stride measurement uses the supplied reviewed start and landing references.'
206
+ if key=='hand_speed_relative_m_s':
207
+ return 'The reported speed peak describes the wrist midpoint relative to the hips during the selected forward interval.'
208
+ if 'rotation_from_start' in key:
209
+ return 'The reported rotation compares the selected window-end heading with its baseline heading.'
210
+ if 'angular_velocity' in key:
211
+ return 'The reported value describes the sampled forward rotation-speed peak within the selected interval.'
212
+ if key.endswith('heading_deg'):
213
+ return 'The reported line heading uses the fixed analysis reference at the selected separation sample.'
214
+ return 'This point refers to the supplied measurement and its stated reference in the selected interval.'
215
+
216
+
217
+ def _practice_text(group,rows):
218
+ if group=='rotation':return 'Try slow dry swings with a comfortable hip and shoulder turn, then compare the same rotation measurements on the next recording.'
219
+ if group=='timing':return 'Try slow dry swings that bring the hips through before the hands, using the reported speed peaks as a reference rather than a pitch-timing verdict.'
220
+ if group=='posture':
221
+ if any(r['key'].startswith('head_') for r in rows):return 'Try slow rehearsals while attending to head position relative to the hips, then compare the same movement measure on your next recording.'
222
+ return 'Rehearse your torso position slowly, then compare the reported lean on your next recording.'
223
+ if any(r['key'].startswith('stride_') for r in rows):return 'Try slow stride rehearsals using the reviewed start and landing positions as references.'
224
+ return 'Mark your preferred starting foot positions and rehearse returning to that comfortable setup between swings.'
225
+
226
+
227
  def build_reviews(parsed,facts,evidence,model):
228
  """Reject changed/missing aspect IDs or unsupported evidence, then compute scores."""
229
  expected={g['key']:g for g in facts};ratings={g.key:g for g in parsed.groups}
 
237
  aspect_map={a['key']:a for a in fact['aspects']}
238
  if {a.key for a in rating.aspects}!=set(aspect_map) or len(rating.aspects)!=len(aspect_map):
239
  raise ValueError('Aspect IDs differ')
240
+ sources=[]
241
+ def safe_text(text,rows,*,suggestion=False):
242
+ try:value=_text(text,suggestion=suggestion);source='coach_agent'
243
+ except ValueError:
244
+ value=_practice_text(key,rows) if suggestion else _fact_text(rows);source='rules'
245
+ sources.append(source)
246
+ return value,source
247
+ aspects=[]
248
+ for a in rating.aspects:
249
+ rows=resolved(a.evidence_ids,set(aspect_map[a.key]['evidence_ids']))
250
+ text,source=safe_text(a.explanation,rows)
251
+ aspects.append({'key':a.key,'label':aspect_map[a.key]['label'],'grade':a.grade,'max_grade':4,
252
+ 'explanation':text,'explanation_source':source,'evidence':rows})
253
  value=round(10*sum(a['grade'] for a in aspects)/(4*len(aspects)),1)
254
  band=next(label for minimum,label in [(9,'Strong pattern'),(7,'Solid foundation'),(5,'Developing'),(3,'Needs practice'),(0,'Priority for practice')] if value>=minimum)
255
+ def point(p,*,suggestion=False):
256
+ rows=resolved(p.evidence_ids);text,source=safe_text(p.text,rows,suggestion=suggestion)
257
+ return {'text':text,'evidence':rows,'source':source}
258
+ summary,summary_source=safe_text(rating.summary,fact['measurements'])
259
+ strengths=[point(p) for p in rating.what_went_well]
260
+ refinements=[point(p,suggestion=True) for p in rating.what_needs_work]
261
+ next_step=point(rating.next_step,suggestion=True)
262
+ source='coach_agent' if all(s=='coach_agent' for s in sources) else 'rules' if all(s=='rules' for s in sources) else 'mixed'
263
  result[key]={'score':{'name':'Estimated coaching score','value':value,'max_value':10,
264
  'status':'estimated','band':band,'basis':'available_measurement_ai_rubric',
265
  'rubric_version':VERSION,'source':'coach_agent','model':model,'aspects':aspects,
266
  'reason_code':None,'accuracy_validated':False},
267
+ 'coaching':{'summary':summary,'summary_source':summary_source,'what_went_well':strengths,
268
+ 'what_needs_work':refinements,'next_step':next_step,'source':source,'model':model}}
 
269
  return result
270
 
271
 
baseball_batting/sam_batting_contract.py CHANGED
@@ -175,6 +175,7 @@ class ScoreEvidence(Strict):
175
  class CoachingPoint(Strict):
176
  text: str = Field(min_length=1, max_length=500)
177
  evidence: list[ScoreEvidence] = Field(min_length=1, max_length=8)
 
178
 
179
 
180
  class ScoreAspect(Strict):
@@ -183,6 +184,7 @@ class ScoreAspect(Strict):
183
  grade: int = Field(ge=0, le=4, strict=True)
184
  max_grade: Literal[4] = 4
185
  explanation: str
 
186
  evidence: list[ScoreEvidence] = Field(min_length=1, max_length=8)
187
 
188
 
@@ -193,7 +195,7 @@ class GroupScore(Strict):
193
  status: Literal['estimated', 'pending']
194
  band: str | None = None
195
  basis: Literal['available_measurement_ai_rubric'] = 'available_measurement_ai_rubric'
196
- rubric_version: str = 'sam-groups-v2'
197
  source: Literal['coach_agent', 'none']
198
  model: str | None = None
199
  aspects: list[ScoreAspect] = Field(default_factory=list, max_length=3)
@@ -208,8 +210,9 @@ class GroupCoaching(Strict):
208
  what_went_well: list[CoachingPoint] = Field(min_length=1, max_length=3)
209
  what_needs_work: list[CoachingPoint] = Field(min_length=1, max_length=3)
210
  next_step: CoachingPoint
211
- source: Literal['coach_agent'] = 'coach_agent'
212
- model: str
 
213
 
214
 
215
  class MeasurementGroup(Strict):
 
175
  class CoachingPoint(Strict):
176
  text: str = Field(min_length=1, max_length=500)
177
  evidence: list[ScoreEvidence] = Field(min_length=1, max_length=8)
178
+ source: Literal['coach_agent','rules'] = 'coach_agent'
179
 
180
 
181
  class ScoreAspect(Strict):
 
184
  grade: int = Field(ge=0, le=4, strict=True)
185
  max_grade: Literal[4] = 4
186
  explanation: str
187
+ explanation_source: Literal['coach_agent','rules'] = 'coach_agent'
188
  evidence: list[ScoreEvidence] = Field(min_length=1, max_length=8)
189
 
190
 
 
195
  status: Literal['estimated', 'pending']
196
  band: str | None = None
197
  basis: Literal['available_measurement_ai_rubric'] = 'available_measurement_ai_rubric'
198
+ rubric_version: str = 'sam-groups-v3'
199
  source: Literal['coach_agent', 'none']
200
  model: str | None = None
201
  aspects: list[ScoreAspect] = Field(default_factory=list, max_length=3)
 
210
  what_went_well: list[CoachingPoint] = Field(min_length=1, max_length=3)
211
  what_needs_work: list[CoachingPoint] = Field(min_length=1, max_length=3)
212
  next_step: CoachingPoint
213
+ source: Literal['coach_agent','mixed','rules'] = 'coach_agent'
214
+ summary_source: Literal['coach_agent','rules'] = 'coach_agent'
215
+ model: str | None = None
216
 
217
 
218
  class MeasurementGroup(Strict):
docs/SAM_BATTING_API.md CHANGED
@@ -199,13 +199,13 @@ validated numerical performance benchmarks. The HTML page marks the distinction.
199
 
200
  For the app, display `groups[i].score.value` with `score.max_value` (ten), then
201
  `groups[i].coaching.summary`, `what_went_well`, `what_needs_work`, and `next_step`.
202
- Each coaching point is `{ "text": "...", "evidence": [...] }`. The backend supplies
203
  the exact measurement value, unit, rep, statistic, reference and frame IDs in each
204
  evidence item. Do not interpret a null individual metric as a missing group score.
205
  Do not display unavailable individual measurements in the player’s main cards;
206
  they remain in the complete API result for diagnostics. Zero is a valid score.
207
 
208
- The `sam-groups-v2` rubric has named aspects for each group:
209
 
210
  | Group | Aspects |
211
  | --- | --- |
@@ -229,8 +229,13 @@ measurements/aspects add neither zeros nor penalties. The remaining aspects are
229
  weighted equally. All four groups in the verified example have usable evidence,
230
  so all four can receive a score while the twelve missing measurements stay unchanged.
231
  Every strength, improvement point and next step cites evidence from its own group;
232
- the server resolves those IDs to the original numbers. Model-generated quantities,
233
- cross-group evidence and changed aspect IDs are rejected.
 
 
 
 
 
234
 
235
  Use the same Bearer key to refresh a saved result without running SAM again:
236
 
 
199
 
200
  For the app, display `groups[i].score.value` with `score.max_value` (ten), then
201
  `groups[i].coaching.summary`, `what_went_well`, `what_needs_work`, and `next_step`.
202
+ Each coaching point is `{ "text": "...", "evidence": [...], "source": "coach_agent" }`. The backend supplies
203
  the exact measurement value, unit, rep, statistic, reference and frame IDs in each
204
  evidence item. Do not interpret a null individual metric as a missing group score.
205
  Do not display unavailable individual measurements in the player’s main cards;
206
  they remain in the complete API result for diagnostics. Zero is a valid score.
207
 
208
+ The `sam-groups-v3` rubric has named aspects for each group:
209
 
210
  | Group | Aspects |
211
  | --- | --- |
 
229
  weighted equally. All four groups in the verified example have usable evidence,
230
  so all four can receive a score while the twelve missing measurements stay unchanged.
231
  Every strength, improvement point and next step cites evidence from its own group;
232
+ the server resolves those IDs to the original numbers. Cross-group evidence,
233
+ invented evidence IDs and changed aspect IDs are rejected and retried once.
234
+ Prose is checked independently: an unsupported paragraph is replaced with a
235
+ source-defined factual explanation or practical rehearsal suggestion, while valid
236
+ grades and other paragraphs remain. `summary_source`, point `source`, and aspect
237
+ `explanation_source` identify `coach_agent` or `rules`; the group coaching source
238
+ is `mixed` when both occur. This fallback does not invent grades or measurements.
239
 
240
  Use the same Bearer key to refresh a saved result without running SAM again:
241
 
docs/sam-batting-result.schema.json CHANGED
@@ -154,6 +154,15 @@
154
  "minItems": 1,
155
  "title": "Evidence",
156
  "type": "array"
 
 
 
 
 
 
 
 
 
157
  }
158
  },
159
  "required": [
@@ -194,22 +203,42 @@
194
  "$ref": "#/$defs/CoachingPoint"
195
  },
196
  "source": {
197
- "const": "coach_agent",
198
  "default": "coach_agent",
 
 
 
 
 
199
  "title": "Source",
200
  "type": "string"
201
  },
202
- "model": {
203
- "title": "Model",
 
 
 
 
 
204
  "type": "string"
 
 
 
 
 
 
 
 
 
 
 
 
205
  }
206
  },
207
  "required": [
208
  "summary",
209
  "what_went_well",
210
  "what_needs_work",
211
- "next_step",
212
- "model"
213
  ],
214
  "title": "GroupCoaching",
215
  "type": "object"
@@ -270,7 +299,7 @@
270
  "type": "string"
271
  },
272
  "rubric_version": {
273
- "default": "sam-groups-v2",
274
  "title": "Rubric Version",
275
  "type": "string"
276
  },
@@ -610,6 +639,15 @@
610
  "title": "Explanation",
611
  "type": "string"
612
  },
 
 
 
 
 
 
 
 
 
613
  "evidence": {
614
  "items": {
615
  "$ref": "#/$defs/ScoreEvidence"
 
154
  "minItems": 1,
155
  "title": "Evidence",
156
  "type": "array"
157
+ },
158
+ "source": {
159
+ "default": "coach_agent",
160
+ "enum": [
161
+ "coach_agent",
162
+ "rules"
163
+ ],
164
+ "title": "Source",
165
+ "type": "string"
166
  }
167
  },
168
  "required": [
 
203
  "$ref": "#/$defs/CoachingPoint"
204
  },
205
  "source": {
 
206
  "default": "coach_agent",
207
+ "enum": [
208
+ "coach_agent",
209
+ "mixed",
210
+ "rules"
211
+ ],
212
  "title": "Source",
213
  "type": "string"
214
  },
215
+ "summary_source": {
216
+ "default": "coach_agent",
217
+ "enum": [
218
+ "coach_agent",
219
+ "rules"
220
+ ],
221
+ "title": "Summary Source",
222
  "type": "string"
223
+ },
224
+ "model": {
225
+ "anyOf": [
226
+ {
227
+ "type": "string"
228
+ },
229
+ {
230
+ "type": "null"
231
+ }
232
+ ],
233
+ "default": null,
234
+ "title": "Model"
235
  }
236
  },
237
  "required": [
238
  "summary",
239
  "what_went_well",
240
  "what_needs_work",
241
+ "next_step"
 
242
  ],
243
  "title": "GroupCoaching",
244
  "type": "object"
 
299
  "type": "string"
300
  },
301
  "rubric_version": {
302
+ "default": "sam-groups-v3",
303
  "title": "Rubric Version",
304
  "type": "string"
305
  },
 
639
  "title": "Explanation",
640
  "type": "string"
641
  },
642
+ "explanation_source": {
643
+ "default": "coach_agent",
644
+ "enum": [
645
+ "coach_agent",
646
+ "rules"
647
+ ],
648
+ "title": "Explanation Source",
649
+ "type": "string"
650
+ },
651
  "evidence": {
652
  "items": {
653
  "$ref": "#/$defs/ScoreEvidence"
docs/sam-group-review.schema.json CHANGED
@@ -155,6 +155,15 @@
155
  "minItems": 1,
156
  "title": "Evidence",
157
  "type": "array"
 
 
 
 
 
 
 
 
 
158
  }
159
  },
160
  "required": [
@@ -195,22 +204,42 @@
195
  "$ref": "#/$defs/CoachingPoint"
196
  },
197
  "source": {
198
- "const": "coach_agent",
199
  "default": "coach_agent",
 
 
 
 
 
200
  "title": "Source",
201
  "type": "string"
202
  },
203
- "model": {
204
- "title": "Model",
 
 
 
 
 
205
  "type": "string"
 
 
 
 
 
 
 
 
 
 
 
 
206
  }
207
  },
208
  "required": [
209
  "summary",
210
  "what_went_well",
211
  "what_needs_work",
212
- "next_step",
213
- "model"
214
  ],
215
  "title": "GroupCoaching",
216
  "type": "object"
@@ -271,7 +300,7 @@
271
  "type": "string"
272
  },
273
  "rubric_version": {
274
- "default": "sam-groups-v2",
275
  "title": "Rubric Version",
276
  "type": "string"
277
  },
@@ -611,6 +640,15 @@
611
  "title": "Explanation",
612
  "type": "string"
613
  },
 
 
 
 
 
 
 
 
 
614
  "evidence": {
615
  "items": {
616
  "$ref": "#/$defs/ScoreEvidence"
@@ -835,6 +873,15 @@
835
  "minItems": 1,
836
  "title": "Evidence",
837
  "type": "array"
 
 
 
 
 
 
 
 
 
838
  }
839
  },
840
  "required": [
@@ -875,22 +922,42 @@
875
  "$ref": "#/$defs/CoachingPoint"
876
  },
877
  "source": {
878
- "const": "coach_agent",
879
  "default": "coach_agent",
 
 
 
 
 
880
  "title": "Source",
881
  "type": "string"
882
  },
883
- "model": {
884
- "title": "Model",
 
 
 
 
 
885
  "type": "string"
 
 
 
 
 
 
 
 
 
 
 
 
886
  }
887
  },
888
  "required": [
889
  "summary",
890
  "what_went_well",
891
  "what_needs_work",
892
- "next_step",
893
- "model"
894
  ],
895
  "title": "GroupCoaching",
896
  "type": "object"
@@ -986,7 +1053,7 @@
986
  "type": "string"
987
  },
988
  "rubric_version": {
989
- "default": "sam-groups-v2",
990
  "title": "Rubric Version",
991
  "type": "string"
992
  },
@@ -1089,6 +1156,15 @@
1089
  "title": "Explanation",
1090
  "type": "string"
1091
  },
 
 
 
 
 
 
 
 
 
1092
  "evidence": {
1093
  "items": {
1094
  "$ref": "#/$defs/ScoreEvidence"
 
155
  "minItems": 1,
156
  "title": "Evidence",
157
  "type": "array"
158
+ },
159
+ "source": {
160
+ "default": "coach_agent",
161
+ "enum": [
162
+ "coach_agent",
163
+ "rules"
164
+ ],
165
+ "title": "Source",
166
+ "type": "string"
167
  }
168
  },
169
  "required": [
 
204
  "$ref": "#/$defs/CoachingPoint"
205
  },
206
  "source": {
 
207
  "default": "coach_agent",
208
+ "enum": [
209
+ "coach_agent",
210
+ "mixed",
211
+ "rules"
212
+ ],
213
  "title": "Source",
214
  "type": "string"
215
  },
216
+ "summary_source": {
217
+ "default": "coach_agent",
218
+ "enum": [
219
+ "coach_agent",
220
+ "rules"
221
+ ],
222
+ "title": "Summary Source",
223
  "type": "string"
224
+ },
225
+ "model": {
226
+ "anyOf": [
227
+ {
228
+ "type": "string"
229
+ },
230
+ {
231
+ "type": "null"
232
+ }
233
+ ],
234
+ "default": null,
235
+ "title": "Model"
236
  }
237
  },
238
  "required": [
239
  "summary",
240
  "what_went_well",
241
  "what_needs_work",
242
+ "next_step"
 
243
  ],
244
  "title": "GroupCoaching",
245
  "type": "object"
 
300
  "type": "string"
301
  },
302
  "rubric_version": {
303
+ "default": "sam-groups-v3",
304
  "title": "Rubric Version",
305
  "type": "string"
306
  },
 
640
  "title": "Explanation",
641
  "type": "string"
642
  },
643
+ "explanation_source": {
644
+ "default": "coach_agent",
645
+ "enum": [
646
+ "coach_agent",
647
+ "rules"
648
+ ],
649
+ "title": "Explanation Source",
650
+ "type": "string"
651
+ },
652
  "evidence": {
653
  "items": {
654
  "$ref": "#/$defs/ScoreEvidence"
 
873
  "minItems": 1,
874
  "title": "Evidence",
875
  "type": "array"
876
+ },
877
+ "source": {
878
+ "default": "coach_agent",
879
+ "enum": [
880
+ "coach_agent",
881
+ "rules"
882
+ ],
883
+ "title": "Source",
884
+ "type": "string"
885
  }
886
  },
887
  "required": [
 
922
  "$ref": "#/$defs/CoachingPoint"
923
  },
924
  "source": {
 
925
  "default": "coach_agent",
926
+ "enum": [
927
+ "coach_agent",
928
+ "mixed",
929
+ "rules"
930
+ ],
931
  "title": "Source",
932
  "type": "string"
933
  },
934
+ "summary_source": {
935
+ "default": "coach_agent",
936
+ "enum": [
937
+ "coach_agent",
938
+ "rules"
939
+ ],
940
+ "title": "Summary Source",
941
  "type": "string"
942
+ },
943
+ "model": {
944
+ "anyOf": [
945
+ {
946
+ "type": "string"
947
+ },
948
+ {
949
+ "type": "null"
950
+ }
951
+ ],
952
+ "default": null,
953
+ "title": "Model"
954
  }
955
  },
956
  "required": [
957
  "summary",
958
  "what_went_well",
959
  "what_needs_work",
960
+ "next_step"
 
961
  ],
962
  "title": "GroupCoaching",
963
  "type": "object"
 
1053
  "type": "string"
1054
  },
1055
  "rubric_version": {
1056
+ "default": "sam-groups-v3",
1057
  "title": "Rubric Version",
1058
  "type": "string"
1059
  },
 
1156
  "title": "Explanation",
1157
  "type": "string"
1158
  },
1159
+ "explanation_source": {
1160
+ "default": "coach_agent",
1161
+ "enum": [
1162
+ "coach_agent",
1163
+ "rules"
1164
+ ],
1165
+ "title": "Explanation Source",
1166
+ "type": "string"
1167
+ },
1168
  "evidence": {
1169
  "items": {
1170
  "$ref": "#/$defs/ScoreEvidence"
tests/test_sam_group_scoring.py CHANGED
@@ -72,7 +72,7 @@ def test_missing_measurements_do_not_change_facts_score_or_denominator():
72
  assert r['stance']['score']['value']==7.5
73
 
74
 
75
- @pytest.mark.parametrize('tamper',['bad_metric','cross_group','cross_aspect','duplicate_aspect','invented_number','bad_grade'])
76
  def test_provider_cannot_invent_evidence_quantities_or_change_score_rules(tamper):
77
  groups=group_fixture();facts,evidence=available_facts(groups);raw=provider_response(groups)
78
  row=raw['groups'][0]
@@ -80,7 +80,6 @@ def test_provider_cannot_invent_evidence_quantities_or_change_score_rules(tamper
80
  elif tamper=='cross_group':row['next_step']['evidence_ids']=[next(g for g in facts if g['key']!=row['key'])['measurements'][0]['metric_id']]
81
  elif tamper=='cross_aspect':row['aspects'][0]['evidence_ids']=row['aspects'][1]['evidence_ids']
82
  elif tamper=='duplicate_aspect':row['aspects'][1]['key']=row['aspects'][0]['key']
83
- elif tamper=='invented_number':row['summary']='Your bat speed was 99 mph.'
84
  elif tamper=='bad_grade':row['aspects'][0]['grade']=5
85
  with pytest.raises(ValueError):build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture')
86
 
@@ -128,7 +127,7 @@ def test_invalid_provider_response_has_one_billed_repair_and_never_fabricates_a_
128
  def __exit__(self,*a):pass
129
  def generate_content(self,**kwargs):
130
  calls.append(kwargs);raw=provider_response(groups)
131
- if len(calls)==1 or not repaired:raw['groups'][0]['summary']='Your bat speed is 99 mph.'
132
  return types.GenerateContentResponse(candidates=[types.Candidate(content=types.Content(parts=[types.Part.from_text(text=json.dumps(raw))]))],
133
  usage_metadata=types.GenerateContentResponseUsageMetadata(prompt_token_count=100,candidates_token_count=200))
134
  monkeypatch.setattr(genai,'Client',Client)
@@ -183,6 +182,7 @@ def test_provider_error_details_are_typed_and_redact_the_key(tmp_path,monkeypatc
183
 
184
 
185
  @pytest.mark.parametrize('claim',[
 
186
  'Your lean was maintained throughout the motion.',
187
  'The stance provided a repeatable base.',
188
  'Hand acceleration was synchronized with the pelvis.',
@@ -193,7 +193,44 @@ def test_provider_error_details_are_typed_and_redact_the_key(tmp_path,monkeypatc
193
  def test_scalar_evidence_cannot_be_laundered_into_dynamic_or_symmetry_claims(claim):
194
  groups=group_fixture();facts,evidence=available_facts(groups);raw=provider_response(groups)
195
  raw['groups'][0]['summary']=claim
196
- with pytest.raises(ValueError):build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
 
199
  def test_practice_goals_are_distinct_from_claims_about_current_motion():
 
72
  assert r['stance']['score']['value']==7.5
73
 
74
 
75
+ @pytest.mark.parametrize('tamper',['bad_metric','cross_group','cross_aspect','duplicate_aspect','bad_grade'])
76
  def test_provider_cannot_invent_evidence_quantities_or_change_score_rules(tamper):
77
  groups=group_fixture();facts,evidence=available_facts(groups);raw=provider_response(groups)
78
  row=raw['groups'][0]
 
80
  elif tamper=='cross_group':row['next_step']['evidence_ids']=[next(g for g in facts if g['key']!=row['key'])['measurements'][0]['metric_id']]
81
  elif tamper=='cross_aspect':row['aspects'][0]['evidence_ids']=row['aspects'][1]['evidence_ids']
82
  elif tamper=='duplicate_aspect':row['aspects'][1]['key']=row['aspects'][0]['key']
 
83
  elif tamper=='bad_grade':row['aspects'][0]['grade']=5
84
  with pytest.raises(ValueError):build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture')
85
 
 
127
  def __exit__(self,*a):pass
128
  def generate_content(self,**kwargs):
129
  calls.append(kwargs);raw=provider_response(groups)
130
+ if len(calls)==1 or not repaired:raw['groups'][0]['next_step']['evidence_ids']=['invented']
131
  return types.GenerateContentResponse(candidates=[types.Candidate(content=types.Content(parts=[types.Part.from_text(text=json.dumps(raw))]))],
132
  usage_metadata=types.GenerateContentResponseUsageMetadata(prompt_token_count=100,candidates_token_count=200))
133
  monkeypatch.setattr(genai,'Client',Client)
 
182
 
183
 
184
  @pytest.mark.parametrize('claim',[
185
+ 'Your bat speed was 99 mph.',
186
  'Your lean was maintained throughout the motion.',
187
  'The stance provided a repeatable base.',
188
  'Hand acceleration was synchronized with the pelvis.',
 
193
  def test_scalar_evidence_cannot_be_laundered_into_dynamic_or_symmetry_claims(claim):
194
  groups=group_fixture();facts,evidence=available_facts(groups);raw=provider_response(groups)
195
  raw['groups'][0]['summary']=claim
196
+ result=build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture')
197
+ repaired=result[raw['groups'][0]['key']]
198
+ assert repaired['score']['value']==7.5
199
+ assert repaired['coaching']['summary']!=claim
200
+ assert repaired['coaching']['summary_source']=='rules'
201
+ assert repaired['coaching']['source']=='mixed'
202
+ assert all(r['score']['value']==7.5 for r in result.values())
203
+
204
+
205
+ def test_bad_paragraphs_are_replaced_individually_without_losing_valid_feedback():
206
+ groups=group_fixture();facts,evidence=available_facts(groups);raw=provider_response(groups)
207
+ timing=next(g for g in raw['groups'] if g['key']=='timing')
208
+ timing['summary']='Hand acceleration was synchronized with the pelvis.'
209
+ timing['aspects'][0]['explanation']='Your bat speed was 99 mph.'
210
+ timing['what_needs_work'][0]={**timing['what_needs_work'][0],
211
+ 'text':'Missing data prevents judging this movement.'}
212
+ result=build_reviews(RatingBatch.model_validate(raw),facts,evidence,'fixture')
213
+ row=result['timing']
214
+ assert row['score']['value']==7.5 and row['coaching']['source']=='mixed'
215
+ assert row['score']['aspects'][0]['explanation_source']=='rules'
216
+ assert row['coaching']['what_needs_work'][0]['source']=='rules'
217
+ assert row['coaching']['next_step']['source']=='coach_agent'
218
+ assert row['coaching']['what_went_well'][0]['text']==timing['what_went_well'][0]['text']
219
+ assert 'before the hand-speed peak' in row['coaching']['summary']
220
+ assert result['rotation']['coaching']['source']=='coach_agent'
221
+ # All additions remain valid public response DTOs, including provenance.
222
+ from baseball_batting.sam_batting_contract import SamGroupReviewResponse
223
+ SamGroupReviewResponse(groups=[{'key':key,**r} for key,r in result.items()])
224
+
225
+
226
+ def test_factual_replacements_do_not_confuse_ground_relative_or_partial_stance_data():
227
+ from ai_coach.group_review import _fact_text
228
+ row={'key':'head_excursion_ground_cm','rep':1,'value':4,'reference':'ground'}
229
+ assert 'ground reference' in _fact_text([row]) and 'hip midpoint' not in _fact_text([row])
230
+ row['key']='stance_span_cm'
231
+ assert 'projected' not in _fact_text([row])
232
+ row['key']='stance_width_baseline_cm'
233
+ assert 'projected' in _fact_text([row])
234
 
235
 
236
  def test_practice_goals_are_distinct_from_claims_about_current_motion():