maproom 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. maproom/__init__.py +14 -0
  2. maproom/__main__.py +10 -0
  3. maproom/analyze/__init__.py +1 -0
  4. maproom/analyze/accel_families.py +45 -0
  5. maproom/analyze/account_azure_activity.py +260 -0
  6. maproom/analyze/account_azure_quota_requests.py +177 -0
  7. maproom/analyze/account_cloudtrail.py +316 -0
  8. maproom/analyze/account_quota_requests.py +180 -0
  9. maproom/analyze/analyze_v1_orchestration.py +1194 -0
  10. maproom/analyze/catalog.py +353 -0
  11. maproom/analyze/change_detection.py +652 -0
  12. maproom/analyze/context_client.py +99 -0
  13. maproom/analyze/context_lookup.py +142 -0
  14. maproom/analyze/cover_analyze.py +344 -0
  15. maproom/analyze/cover_client.py +65 -0
  16. maproom/analyze/cover_lookup.py +242 -0
  17. maproom/analyze/engine.py +644 -0
  18. maproom/analyze/fleetfit_endpoints.py +217 -0
  19. maproom/analyze/fleetfit_policy.py +66 -0
  20. maproom/analyze/instance_price_analyze.py +221 -0
  21. maproom/analyze/instance_price_client.py +108 -0
  22. maproom/analyze/instance_price_lookup.py +60 -0
  23. maproom/analyze/local_reads.py +484 -0
  24. maproom/analyze/lookup_http.py +280 -0
  25. maproom/analyze/metric_format.py +20 -0
  26. maproom/analyze/migration_method.py +130 -0
  27. maproom/analyze/move_list.py +93 -0
  28. maproom/analyze/operator_context.py +156 -0
  29. maproom/analyze/performance_rank.py +97 -0
  30. maproom/analyze/primary_recommendation.py +422 -0
  31. maproom/analyze/provider_comparison.py +401 -0
  32. maproom/analyze/quota_analyze.py +481 -0
  33. maproom/analyze/quota_client.py +75 -0
  34. maproom/analyze/quota_lookup.py +110 -0
  35. maproom/analyze/quota_outcome_steer.py +105 -0
  36. maproom/analyze/recommend_batch.py +199 -0
  37. maproom/analyze/recommend_client.py +362 -0
  38. maproom/analyze/recommend_share.py +118 -0
  39. maproom/analyze/recommendation.py +591 -0
  40. maproom/analyze/reservation_pack.py +883 -0
  41. maproom/analyze/reservation_read.py +461 -0
  42. maproom/analyze/safe_analyze.py +1134 -0
  43. maproom/analyze/safe_move.py +195 -0
  44. maproom/analyze/safe_moves.py +571 -0
  45. maproom/analyze/safe_moves_catalog.py +127 -0
  46. maproom/analyze/safe_moves_client.py +70 -0
  47. maproom/analyze/series_analyze.py +491 -0
  48. maproom/analyze/series_client.py +106 -0
  49. maproom/analyze/series_lookup.py +663 -0
  50. maproom/analyze/shape.py +254 -0
  51. maproom/analyze/size_analyze.py +883 -0
  52. maproom/analyze/size_client.py +81 -0
  53. maproom/analyze/size_keep.py +409 -0
  54. maproom/analyze/size_lookup.py +368 -0
  55. maproom/analyze/specs.py +325 -0
  56. maproom/analyze/spot_analyze.py +392 -0
  57. maproom/analyze/spot_client.py +74 -0
  58. maproom/analyze/spot_lookup.py +213 -0
  59. maproom/analyze/token_client.py +97 -0
  60. maproom/analyze/utilization.py +190 -0
  61. maproom/analyze/workload.py +104 -0
  62. maproom/analyze/workset.py +762 -0
  63. maproom/aws_region.py +78 -0
  64. maproom/cache/__init__.py +1 -0
  65. maproom/cache/catalog.py +372 -0
  66. maproom/cache/commands.py +215 -0
  67. maproom/cache/instances.py +460 -0
  68. maproom/cli.py +2084 -0
  69. maproom/cli_argv.py +329 -0
  70. maproom/cli_floors.py +89 -0
  71. maproom/cliio/__init__.py +1 -0
  72. maproom/cliio/registry.py +377 -0
  73. maproom/cliio/runner.py +489 -0
  74. maproom/consent/__init__.py +33 -0
  75. maproom/consent/gate.py +238 -0
  76. maproom/consent/policy.py +20 -0
  77. maproom/consent/prompt.py +61 -0
  78. maproom/consent/service_upload_gate.py +318 -0
  79. maproom/consent/service_upload_prompt.py +62 -0
  80. maproom/consent/stdin.py +45 -0
  81. maproom/consent/storage.py +24 -0
  82. maproom/consent/write_token.py +29 -0
  83. maproom/contracts/__init__.py +6 -0
  84. maproom/contracts/schema_diff.py +119 -0
  85. maproom/contracts/validate.py +113 -0
  86. maproom/data/__init__.py +1 -0
  87. maproom/data/clear.py +76 -0
  88. maproom/data/commands.py +14 -0
  89. maproom/doctor/__init__.py +1 -0
  90. maproom/doctor/aws_session.py +226 -0
  91. maproom/doctor/checks.py +701 -0
  92. maproom/doctor/context.py +32 -0
  93. maproom/doctor/display.py +96 -0
  94. maproom/doctor/inventory_display.py +377 -0
  95. maproom/doctor/runner.py +1467 -0
  96. maproom/errors.py +43 -0
  97. maproom/exitcodes.py +70 -0
  98. maproom/inventory/__init__.py +1 -0
  99. maproom/inventory/account_identity.py +79 -0
  100. maproom/inventory/accounts.py +155 -0
  101. maproom/inventory/command.py +961 -0
  102. maproom/inventory/messages.py +264 -0
  103. maproom/inventory/reservations_refresh.py +37 -0
  104. maproom/mock_environment/__init__.py +28 -0
  105. maproom/mock_environment/load.py +241 -0
  106. maproom/mock_environment/runner.py +387 -0
  107. maproom/output/__init__.py +1 -0
  108. maproom/output/json_envelope.py +241 -0
  109. maproom/output/redact.py +11 -0
  110. maproom/output/terminal.py +129 -0
  111. maproom/parsers.py +284 -0
  112. maproom/paths.py +105 -0
  113. maproom/plan/__init__.py +1 -0
  114. maproom/plan/accept.py +59 -0
  115. maproom/plan/analysis_context.py +78 -0
  116. maproom/plan/analyze_selection.py +279 -0
  117. maproom/plan/commands.py +586 -0
  118. maproom/plan/current.py +59 -0
  119. maproom/plan/errors.py +10 -0
  120. maproom/plan/export.py +36 -0
  121. maproom/plan/formatting.py +91 -0
  122. maproom/plan/ids.py +13 -0
  123. maproom/plan/migration_options.py +75 -0
  124. maproom/plan/model.py +265 -0
  125. maproom/plan/names.py +24 -0
  126. maproom/plan/store.py +193 -0
  127. maproom/plan/tty.py +34 -0
  128. maproom/pricing/__init__.py +5 -0
  129. maproom/pricing/prices.py +119 -0
  130. maproom/privacy/__init__.py +6 -0
  131. maproom/privacy/commands.py +159 -0
  132. maproom/privacy/delete_uploads.py +204 -0
  133. maproom/privacy/fleetfit_policy.py +125 -0
  134. maproom/privacy/fleetfit_statement.py +104 -0
  135. maproom/privacy/format.py +76 -0
  136. maproom/privacy/manifests.py +342 -0
  137. maproom/privacy/statement.py +58 -0
  138. maproom/quotas/__init__.py +21 -0
  139. maproom/quotas/aws.py +204 -0
  140. maproom/quotas/azure.py +75 -0
  141. maproom/quotas/commands.py +240 -0
  142. maproom/quotas/family_coverage.py +122 -0
  143. maproom/quotas/fetch.py +124 -0
  144. maproom/quotas/load.py +41 -0
  145. maproom/quotas/model.py +178 -0
  146. maproom/quotas/outcome_ledger.py +245 -0
  147. maproom/quotas/quota_request_sync.py +221 -0
  148. maproom/quotas/show.py +73 -0
  149. maproom/quotas/status.py +206 -0
  150. maproom/quotas/store.py +161 -0
  151. maproom/redaction.py +157 -0
  152. maproom/reference_data/__init__.py +1 -0
  153. maproom/reference_data/aws/aws_prices.csv +25562 -0
  154. maproom/reference_data/aws/capabilities.csv +1346 -0
  155. maproom/reference_data/aws/instance_types.csv +1346 -0
  156. maproom/reference_data/azure/azure_prices.csv +1 -0
  157. maproom/reference_data/azure/vm_types.csv +1 -0
  158. maproom/reference_data/benchmarks/cpu-lscpu-v2-instances.json +27 -0
  159. maproom/reference_data/benchmarks/safe-moves-v1.json +328 -0
  160. maproom/reference_data/manifest.json +174 -0
  161. maproom/reference_data/manifest.py +69 -0
  162. maproom/reservations/__init__.py +17 -0
  163. maproom/reservations/aws.py +76 -0
  164. maproom/reservations/azure.py +36 -0
  165. maproom/reservations/commands.py +149 -0
  166. maproom/reservations/load.py +41 -0
  167. maproom/reservations/model.py +316 -0
  168. maproom/reservations/show.py +64 -0
  169. maproom/reservations/status.py +181 -0
  170. maproom/reservations/store.py +391 -0
  171. maproom/resources.py +54 -0
  172. maproom/root_help.py +251 -0
  173. maproom/saving_plans/__init__.py +15 -0
  174. maproom/saving_plans/aws.py +73 -0
  175. maproom/saving_plans/commands.py +122 -0
  176. maproom/saving_plans/load.py +41 -0
  177. maproom/saving_plans/model.py +101 -0
  178. maproom/saving_plans/show.py +64 -0
  179. maproom/saving_plans/status.py +118 -0
  180. maproom/saving_plans/store.py +173 -0
  181. maproom/secret_egress_gate.py +108 -0
  182. maproom/service/install_id.py +60 -0
  183. maproom/settings/__init__.py +1 -0
  184. maproom/settings/defaults.py +73 -0
  185. maproom/settings/init.py +143 -0
  186. maproom/settings/model.py +105 -0
  187. maproom/settings/product_version_change.py +343 -0
  188. maproom/settings/product_versions.py +68 -0
  189. maproom/settings/set.py +347 -0
  190. maproom/settings/show.py +227 -0
  191. maproom/settings/write.py +273 -0
  192. maproom/snapshot_time.py +27 -0
  193. maproom-0.2.0.dist-info/METADATA +263 -0
  194. maproom-0.2.0.dist-info/RECORD +199 -0
  195. maproom-0.2.0.dist-info/WHEEL +5 -0
  196. maproom-0.2.0.dist-info/entry_points.txt +2 -0
  197. maproom-0.2.0.dist-info/licenses/LICENSE +201 -0
  198. maproom-0.2.0.dist-info/licenses/NOTICE +72 -0
  199. maproom-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,401 @@
