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,118 @@
1
+ """Which recommend field groups maproom shares: product_version defaults + CLI overrides."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Iterable
6
+
7
+ SHARE_GROUPS: tuple[str, ...] = (
8
+ "purchase_option",
9
+ "metrics",
10
+ "reservations",
11
+ "series",
12
+ "quota",
13
+ )
14
+
15
+ _LEGACY_SHARE_ALIASES: dict[str, str] = {
16
+ "placement": "purchase_option",
17
+ "price": "purchase_option",
18
+ }
19
+
20
+ _KIND_TO_GROUP: dict[str, str] = {
21
+ "spot": "purchase_option",
22
+ "size": "metrics",
23
+ "safe_moves": "reservations",
24
+ "cover": "reservations",
25
+ "series": "series",
26
+ "quota": "quota",
27
+ "price": "purchase_option",
28
+ }
29
+
30
+
31
+ def _normalize_share_name(name: str) -> str:
32
+ text = str(name).strip().lower()
33
+ return _LEGACY_SHARE_ALIASES.get(text, text)
34
+
35
+
36
+ def default_share_groups(product_version: int) -> set[str]:
37
+ """Field groups enabled for each product_version (try-first complexity level).
38
+
39
+ 1 Local safe moves — no recommend field groups (shipped prices only).
40
+ 2 Remote downsize/upsize — purchase_option + metrics.
41
+ 3 Remote Spot-to-Spot — purchase_option + metrics (Spot context in purchase_option).
42
+ 4 Remote cross-family — + series; prior groups kept for fallback.
43
+ 5 Unused reservations — + reservations.
44
+ 6 Quota management — + quota.
45
+ """
46
+ groups: set[str] = set()
47
+ if product_version >= 2:
48
+ groups.add("purchase_option")
49
+ groups.add("metrics")
50
+ if product_version >= 4:
51
+ groups.add("series")
52
+ if product_version >= 5:
53
+ groups.add("reservations")
54
+ if product_version >= 6:
55
+ groups.add("quota")
56
+ return groups
57
+
58
+
59
+ class ShareCeilingError(ValueError):
60
+ """A share override names a field group above the configured product_version."""
61
+
62
+
63
+ def _ceiling_message(product_version: int, flag: str, name: str, group: str) -> str:
64
+ return (
65
+ f"{flag} {name} needs the {group} field group, which product_version "
66
+ f"{product_version} does not share. Raise product_version with "
67
+ "`maproom settings set product_version N` to use it."
68
+ )
69
+
70
+
71
+ def resolve_share_groups(
72
+ product_version: int,
73
+ *,
74
+ share: Iterable[str] | None = None,
75
+ omit: Iterable[str] | None = None,
76
+ recommend_kinds: Iterable[str] | None = None,
77
+ ) -> set[str]:
78
+ ceiling = default_share_groups(product_version)
79
+ groups = set(ceiling)
80
+ for name in share or ():
81
+ text = _normalize_share_name(str(name))
82
+ if text in SHARE_GROUPS:
83
+ if text not in ceiling:
84
+ raise ShareCeilingError(
85
+ _ceiling_message(product_version, "--share", str(name), text)
86
+ )
87
+ groups.add(text)
88
+ for name in omit or ():
89
+ text = _normalize_share_name(str(name))
90
+ groups.discard(text)
91
+ if recommend_kinds is not None:
92
+ normalized = [str(kind).strip().lower() for kind in recommend_kinds]
93
+ for kind in normalized:
94
+ group = _KIND_TO_GROUP.get(kind)
95
+ if group is not None and group not in ceiling:
96
+ raise ShareCeilingError(
97
+ _ceiling_message(product_version, "--recommend-kinds", kind, group)
98
+ )
99
+ wanted = {_KIND_TO_GROUP[kind] for kind in normalized if kind in _KIND_TO_GROUP}
100
+ groups &= wanted if wanted else groups
101
+ return groups
102
+
103
+
104
+ def share_groups_from_args(product_version: int, args: Any) -> set[str]:
105
+ share = getattr(args, "share", None) or ()
106
+ omit = getattr(args, "omit", None) or ()
107
+ kinds_raw = getattr(args, "recommend_kinds", None)
108
+ kinds: list[str] | None = None
109
+ if isinstance(kinds_raw, str) and kinds_raw.strip():
110
+ kinds = [part.strip() for part in kinds_raw.split(",") if part.strip()]
111
+ elif isinstance(kinds_raw, (list, tuple)):
112
+ kinds = [str(part).strip() for part in kinds_raw if str(part).strip()]
113
+ return resolve_share_groups(
114
+ product_version,
115
+ share=share,
116
+ omit=omit,
117
+ recommend_kinds=kinds,
118
+ )
@@ -0,0 +1,591 @@
1
+ """Local and service-backed recommendation output for analyze (OUTPUT_CONTRACT kind=recommendation)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from datetime import datetime, timezone
7
+ from decimal import Decimal
8
+ from typing import Any
9
+
10
+ from maproom.analyze.change_detection import (
11
+ InstanceTypeChange,
12
+ change_detection_document,
13
+ )
14
+ from maproom.analyze.engine import (
15
+ CURATED_REJECTED_LIMIT,
16
+ UtilizationSummary,
17
+ apply_change_cooldown,
18
+ candidate_to_document_item,
19
+ engine_metadata,
20
+ engine_settings_from_mapping,
21
+ evaluate_candidates,
22
+ evaluate_upsize_candidates,
23
+ merge_upsize_results,
24
+ rejected_to_document_item,
25
+ )
26
+ from maproom.analyze.shape import ShapeConstraint, attribute_tokens, restrict_engine_result
27
+ from maproom.analyze.utilization import UTILIZATION_LOOKBACK_DAYS
28
+ from maproom.analyze.workload import reconcile_instance_specs_evidence
29
+ from maproom.consent.service_upload_prompt import ENABLE_UPLOADS_HINT, LOCAL_ASSESSMENT_WARNING
30
+ from maproom.analyze.provider_comparison import (
31
+ ProviderFetchResult,
32
+ attach_provider_comparison,
33
+ format_provider_tty,
34
+ )
35
+ from maproom.analyze.specs import SpecCatalog, catalog_has_specs
36
+ from maproom.output.json_envelope import build_document, command_metadata, warning_item
37
+ from maproom.pricing import PriceTable, load_price_table
38
+ from maproom.quotas.status import (
39
+ Launchability,
40
+ QuotaState,
41
+ launchability_for_region,
42
+ quota_blocked_instance_types,
43
+ )
44
+ from maproom.resources import Ec2Target
45
+
46
+ SERVICE_UPLOAD_OFF_MESSAGE = (
47
+ "Service upload: off (no MAPROOM_RECOMMEND_URL configured)"
48
+ )
49
+
50
+ _HOURS_PER_MONTH = Decimal(730)
51
+ _CODED_WARNING = re.compile(r"^([a-z][a-z0-9]*(?:_[a-z0-9]+)*)\s*:\s*(.*)$", re.DOTALL)
52
+
53
+
54
+ def _warning_from_text(text: str) -> dict[str, Any]:
55
+ """Snake_case token before a colon becomes the code. Other text is a notice."""
56
+ match = _CODED_WARNING.match(text)
57
+ if match:
58
+ return warning_item(match.group(1), match.group(2))
59
+ return warning_item("notice", text)
60
+
61
+
62
+ def _usd_amount_str(value: Decimal) -> str:
63
+ rounded = value.quantize(Decimal("0.001"))
64
+ integral = rounded.to_integral_value()
65
+ if rounded == integral:
66
+ return str(int(integral))
67
+ text = format(rounded.normalize(), "f")
68
+ if "." in text:
69
+ text = text.rstrip("0").rstrip(".")
70
+ return text
71
+
72
+
73
+ def _monthly_str(table: PriceTable, instance_type: str, region: str) -> str | None:
74
+ monthly = table.monthly(instance_type, region)
75
+ if monthly is None:
76
+ return None
77
+ return _usd_amount_str(monthly)
78
+
79
+
80
+ def _hourly_str(table: PriceTable, instance_type: str, region: str) -> str | None:
81
+ hourly = table.hourly(instance_type, region)
82
+ if hourly is None:
83
+ return None
84
+ return _usd_amount_str(hourly)
85
+
86
+
87
+ def _overall_confidence(missing_evidence: list[str]) -> str:
88
+ if not missing_evidence:
89
+ return "HIGH"
90
+ if len(missing_evidence) <= 2:
91
+ return "MEDIUM"
92
+ return "LOW"
93
+
94
+
95
+ def _current_metrics(
96
+ profile: dict[str, Any],
97
+ *,
98
+ region: str,
99
+ table: PriceTable,
100
+ warnings: list[str],
101
+ spec_catalog: SpecCatalog | None = None,
102
+ ) -> dict[str, Any]:
103
+ cpu = (profile.get("utilization") or {}).get("cpu") or {}
104
+ instance_type = profile.get("instance_type") or ""
105
+ monthly_str = _monthly_str(table, instance_type, region)
106
+ hourly_str = _hourly_str(table, instance_type, region)
107
+ if monthly_str is None or hourly_str is None:
108
+ warnings.append(
109
+ f"price not in shipped file for current type {instance_type} in {region}"
110
+ )
111
+ monthly_str = "0"
112
+ hourly_str = "0"
113
+ metrics: dict[str, Any] = {
114
+ "price_per_hour_usd": hourly_str,
115
+ "price_per_month_usd": monthly_str,
116
+ "cpu_p95_pct": cpu.get("p95"),
117
+ "memory_p95_pct": None,
118
+ "network_p95_mbps": None,
119
+ }
120
+ if catalog_has_specs(spec_catalog):
121
+ spec = spec_catalog.current
122
+ if spec.vcpus > 0:
123
+ metrics["vcpus"] = spec.vcpus
124
+ if spec.memory_mib > 0:
125
+ metrics["memory_mib"] = spec.memory_mib
126
+ return metrics
127
+
128
+
129
+ def _verdict_label(placement: str) -> str:
130
+ if placement == "ideally_placed":
131
+ return "well placed"
132
+ if placement == "easy_move":
133
+ return "likely oversized"
134
+ if placement == "undersized":
135
+ return "undersized (urgent upsize)"
136
+ return "conditional savings available"
137
+
138
+
139
+ def _placement_from_engine(
140
+ recommendations: list[Any],
141
+ conditional: list[Any],
142
+ ) -> str:
143
+ if any("URGENT_UPSIZE" in (getattr(item, "migration_options", None) or []) for item in recommendations):
144
+ return "undersized"
145
+ if any(
146
+ isinstance(item, dict) and "URGENT_UPSIZE" in (item.get("migration_options") or [])
147
+ for item in recommendations
148
+ ):
149
+ return "undersized"
150
+ if recommendations:
151
+ return "easy_move"
152
+ if conditional:
153
+ return "conditional_move"
154
+ return "ideally_placed"
155
+
156
+
157
+ def _annotate_launchability(
158
+ items: list[dict[str, Any]],
159
+ *,
160
+ region: str,
161
+ quota_state: QuotaState | None,
162
+ headroom_pct: int,
163
+ ) -> list[dict[str, Any]]:
164
+ if quota_state is None:
165
+ return items
166
+ status = launchability_for_region(quota_state, region=region, headroom_pct=headroom_pct)
167
+ annotated: list[dict[str, Any]] = []
168
+ for item in items:
169
+ copy = dict(item)
170
+ copy["quota_launchability"] = status
171
+ annotated.append(copy)
172
+ return annotated
173
+
174
+
175
+ def _cpu_utilization_summary(
176
+ profile: dict[str, Any],
177
+ *,
178
+ downsize_cpu_reliable: bool = True,
179
+ ) -> UtilizationSummary:
180
+ cpu = (profile.get("utilization") or {}).get("cpu") or {}
181
+ p95 = cpu.get("p95")
182
+ if p95 is None:
183
+ return UtilizationSummary(cpu_p95_pct=None, downsize_cpu_reliable=downsize_cpu_reliable)
184
+ return UtilizationSummary(
185
+ cpu_p95_pct=float(p95),
186
+ downsize_cpu_reliable=downsize_cpu_reliable,
187
+ )
188
+
189
+
190
+ def _empty_engine_payload(
191
+ *,
192
+ warnings: list[str],
193
+ ) -> tuple[str, list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]], int, dict[str, int], dict[str, Any] | None]:
194
+ warnings.append("candidate_engine_skipped: instance specs unavailable")
195
+ return "ideally_placed", [], [], [], 0, {}, None
196
+
197
+
198
+ def build_recommendation_document(
199
+ *,
200
+ target: Ec2Target,
201
+ profile: dict[str, Any],
202
+ missing_evidence: list[str],
203
+ local_only: bool,
204
+ declined_upload: bool = False,
205
+ service_upload_disabled: bool = False,
206
+ extra_warnings: list[str] | None = None,
207
+ quota_state: QuotaState | None = None,
208
+ quota_headroom_pct: int = 10,
209
+ spec_catalog: SpecCatalog | None = None,
210
+ effective_settings: dict[str, Any] | None = None,
211
+ provider_fetch: ProviderFetchResult | None = None,
212
+ instance_type_change: InstanceTypeChange | None = None,
213
+ utilization_window_start: str | None = None,
214
+ effective_utilization_window_days: float | None = None,
215
+ now: datetime | None = None,
216
+ shape: ShapeConstraint | None = None,
217
+ ) -> dict[str, Any]:
218
+ """Return OUTPUT_CONTRACT kind=recommendation payload from a workload profile."""
219
+ profile, missing_evidence = reconcile_instance_specs_evidence(
220
+ profile, missing_evidence, spec_catalog
221
+ )
222
+ instance_type = profile.get("instance_type") or ""
223
+ table = load_price_table()
224
+ warnings: list[str] = list(extra_warnings or [])
225
+ if local_only:
226
+ warnings.append(
227
+ "local-only assessment: personalized service recommendations unavailable"
228
+ )
229
+ elif declined_upload:
230
+ warnings.append(LOCAL_ASSESSMENT_WARNING)
231
+ warnings.append(ENABLE_UPLOADS_HINT)
232
+
233
+ region = profile.get("region") or target.region
234
+ engine_block: dict[str, Any] | None = None
235
+ rejected_by_reason: dict[str, int] = {}
236
+
237
+ change = instance_type_change or InstanceTypeChange()
238
+ now_utc = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
239
+ downsize_reliable = "post_change_utilization" not in missing_evidence
240
+
241
+ if catalog_has_specs(spec_catalog):
242
+ engine_settings = engine_settings_from_mapping(effective_settings or {})
243
+ utilization = _cpu_utilization_summary(
244
+ profile,
245
+ downsize_cpu_reliable=downsize_reliable,
246
+ )
247
+ quota_blocked = quota_blocked_instance_types(
248
+ quota_state,
249
+ region=region,
250
+ headroom_pct=quota_headroom_pct,
251
+ offered_specs=spec_catalog.specs,
252
+ )
253
+ engine_result = evaluate_candidates(
254
+ spec_catalog.current,
255
+ spec_catalog,
256
+ table,
257
+ utilization,
258
+ engine_settings,
259
+ quota_blocked=quota_blocked,
260
+ )
261
+ upsizes = evaluate_upsize_candidates(
262
+ spec_catalog.current,
263
+ spec_catalog,
264
+ table,
265
+ utilization,
266
+ engine_settings,
267
+ quota_blocked=quota_blocked,
268
+ )
269
+ engine_result = merge_upsize_results(
270
+ engine_result,
271
+ upsizes,
272
+ max_recommendations=engine_settings.max_recommendations,
273
+ )
274
+ engine_result = apply_change_cooldown(
275
+ engine_result,
276
+ cooldown_active=change.cooldown_active(
277
+ now_utc,
278
+ engine_settings.min_days_since_change,
279
+ ),
280
+ max_conditional=engine_settings.max_conditional,
281
+ )
282
+ if shape is not None:
283
+ engine_result = restrict_engine_result(
284
+ engine_result,
285
+ current=spec_catalog.current,
286
+ catalog=spec_catalog,
287
+ shape=shape,
288
+ )
289
+ warnings.append(f"shape: {shape.summary()}")
290
+ placement = _placement_from_engine(
291
+ engine_result.recommendations,
292
+ engine_result.conditional,
293
+ )
294
+ recommendations = [
295
+ _attach_shape_tokens(
296
+ candidate_to_document_item(item, rank=index + 1, region=region),
297
+ current=spec_catalog.current,
298
+ catalog=spec_catalog,
299
+ )
300
+ for index, item in enumerate(engine_result.recommendations)
301
+ ]
302
+ conditional = [
303
+ _attach_shape_tokens(
304
+ candidate_to_document_item(item, region=region),
305
+ current=spec_catalog.current,
306
+ catalog=spec_catalog,
307
+ )
308
+ for item in engine_result.conditional
309
+ ]
310
+ rejected_all = [rejected_to_document_item(item) for item in engine_result.rejected]
311
+ rejected = rejected_all[:CURATED_REJECTED_LIMIT]
312
+ rejected_total = engine_result.rejected_total
313
+ rejected_by_reason = dict(engine_result.rejected_by_reason)
314
+ engine_block = engine_metadata(engine_settings)
315
+ else:
316
+ placement, recommendations, conditional, rejected, rejected_total, rejected_by_reason, engine_block = (
317
+ _empty_engine_payload(warnings=warnings)
318
+ )
319
+
320
+ recommendations = _annotate_launchability(
321
+ recommendations,
322
+ region=region,
323
+ quota_state=quota_state,
324
+ headroom_pct=quota_headroom_pct,
325
+ )
326
+ conditional = _annotate_launchability(
327
+ conditional,
328
+ region=region,
329
+ quota_state=quota_state,
330
+ headroom_pct=quota_headroom_pct,
331
+ )
332
+
333
+ payload: dict[str, Any] = {
334
+ "cloud": target.cloud,
335
+ "placement": placement,
336
+ "confidence": _overall_confidence(missing_evidence),
337
+ "missing_evidence": list(missing_evidence),
338
+ "target": {
339
+ "instance_id": target.instance_id,
340
+ "region": region,
341
+ "instance_type": instance_type,
342
+ "pricing_model": "on-demand",
343
+ },
344
+ "current": _current_metrics(
345
+ profile,
346
+ region=region,
347
+ table=table,
348
+ warnings=warnings,
349
+ spec_catalog=spec_catalog,
350
+ ),
351
+ "recommendations": recommendations,
352
+ "conditional_moves": conditional,
353
+ "rejected": rejected,
354
+ "rejected_total": rejected_total,
355
+ "rejected_by_reason": rejected_by_reason,
356
+ "pricing_data_as_of": table.published_at,
357
+ "utilization_window_days": UTILIZATION_LOOKBACK_DAYS,
358
+ "change_detection": change_detection_document(
359
+ change,
360
+ now=now_utc,
361
+ min_days_since_change=int(
362
+ (engine_settings_from_mapping(effective_settings or {})).min_days_since_change
363
+ if catalog_has_specs(spec_catalog)
364
+ else 7
365
+ ),
366
+ ),
367
+ }
368
+ if utilization_window_start is not None:
369
+ payload["utilization_window_start"] = utilization_window_start
370
+ if effective_utilization_window_days is not None:
371
+ payload["effective_utilization_window_days"] = effective_utilization_window_days
372
+ if engine_block is not None:
373
+ payload["engine"] = engine_block
374
+ if spec_catalog is not None:
375
+ payload["spec_source"] = spec_catalog.source
376
+
377
+ if provider_fetch is not None:
378
+ attach_provider_comparison(
379
+ payload,
380
+ provider=provider_fetch,
381
+ region=region,
382
+ prices=table,
383
+ )
384
+
385
+ if service_upload_disabled:
386
+ payload["service"] = {
387
+ "status": "disabled",
388
+ "reason": "no_recommendation_url",
389
+ }
390
+
391
+ return build_document(
392
+ schema_type="recommendation",
393
+ schema_id="maproom.recommendation",
394
+ metadata=command_metadata("analyze", now=now_utc),
395
+ errors=[],
396
+ warnings=[_warning_from_text(text) for text in warnings],
397
+ payload=payload,
398
+ )
399
+
400
+
401
+ def _attach_shape_tokens(
402
+ item: dict[str, Any],
403
+ *,
404
+ current: Any,
405
+ catalog: SpecCatalog,
406
+ ) -> dict[str, Any]:
407
+ spec = catalog.specs.get(str(item.get("instance_type") or ""))
408
+ if spec is None:
409
+ item["modifies"] = []
410
+ item["keeps"] = []
411
+ return item
412
+ modifies, keeps = attribute_tokens(current, spec)
413
+ item["modifies"] = modifies
414
+ item["keeps"] = keeps
415
+ return item
416
+
417
+
418
+ def _shape_phrase(item: dict[str, Any]) -> str:
419
+ modifies = [str(value).removeprefix("modify_") for value in item.get("modifies") or []]
420
+ keeps = [str(value).removeprefix("keep_") for value in item.get("keeps") or []]
421
+ if not modifies and not keeps:
422
+ return ""
423
+ change = ", ".join(modifies) if modifies else "nothing"
424
+ held = ", ".join(keeps) if keeps else "nothing"
425
+ return f"change: {change}; keep: {held}"
426
+
427
+
428
+ def _launchability_label(status: Launchability | str | None) -> str:
429
+ if status == "sufficient":
430
+ return "quota: sufficient"
431
+ if status == "blocked":
432
+ return "quota: blocked"
433
+ return "quota: unknown"
434
+
435
+
436
+ def rejected_summary_line(rejected_by_reason: dict[str, int]) -> str:
437
+ if not rejected_by_reason:
438
+ return ""
439
+ parts = sorted(
440
+ rejected_by_reason.items(),
441
+ key=lambda item: (-item[1], item[0]),
442
+ )
443
+ summary = ", ".join(f"{code} {count}" for code, count in parts)
444
+ total = sum(rejected_by_reason.values())
445
+ return f"Rejected {total} ({summary})"
446
+
447
+
448
+ def format_recommendation_tty(
449
+ doc: dict[str, Any],
450
+ *,
451
+ account_id: str,
452
+ show_all: bool,
453
+ plan_summary: str | None = None,
454
+ reservations_summary: str | None = None,
455
+ saving_plans_summary: str | None = None,
456
+ quotas_summary: str | None = None,
457
+ ) -> str:
458
+ """Verdict-first human report for analyze TTY mode."""
459
+ target = doc["target"]
460
+ plan_segment = plan_summary if plan_summary is not None else "plan: none"
461
+ reservations_segment = (
462
+ reservations_summary
463
+ if reservations_summary is not None
464
+ else "reservations: none loaded (on-demand pricing)"
465
+ )
466
+ saving_plans_segment = (
467
+ saving_plans_summary
468
+ if saving_plans_summary is not None
469
+ else "savings-plans: none loaded (on-demand pricing)"
470
+ )
471
+ quotas_segment = (
472
+ quotas_summary if quotas_summary is not None else "quotas: not loaded"
473
+ )
474
+ inventory_segment = (
475
+ f"inventory: {quotas_segment}; {reservations_segment}; {saving_plans_segment}"
476
+ )
477
+ lines = [
478
+ (
479
+ f"Analysis: {target['instance_id']} · AWS {account_id} · "
480
+ f"{target['region']}"
481
+ ),
482
+ f"Using: {plan_segment} · {inventory_segment}",
483
+ f"Verdict: {_verdict_label(doc['placement'])}",
484
+ ]
485
+
486
+ missing = doc.get("missing_evidence") or []
487
+ if missing:
488
+ lines.append("")
489
+ lines.append("Input quality:")
490
+ lines.append(" missing: " + ", ".join(missing))
491
+ if "reservation_coverage" in missing:
492
+ lines.append(
493
+ " reservation coverage unknown: savings estimates use on-demand pricing"
494
+ )
495
+ if "quota_headroom" in missing:
496
+ lines.append(
497
+ " quota headroom unknown: launchability not evaluated for candidates"
498
+ )
499
+
500
+ recs = doc.get("recommendations") or []
501
+ if recs:
502
+ lines.append("")
503
+ lines.append("Choices:")
504
+ for item in recs:
505
+ launch = item.get("quota_launchability")
506
+ launch_suffix = (
507
+ f" {_launchability_label(launch)}" if launch else ""
508
+ )
509
+ lines.append(
510
+ f" {item['rank']}. {item['instance_type']:<12} "
511
+ f"USD {item['price_per_month_usd']}/mo "
512
+ f"save USD {item['savings_per_month_usd']}/mo "
513
+ f"({item['savings_pct']}%) confidence: {item['confidence']}"
514
+ f"{launch_suffix}"
515
+ )
516
+ phrase = _shape_phrase(item)
517
+ if phrase:
518
+ lines.append(f" {phrase}")
519
+ elif doc["placement"] == "ideally_placed":
520
+ lines.append("")
521
+ lines.append(
522
+ "Nothing cheaper meets the observed requirements with the current constraints."
523
+ )
524
+
525
+ conditional_moves = doc.get("conditional_moves") or []
526
+ if conditional_moves and (show_all or len(conditional_moves) <= 3):
527
+ lines.append("")
528
+ lines.append("Conditional:")
529
+ for move in conditional_moves:
530
+ opts = ", ".join(move.get("migration_options") or [])
531
+ phrase = _shape_phrase(move)
532
+ detail = phrase or f"options: {opts}"
533
+ lines.append(
534
+ f" {move['instance_type']:<12} "
535
+ f"USD {move['price_per_month_usd']}/mo "
536
+ f"save USD {move['savings_per_month_usd']}/mo "
537
+ f"({move['savings_pct']}%) {detail}"
538
+ )
539
+
540
+ rejected_line = rejected_summary_line(doc.get("rejected_by_reason") or {})
541
+ if rejected_line:
542
+ lines.append("")
543
+ lines.append(rejected_line)
544
+
545
+ if doc.get("provider_gap") is not None:
546
+ lines.append("")
547
+ lines.extend(format_provider_tty(doc))
548
+
549
+ if show_all:
550
+ for rejected in doc.get("rejected") or []:
551
+ lines.append(
552
+ f" rejected: {rejected['instance_type']:<12} "
553
+ f"{rejected['reason_code']}: {rejected['reason']}"
554
+ )
555
+
556
+ current = doc.get("current") or {}
557
+ lines.append("")
558
+ lines.append(
559
+ f"Current instance: {target['instance_type']} · on-demand · "
560
+ f"USD {current.get('price_per_month_usd', '0')}/mo"
561
+ )
562
+ if "reservation_coverage" in missing:
563
+ lines.append(
564
+ "Savings use on-demand pricing because reservation coverage is unknown."
565
+ )
566
+ change = doc.get("change_detection") or {}
567
+ if change.get("cooldown_active") and change.get("changed_at"):
568
+ changed_raw = str(change["changed_at"]).replace("Z", "+00:00")
569
+ changed = datetime.fromisoformat(changed_raw).astimezone(timezone.utc)
570
+ days_ago = max(0, (datetime.now(timezone.utc) - changed).days)
571
+ until = change.get("cooldown_until") or ""
572
+ source = change.get("detection_source") or "none"
573
+ lines.append(
574
+ f"Instance type changed {days_ago} days ago ({source}); "
575
+ f"downsizing is on hold until {until.replace('T', ' ').replace('Z', ' UTC')}"
576
+ )
577
+ effective_days = doc.get("effective_utilization_window_days")
578
+ window_line = f"utilization window: {doc['utilization_window_days']} days"
579
+ if effective_days is not None:
580
+ window_line += f" ({effective_days:.1f} days post-change)"
581
+ lines.append(
582
+ f"Pricing data: {doc['pricing_data_as_of']} · "
583
+ f"{window_line}"
584
+ )
585
+ service = doc.get("service")
586
+ if isinstance(service, dict) and service.get("status") == "disabled":
587
+ lines.append(SERVICE_UPLOAD_OFF_MESSAGE)
588
+ for warning in doc.get("warnings") or []:
589
+ message = warning["message"] if isinstance(warning, dict) else warning
590
+ lines.append(f"Note: {message}")
591
+ return "\n".join(lines)