1
+ """AWS Compute Optimizer comparison for analyze (NEXT-1 W5)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from dataclasses import dataclass
8
+ from decimal import Decimal
9
+ from typing import Any, Literal
10
+
11
+ from maproom.cliio.runner import CliTimeoutError
12
+
13
+ from maproom.pricing import PriceTable
14
+ from maproom.redaction import redact_text
15
+
16
+ _OPTIMIZER_API = "aws_compute_optimizer_get_ec2_instance_recommendations"
17
+
18
+ Finding = Literal["Overprovisioned", "Underprovisioned", "Optimized", "NotOptimized"]
19
+ GapStatus = Literal[
20
+ "cheaper_found",
21
+ "provider_none",
22
+ "provider_agrees",
23
+ "unavailable",
24
+ ]
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class ProviderRecommendation:
29
+ finding: Finding
30
+ instance_type: str
31
+ estimated_monthly_savings_usd: str | None
32
+ lookback_days: int | None
33
+ current_instance_type: str | None
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class ProviderUnavailable:
38
+ reason: str
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class ProviderNone:
43
+ """Compute Optimizer returned no instance recommendations."""
44
+
45
+
46
+ ProviderFetchResult = ProviderRecommendation | ProviderUnavailable | ProviderNone
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class ProviderGap:
51
+ status: GapStatus
52
+ reason: str
53
+
54
+
55
+ def ec2_instance_arn(account_id: str, region: str, instance_id: str) -> str:
56
+ """Build the EC2 instance ARN used for Compute Optimizer reads."""
57
+ return f"arn:aws:ec2:{region}:{account_id}:instance/{instance_id}"
58
+
59
+
60
+ def _normalize_finding(raw: str) -> Finding:
61
+ text = (raw or "").strip().upper().replace("-", "_")
62
+ mapping: dict[str, Finding] = {
63
+ "OVER_PROVISIONED": "Overprovisioned",
64
+ "UNDER_PROVISIONED": "Underprovisioned",
65
+ "OPTIMIZED": "Optimized",
66
+ "NOT_OPTIMIZED": "NotOptimized",
67
+ }
68
+ if text in mapping:
69
+ return mapping[text]
70
+ if text == "OVERPROVISIONED":
71
+ return "Overprovisioned"
72
+ if text == "UNDERPROVISIONED":
73
+ return "Underprovisioned"
74
+ return "NotOptimized"
75
+
76
+
77
+ def _stderr_lower(response: dict[str, Any]) -> str:
78
+ return str(response.get("stderr") or "").lower()
79
+
80
+
81
+ def _runner_document(result: Any) -> dict[str, Any]:
82
+ response: dict[str, Any] = {
83
+ "exit_code": result.exit_code,
84
+ "stdout_json": {},
85
+ "stderr": result.stderr,
86
+ }
87
+ if result.stdout.strip():
88
+ try:
89
+ response["stdout_json"] = json.loads(result.stdout)
90
+ except json.JSONDecodeError:
91
+ response["stdout_json"] = {"_raw_stdout": result.stdout}
92
+ return response
93
+
94
+
95
+ def _short_unavailable_reason(response: dict[str, Any]) -> str:
96
+ exit_code = int(response.get("exit_code", 0))
97
+ err = _stderr_lower(response)
98
+ if "optinrequired" in err or "opt in" in err:
99
+ return "opt_in_required"
100
+ if "accessdenied" in err or "not authorized" in err:
101
+ return "access_denied"
102
+ if exit_code in (253, 255) and "credential" in err:
103
+ return "not_logged_in"
104
+ snippet = redact_text(str(response.get("stderr") or "").strip())
105
+ snippet = re.sub(r"\s+", " ", snippet)
106
+ if len(snippet) > 120:
107
+ snippet = snippet[:117] + "..."
108
+ return snippet or f"exit_{exit_code}"
109
+
110
+
111
+ def parse_compute_optimizer_response(response: dict[str, Any]) -> ProviderFetchResult:
112
+ """Parse a fixture-shaped CLI response into a provider outcome."""
113
+ exit_code = int(response.get("exit_code", 0))
114
+ if exit_code != 0:
115
+ return ProviderUnavailable(reason=_short_unavailable_reason(response))
116
+
117
+ payload = response.get("stdout_json") or {}
118
+ rows = payload.get("instanceRecommendations")
119
+ if rows is None:
120
+ rows = []
121
+ if not isinstance(rows, list):
122
+ return ProviderUnavailable(reason="invalid_response")
123
+
124
+ if not rows:
125
+ return ProviderNone()
126
+
127
+ row = rows[0] if isinstance(rows[0], dict) else {}
128
+ finding_raw = str(row.get("finding") or "")
129
+ finding = _normalize_finding(finding_raw)
130
+ current_type = str(row.get("currentInstanceType") or "").strip() or None
131
+ lookback_raw = row.get("lookBackPeriodInDays")
132
+ lookback_days: int | None
133
+ if lookback_raw is None:
134
+ lookback_days = None
135
+ else:
136
+ lookback_days = int(float(lookback_raw))
137
+
138
+ options = row.get("recommendationOptions") or []
139
+ if not isinstance(options, list) or not options:
140
+ if finding == "Optimized":
141
+ return ProviderNone()
142
+ return ProviderUnavailable(reason="missing_recommendation_options")
143
+
144
+ top = options[0] if isinstance(options[0], dict) else {}
145
+ instance_type = str(top.get("instanceType") or "").strip()
146
+ if not instance_type:
147
+ if finding == "Optimized":
148
+ return ProviderNone()
149
+ return ProviderUnavailable(reason="missing_instance_type")
150
+
151
+ savings_block = top.get("savingsOpportunity") or {}
152
+ estimated = savings_block.get("estimatedMonthlySavings") or {}
153
+ savings_value = estimated.get("value")
154
+ savings_str: str | None
155
+ if savings_value is None:
156
+ savings_str = None
157
+ else:
158
+ savings_str = _usd_amount_str(Decimal(str(savings_value)))
159
+
160
+ return ProviderRecommendation(
161
+ finding=finding,
162
+ instance_type=instance_type,
163
+ estimated_monthly_savings_usd=savings_str,
164
+ lookback_days=lookback_days,
165
+ current_instance_type=current_type,
166
+ )
167
+
168
+
169
+ def _usd_amount_str(value: Decimal) -> str:
170
+ rounded = value.quantize(Decimal("0.01"))
171
+ integral = rounded.to_integral_value()
172
+ if rounded == integral:
173
+ return str(int(integral))
174
+ text = format(rounded.normalize(), "f")
175
+ if "." in text:
176
+ text = text.rstrip("0").rstrip(".")
177
+ return text
178
+
179
+
180
+ def fetch_provider_recommendation(
181
+ instance_arn_or_id: str,
182
+ region: str,
183
+ runner: Any,
184
+ ) -> ProviderFetchResult:
185
+ """Call Compute Optimizer for one instance ARN (or pass-through identifier)."""
186
+ argv = [
187
+ "compute-optimizer",
188
+ "get-ec2-instance-recommendations",
189
+ "--instance-arns",
190
+ instance_arn_or_id,
191
+ "--region",
192
+ region,
193
+ "--output",
194
+ "json",
195
+ ]
196
+ instance_id = (
197
+ instance_arn_or_id.rsplit("/", 1)[-1]
198
+ if instance_arn_or_id.startswith("arn:")
199
+ else instance_arn_or_id
200
+ )
201
+ from maproom.analyze.local_reads import document_from_cli_result, run_cached_analyze_read
202
+
203
+ try:
204
+ result = run_cached_analyze_read(
205
+ runner,
206
+ "aws",
207
+ argv,
208
+ api_id="aws_compute_optimizer_get_ec2_instance_recommendations",
209
+ region=region,
210
+ instance_id=instance_id,
211
+ record=False,
212
+ pagination="none",
213
+ )
214
+ except CliTimeoutError:
215
+ return ProviderUnavailable(reason="timeout")
216
+ response = document_from_cli_result(result)
217
+ return parse_compute_optimizer_response(response)
218
+
219
+
220
+ def resolve_provider_recommendation(
221
+ *,
222
+ account_id: str,
223
+ region: str,
224
+ instance_id: str,
225
+ runner: Any,
226
+ local_only: bool,
227
+ ) -> ProviderFetchResult:
228
+ """Load provider recommendation or degrade without aborting analyze."""
229
+ if local_only:
230
+ return ProviderUnavailable(reason="local_only")
231
+ arn = ec2_instance_arn(account_id, region, instance_id)
232
+ try:
233
+ return fetch_provider_recommendation(arn, region, runner)
234
+ except CliTimeoutError:
235
+ return ProviderUnavailable(reason="timeout")
236
+ except Exception as exc:
237
+ reason = redact_text(str(exc).split(";")[0].strip() or type(exc).__name__)
238
+ return ProviderUnavailable(reason=reason)
239
+
240
+
241
+ def _engine_top_type(doc: dict[str, Any]) -> str | None:
242
+ recs = doc.get("recommendations") or []
243
+ if recs:
244
+ return str(recs[0].get("instance_type") or "").strip() or None
245
+ cond = doc.get("conditional_moves") or []
246
+ if cond:
247
+ return str(cond[0].get("instance_type") or "").strip() or None
248
+ return None
249
+
250
+
251
+ def _engine_top_monthly(doc: dict[str, Any]) -> Decimal | None:
252
+ recs = doc.get("recommendations") or []
253
+ if recs:
254
+ raw = recs[0].get("price_per_month_usd")
255
+ else:
256
+ cond = doc.get("conditional_moves") or []
257
+ raw = cond[0].get("price_per_month_usd") if cond else None
258
+ if raw is None:
259
+ return None
260
+ try:
261
+ return Decimal(str(raw))
262
+ except Exception:
263
+ return None
264
+
265
+
266
+ def _engine_has_surface(doc: dict[str, Any]) -> bool:
267
+ return bool(doc.get("recommendations") or doc.get("conditional_moves"))
268
+
269
+
270
+ def compare(
271
+ engine_doc: dict[str, Any],
272
+ provider: ProviderFetchResult,
273
+ prices: PriceTable,
274
+ *,
275
+ region: str,
276
+ ) -> ProviderGap:
277
+ """Compare local engine output to the provider recommendation."""
278
+ if isinstance(provider, ProviderUnavailable):
279
+ return ProviderGap(status="unavailable", reason=provider.reason)
280
+
281
+ engine_top = _engine_top_type(engine_doc)
282
+ engine_monthly = _engine_top_monthly(engine_doc)
283
+ has_surface = _engine_has_surface(engine_doc)
284
+
285
+ if isinstance(provider, ProviderNone):
286
+ if has_surface:
287
+ return ProviderGap(
288
+ status="provider_none",
289
+ reason="provider returned no recommendation",
290
+ )
291
+ return ProviderGap(status="provider_none", reason="both_none")
292
+
293
+ provider_type = provider.instance_type
294
+ if provider.finding == "Optimized" and not provider_type:
295
+ if has_surface:
296
+ return ProviderGap(
297
+ status="provider_none",
298
+ reason="provider returned no recommendation",
299
+ )
300
+ return ProviderGap(status="provider_none", reason="both_none")
301
+
302
+ if engine_top is None:
303
+ return ProviderGap(status="provider_none", reason="both_none")
304
+
305
+ if provider_type == engine_top:
306
+ return ProviderGap(
307
+ status="provider_agrees",
308
+ reason="same top instance type",
309
+ )
310
+
311
+ provider_monthly = prices.monthly(provider_type, region)
312
+ if provider_monthly is None:
313
+ return ProviderGap(
314
+ status="provider_agrees",
315
+ reason=f"provider type {provider_type} has no price in shipped file",
316
+ )
317
+
318
+ if engine_monthly is not None and engine_monthly < provider_monthly:
319
+ return ProviderGap(
320
+ status="cheaper_found",
321
+ reason=(
322
+ f"engine top {engine_top} at USD {_usd_amount_str(engine_monthly)}/mo "
323
+ f"below provider {provider_type} at USD {_usd_amount_str(provider_monthly)}/mo"
324
+ ),
325
+ )
326
+
327
+ return ProviderGap(
328
+ status="provider_agrees",
329
+ reason=(
330
+ f"provider_cheaper_or_equal: provider {provider_type} "
331
+ f"USD {_usd_amount_str(provider_monthly)}/mo"
332
+ ),
333
+ )
334
+
335
+
336
+ def provider_recommendation_document(
337
+ provider: ProviderFetchResult,
338
+ ) -> dict[str, Any] | None:
339
+ if isinstance(provider, ProviderRecommendation):
340
+ return {
341
+ "source": "aws_compute_optimizer",
342
+ "finding": provider.finding,
343
+ "instance_type": provider.instance_type,
344
+ "estimated_monthly_savings_usd": provider.estimated_monthly_savings_usd,
345
+ "lookback_days": provider.lookback_days,
346
+ }
347
+ return None
348
+
349
+
350
+ def attach_provider_comparison(
351
+ doc: dict[str, Any],
352
+ *,
353
+ provider: ProviderFetchResult,
354
+ region: str,
355
+ prices: PriceTable | None = None,
356
+ ) -> None:
357
+ """Add provider_recommendation and provider_gap to a recommendation document."""
358
+ from maproom.pricing import load_price_table
359
+
360
+ table = prices or load_price_table()
361
+ gap = compare(doc, provider, table, region=region)
362
+ doc["provider_recommendation"] = provider_recommendation_document(provider)
363
+ doc["provider_gap"] = {"status": gap.status, "reason": gap.reason}
364
+
365
+
366
+ def format_provider_tty(
367
+ doc: dict[str, Any],
368
+ ) -> list[str]:
369
+ """TTY lines for provider comparison (after candidates, before current instance)."""
370
+ provider = doc.get("provider_recommendation")
371
+ gap = doc.get("provider_gap") or {}
372
+ lines: list[str] = []
373
+ if provider:
374
+ finding = provider.get("finding") or "Unknown"
375
+ inst = provider.get("instance_type") or "unknown"
376
+ savings = provider.get("estimated_monthly_savings_usd")
377
+ lookback = provider.get("lookback_days")
378
+ savings_part = (
379
+ f"est. USD {savings}/mo" if savings is not None else "est. savings unknown"
380
+ )
381
+ lookback_part = (
382
+ f"{lookback}-day lookback" if lookback is not None else "lookback unknown"
383
+ )
384
+ lines.append(
385
+ f"Provider (Compute Optimizer): {finding} -> {inst} "
386
+ f"({savings_part}, {lookback_part})"
387
+ )
388
+ elif gap.get("status") == "unavailable":
389
+ lines.append(
390
+ "Provider (Compute Optimizer): unavailable "
391
+ f"({gap.get('reason') or 'unknown'})"
392
+ )
393
+ elif gap.get("status") == "provider_none":
394
+ lines.append("Provider (Compute Optimizer): no recommendation")
395
+ else:
396
+ lines.append("Provider (Compute Optimizer): no recommendation")
397
+
398
+ status = gap.get("status") or "unavailable"
399
+ reason = gap.get("reason") or ""
400
+ lines.append(f"Gap: {status} - {reason}")
401
+ return lines