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,1467 @@
1
+ """Execute doctor checks and format output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import time
7
+ from datetime import datetime, timezone
8
+ from typing import Any
9
+
10
+ from maproom.consent import require_cloud_read_consent, require_service_upload_consent
11
+ from maproom.consent.service_upload_gate import (
12
+ FLEETFIT_POLICY_ACTION,
13
+ fleetfit_missing_policy_message,
14
+ )
15
+ from maproom.consent.prompt import CLOUD_READ_FLAG_GRANT_LINE
16
+ from maproom.doctor.checks import (
17
+ AZURE_CLI_INSTALL_REMEDIATION,
18
+ CLOUD_READ_CONSENT_REMEDIATION,
19
+ DATA_SOURCE_CHECKS,
20
+ CheckResult,
21
+ run_identity_checks,
22
+ run_prerequisite_checks,
23
+ )
24
+ from maproom.doctor.context import DoctorContext
25
+ from maproom.consent.gate import CloudReadGateOutcome
26
+ from maproom.exitcodes import RUNTIME, SUCCESS
27
+ from maproom.output.json_envelope import (
28
+ build_document,
29
+ command_metadata,
30
+ error_item,
31
+ print_json,
32
+ warning_item,
33
+ )
34
+ from maproom.output.redact import redact
35
+ from maproom.doctor.display import (
36
+ interactive_check_fact,
37
+ interactive_display_key,
38
+ interactive_muted_detail_lines,
39
+ )
40
+ from maproom.output.terminal import (
41
+ ANSI_RESET,
42
+ ansi_color_enabled,
43
+ colorize_muted,
44
+ colorize_status_word,
45
+ colorize_success_text,
46
+ highlight_cli_commands,
47
+ )
48
+ from maproom.paths import settings_read_file
49
+ from maproom.quotas.status import read_quota_state, stale_quota_warning
50
+ from maproom.reservations.status import read_inventory_state, stale_reservation_warning
51
+ from maproom.saving_plans.status import (
52
+ read_saving_plan_state,
53
+ stale_saving_plan_warning,
54
+ )
55
+ from maproom.settings.model import load_consent_state, product_version
56
+ from maproom.settings.product_versions import MAX_PRODUCT_VERSION
57
+
58
+ DOCTOR_NEXT_STEP = "maproom analyze aws"
59
+ _NEXT_STEP_BY_CLOUD = {
60
+ "aws": "maproom analyze aws",
61
+ "azure": "maproom analyze azure",
62
+ }
63
+ _PREREQUISITE_CHECK_NAMES = frozenset(
64
+ {
65
+ "python_version",
66
+ "platform_info",
67
+ "aws_cli_version_floor",
68
+ "az_cli_version_floor",
69
+ }
70
+ )
71
+
72
+ _CHECK_SECTIONS = {
73
+ "python_version": "system_requirements",
74
+ "platform_info": "system_requirements",
75
+ "aws_cli_version_floor": "system_requirements",
76
+ "az_cli_version_floor": "system_requirements",
77
+ "aws_price_file": "data_sources",
78
+ "user_local_data": "data_sources",
79
+ "inventory": "data_sources",
80
+ "cloud_identity_aws": "cloud_provider_identity",
81
+ "cloud_identity_azure": "cloud_provider_identity",
82
+ "consent_cloud_reads": "user_consent",
83
+ "fleetfit_ai": "user_consent",
84
+ }
85
+ _IDENTITY_CHECK_NAMES = frozenset({"cloud_identity_aws", "cloud_identity_azure"})
86
+
87
+ SECTION_SYSTEM_REQUIREMENTS = "SYSTEM_REQUIREMENTS"
88
+ SECTION_CLOUD_PROVIDER_IDENTITY = "CLOUD_PROVIDER_IDENTITY"
89
+ SECTION_USER_CONSENT = "USER_CONSENT"
90
+ SECTION_DATA_SOURCES = "DATA_SOURCES"
91
+
92
+ _STATUS_LABELS = {
93
+ "pass": "PASS",
94
+ "fail": "FAIL",
95
+ "warn": "WARN",
96
+ "skipped": "SKIPPED",
97
+ "optional": "OPTIONAL",
98
+ }
99
+
100
+
101
+ _READINESS_REASON_LABELS = {
102
+ "not_authenticated": "not signed in to the cloud CLI",
103
+ "consent_required": "cloud read consent is required",
104
+ "cli_missing": "cloud CLI is not installed",
105
+ "cli_too_old": "cloud CLI is below the supported version",
106
+ "version_unreadable": "cloud CLI version could not be read",
107
+ }
108
+
109
+
110
+ def _find_check(results: list[CheckResult], name: str) -> CheckResult | None:
111
+ for result in results:
112
+ if result.name == name:
113
+ return result
114
+ return None
115
+
116
+
117
+ _CONSENT_SKIP_REASONS = frozenset(
118
+ {
119
+ "consent_pending",
120
+ "consent_declined",
121
+ "consent_snoozed",
122
+ "consent_required",
123
+ "consent_managed_deny",
124
+ "consent_not_implemented",
125
+ }
126
+ )
127
+
128
+ _INVENTORY_CHECK_NAMES = frozenset({"inventory"})
129
+
130
+ def _provider_readiness(provider: str, results: list[CheckResult]) -> dict[str, Any]:
131
+ floor_name = (
132
+ "aws_cli_version_floor" if provider == "aws" else "az_cli_version_floor"
133
+ )
134
+ identity_name = f"cloud_identity_{provider}"
135
+ floor = _find_check(results, floor_name)
136
+ identity = _find_check(results, identity_name)
137
+ entry: dict[str, Any] = {"can_analyze": False}
138
+
139
+ if provider == "aws":
140
+ if floor and floor.status == "fail" and floor.reason_code == "not_installed":
141
+ entry["reason"] = "cli_missing"
142
+ return entry
143
+
144
+ if provider == "azure":
145
+ if floor and floor.status == "skipped" and floor.reason_code == "not_installed":
146
+ entry["reason"] = "cli_missing"
147
+ return entry
148
+ if floor and floor.status == "skipped" and floor.reason_code == "version_unreadable":
149
+ entry["reason"] = "version_unreadable"
150
+ return entry
151
+ if identity and identity.status == "skipped" and identity.reason_code == "not_installed":
152
+ entry["reason"] = "cli_missing"
153
+ return entry
154
+
155
+ if floor and floor.status == "fail":
156
+ if floor.reason_code == "not_installed":
157
+ entry["reason"] = "cli_missing"
158
+ else:
159
+ entry["reason"] = "cli_too_old"
160
+ return entry
161
+
162
+ if identity is None:
163
+ return entry
164
+
165
+ if identity.status == "skipped":
166
+ reason = identity.reason_code or ""
167
+ if reason in _CONSENT_SKIP_REASONS:
168
+ entry["reason"] = "consent_required"
169
+ return entry
170
+ if reason == "not_installed":
171
+ entry["reason"] = "cli_missing"
172
+ return entry
173
+ return entry
174
+
175
+ if identity.status == "fail":
176
+ if identity.reason_code == "not_logged_in":
177
+ entry["reason"] = "not_authenticated"
178
+ else:
179
+ entry["reason"] = "not_authenticated"
180
+ return entry
181
+
182
+ if identity.status == "optional" and identity.reason_code == "not_logged_in":
183
+ entry["reason"] = "not_authenticated"
184
+ return entry
185
+
186
+ if identity.status == "pass":
187
+ entry["can_analyze"] = True
188
+ return entry
189
+
190
+
191
+ def doctor_readiness(results: list[CheckResult]) -> dict[str, Any]:
192
+ return {
193
+ "aws": _provider_readiness("aws", results),
194
+ "azure": _provider_readiness("azure", results),
195
+ }
196
+
197
+
198
+ def doctor_ready(readiness: dict[str, Any]) -> bool:
199
+ return any(
200
+ readiness.get(provider, {}).get("can_analyze") for provider in ("aws", "azure")
201
+ )
202
+
203
+
204
+ def _envelope_from_checks(
205
+ results: list[CheckResult],
206
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
207
+ errors: list[dict[str, Any]] = []
208
+ warnings: list[dict[str, Any]] = []
209
+ seen: set[tuple[str, str]] = set()
210
+ for result in results:
211
+ if result.status == "fail":
212
+ code = result.reason_code or result.name
213
+ message = result.message or result.name
214
+ key = (code, redact(message))
215
+ if key in seen:
216
+ continue
217
+ seen.add(key)
218
+ errors.append(error_item(code, key[1]))
219
+ elif result.status == "warn":
220
+ code = result.reason_code or result.name
221
+ message = result.message or result.name
222
+ warnings.append(warning_item(code, redact(message)))
223
+ return errors, warnings
224
+
225
+
226
+ def _stale_inventory_json_warnings() -> list[dict[str, Any]]:
227
+ warnings: list[dict[str, Any]] = []
228
+ quota_message = stale_quota_warning(read_quota_state())
229
+ if quota_message:
230
+ warnings.append(
231
+ warning_item("quotas_inventory_stale", redact(quota_message))
232
+ )
233
+ reservation_message = stale_reservation_warning(read_inventory_state())
234
+ if reservation_message:
235
+ warnings.append(
236
+ warning_item(
237
+ "reservations_inventory_stale",
238
+ redact(reservation_message),
239
+ )
240
+ )
241
+ saving_plan_message = stale_saving_plan_warning(read_saving_plan_state())
242
+ if saving_plan_message:
243
+ warnings.append(
244
+ warning_item(
245
+ "saving_plans_inventory_stale",
246
+ redact(saving_plan_message),
247
+ )
248
+ )
249
+ return warnings
250
+
251
+
252
+ def _result_to_dict(result: CheckResult, *, redact_identity: bool = False) -> dict[str, Any]:
253
+ payload: dict[str, Any] = {
254
+ "name": result.name,
255
+ "status": result.status,
256
+ "reason_code": result.reason_code,
257
+ "remediation": (
258
+ redact(result.remediation) if result.remediation is not None else None
259
+ ),
260
+ "impact": (
261
+ redact(result.impact)
262
+ if result.impact is not None
263
+ else None
264
+ ),
265
+ }
266
+ section = _CHECK_SECTIONS.get(result.name)
267
+ if section is not None:
268
+ payload["section"] = section
269
+ message = result.message
270
+ if redact_identity and result.name in _IDENTITY_CHECK_NAMES and message is not None:
271
+ message = "redacted"
272
+ if message is not None:
273
+ payload["message"] = redact(message)
274
+ if result.loaded_at is not None:
275
+ payload["loaded_at"] = result.loaded_at
276
+ if result.max_age_seconds is not None:
277
+ payload["max_age_seconds"] = result.max_age_seconds
278
+ if result.name == "aws_price_file":
279
+ if result.price_path is not None:
280
+ payload["path"] = result.price_path
281
+ if result.published_at is not None:
282
+ payload["published_at"] = result.published_at
283
+ if result.row_count is not None:
284
+ payload["row_count"] = result.row_count
285
+ if result.source_kind is not None:
286
+ payload["source_kind"] = result.source_kind
287
+ return payload
288
+
289
+
290
+ def _print_section(title: str) -> None:
291
+ print()
292
+ print(title)
293
+ print("-" * len(title))
294
+
295
+
296
+ def _status_label(status: str) -> str:
297
+ return _STATUS_LABELS.get(status, status.upper())
298
+
299
+
300
+ def _remediation_indent(status: str) -> str:
301
+ """Align with check name column (after ``{STATUS} - ``)."""
302
+ return " " * (len(_status_label(status)) + 3)
303
+
304
+
305
+ def _format_status_first_line(
306
+ check_name: str,
307
+ status: str,
308
+ detail: str | None = None,
309
+ *,
310
+ use_color: bool,
311
+ ) -> str:
312
+ label = colorize_status_word(_status_label(status), use_color)
313
+ line = f"{label} - {check_name.upper()}"
314
+ if detail:
315
+ line += f" - {detail}"
316
+ line = highlight_cli_commands(line, use_color)
317
+ if use_color:
318
+ line += ANSI_RESET
319
+ return line
320
+
321
+
322
+ def _format_human_line(result: CheckResult, *, use_color: bool) -> str:
323
+ return _format_status_first_line(
324
+ result.name,
325
+ result.status,
326
+ result.message,
327
+ use_color=use_color,
328
+ )
329
+
330
+
331
+ def _print_human(results: list[CheckResult], *, use_color: bool) -> None:
332
+ for result in results:
333
+ _print_check_block(result, use_color=use_color)
334
+
335
+
336
+ def _print_check_block(result: CheckResult, *, use_color: bool) -> None:
337
+ print(_format_human_line(result, use_color=use_color))
338
+ prefix = _remediation_indent(result.status)
339
+ for line in result.detail_lines:
340
+ print(highlight_cli_commands(f"{prefix}{line}", use_color))
341
+ if result.reason_code:
342
+ print(highlight_cli_commands(f"{prefix}Reason: {result.reason_code}", use_color))
343
+ if result.remediation and result.status in (
344
+ "fail",
345
+ "warn",
346
+ "skipped",
347
+ "optional",
348
+ ):
349
+ if "\n" in result.remediation:
350
+ for line in result.remediation.splitlines():
351
+ print(highlight_cli_commands(f"{prefix}{line}", use_color))
352
+ else:
353
+ text = highlight_cli_commands(f"{prefix}{result.remediation}", use_color)
354
+ print(text)
355
+
356
+
357
+ def _print_data_sources(
358
+ results: list[CheckResult],
359
+ *,
360
+ use_color: bool,
361
+ cloud_read_allowed: bool,
362
+ ) -> None:
363
+ if not results:
364
+ return
365
+ _print_check_block(results[0], use_color=use_color)
366
+ inventory_results = results[1:]
367
+ if not inventory_results:
368
+ return
369
+ print()
370
+ for result in inventory_results:
371
+ _print_check_block(result, use_color=use_color)
372
+
373
+
374
+ def _consent_allowed_on_date(allowed_at: str) -> str | None:
375
+ raw = allowed_at.strip()
376
+ if not raw:
377
+ return None
378
+ if raw.endswith("Z"):
379
+ raw = f"{raw[:-1]}+00:00"
380
+ try:
381
+ return datetime.fromisoformat(raw).strftime("%Y-%m-%d")
382
+ except ValueError:
383
+ return None
384
+
385
+
386
+ def _cloud_read_already_granted(*, consent_cloud_reads: bool) -> bool:
387
+ del consent_cloud_reads
388
+ state = load_consent_state(settings_read_file())
389
+ return bool(state.get("cloud_read_consent"))
390
+
391
+
392
+ def _print_cloud_read_flag_grant_line() -> None:
393
+ print(CLOUD_READ_FLAG_GRANT_LINE)
394
+
395
+
396
+ def _snooze_calendar_date_utc(raw: str) -> str | None:
397
+ value = raw.strip()
398
+ if not value:
399
+ return None
400
+ if value.endswith("Z"):
401
+ value = f"{value[:-1]}+00:00"
402
+ try:
403
+ return datetime.fromisoformat(value).astimezone(timezone.utc).strftime("%Y-%m-%d")
404
+ except ValueError:
405
+ return None
406
+
407
+
408
+ def _cloud_read_consent_off_detail(reason: str) -> str:
409
+ if reason == "consent_snoozed":
410
+ state = load_consent_state(settings_read_file())
411
+ raw = state.get("cloud_read_consent_snoozed_until")
412
+ if isinstance(raw, str):
413
+ on_date = _snooze_calendar_date_utc(raw)
414
+ if on_date:
415
+ return (
416
+ "Cloud read consent is snoozed until "
417
+ f"{on_date} (UTC). Doctor will not ask until then."
418
+ )
419
+ return "Cloud read consent is snoozed. Doctor will not ask until the snooze ends."
420
+ if reason == "consent_declined":
421
+ return (
422
+ "You declined cloud reads for this run. "
423
+ "Run maproom doctor again and answer y to allow reads."
424
+ )
425
+ if reason == "consent_required":
426
+ return (
427
+ "Cloud read consent is required for this run. "
428
+ "Re-run with --consent-cloud-reads after reviewing maproom privacy doctor."
429
+ )
430
+ return (
431
+ "Cloud read consent is off for this run and analysis stays off. "
432
+ f"Later: {CLOUD_READ_CONSENT_REMEDIATION}"
433
+ )
434
+
435
+
436
+ def _cloud_read_consent_check(context: DoctorContext) -> CheckResult | None:
437
+ outcome = context.cloud_read_gate_outcome
438
+ if outcome is None:
439
+ return None
440
+ path = settings_read_file()
441
+ state = load_consent_state(path)
442
+ allowed_at = state.get("cloud_read_consent_approved_at")
443
+ if outcome.allowed:
444
+ if state.get("cloud_read_consent"):
445
+ if isinstance(allowed_at, str) and allowed_at.strip():
446
+ on_date = _consent_allowed_on_date(allowed_at)
447
+ detail = (
448
+ f"Cloud reads allowed on {on_date}"
449
+ if on_date
450
+ else "Cloud reads allowed; date not recorded"
451
+ )
452
+ else:
453
+ detail = "Cloud reads allowed; date not recorded"
454
+ else:
455
+ detail = "allowed by managed policy"
456
+ return CheckResult(
457
+ "consent_cloud_reads",
458
+ "pass",
459
+ detail,
460
+ remediation=None,
461
+ reason_code=None,
462
+ impact=None,
463
+ )
464
+ reason = outcome.reason_code or "consent_declined"
465
+ if reason == "consent_managed_deny":
466
+ return CheckResult(
467
+ "consent_cloud_reads",
468
+ "fail",
469
+ "denied by managed policy",
470
+ reason_code=reason,
471
+ remediation=None,
472
+ impact="Cloud analysis cannot run until managed policy allows reads.",
473
+ )
474
+ return CheckResult(
475
+ "consent_cloud_reads",
476
+ "skipped",
477
+ _cloud_read_consent_off_detail(reason),
478
+ reason_code=reason,
479
+ remediation=CLOUD_READ_CONSENT_REMEDIATION,
480
+ impact="Cloud analysis stays off until cloud read consent is granted.",
481
+ )
482
+
483
+
484
+ def _print_user_consent_block(context: DoctorContext, *, use_color: bool) -> None:
485
+ check = _cloud_read_consent_check(context)
486
+ if check is None:
487
+ return
488
+ print(
489
+ _format_status_first_line(
490
+ check.name,
491
+ check.status,
492
+ check.message,
493
+ use_color=use_color,
494
+ )
495
+ )
496
+ outcome = context.cloud_read_gate_outcome
497
+ path = settings_read_file()
498
+ state = load_consent_state(path)
499
+ show_revoke = bool(state.get("cloud_read_consent")) or (
500
+ outcome is not None and outcome.allowed
501
+ )
502
+ if show_revoke:
503
+ indent = _remediation_indent(check.status)
504
+ revoke = f"{indent}To revoke: maproom settings set cloud_read_consent false"
505
+ print(highlight_cli_commands(revoke, use_color))
506
+
507
+
508
+ def _fleetfit_consent_check(context: DoctorContext) -> CheckResult | None:
509
+ if not _fleetfit_active():
510
+ return None
511
+ outcome = context.fleetfit_gate_outcome
512
+ check_name = "fleetfit_ai"
513
+ level = product_version()
514
+ spot_level = 3 <= level <= MAX_PRODUCT_VERSION
515
+ remote_level = 2 <= level <= MAX_PRODUCT_VERSION
516
+ if outcome is None:
517
+ return CheckResult(
518
+ check_name,
519
+ "skipped",
520
+ "not evaluated",
521
+ reason_code=None,
522
+ remediation=None,
523
+ impact=None,
524
+ )
525
+ if outcome.upload_allowed:
526
+ detail = (
527
+ "Spot description without ids may be sent"
528
+ if spot_level
529
+ else "remote calls allowed"
530
+ if remote_level
531
+ else "optional instance-price POST when consented"
532
+ )
533
+ return CheckResult(
534
+ check_name,
535
+ "pass",
536
+ detail,
537
+ reason_code=None,
538
+ remediation=None,
539
+ impact=None,
540
+ )
541
+ reason = outcome.reason_code or "upload_declined"
542
+ if reason in ("upload_declined", "upload_declined_stored"):
543
+ detail = (
544
+ "Spot lookup declined; the completely safe local move still runs"
545
+ if spot_level
546
+ else "local recommendations only; remote lookups stay off"
547
+ if remote_level
548
+ else "local pricing file only (weaker recommendations)"
549
+ )
550
+ elif reason == "upload_required":
551
+ detail = (
552
+ "Spot lookup stays off until you pass --consent-fleetfit-recommendations"
553
+ if spot_level
554
+ else (
555
+ "remote lookups stay off until you pass "
556
+ "--consent-fleetfit-recommendations"
557
+ )
558
+ if remote_level
559
+ else (
560
+ "local pricing file only until you pass "
561
+ "--consent-fleetfit-recommendations"
562
+ )
563
+ )
564
+ elif reason == "upload_missing_policy":
565
+ detail = fleetfit_missing_policy_message()
566
+ else:
567
+ detail = reason
568
+ remediation = FLEETFIT_POLICY_ACTION if reason == "upload_missing_policy" else None
569
+ return CheckResult(
570
+ check_name,
571
+ "skipped",
572
+ detail,
573
+ reason_code=reason,
574
+ remediation=remediation,
575
+ impact=None,
576
+ )
577
+
578
+
579
+ def _print_fleetfit_consent_block(context: DoctorContext, *, use_color: bool) -> None:
580
+ """Second consent: remote fleetfit.ai calls. Spot try-first starts at level 3."""
581
+ outcome = context.fleetfit_gate_outcome
582
+ check_name = "fleetfit_ai"
583
+ level = product_version()
584
+ spot_level = 3 <= level <= MAX_PRODUCT_VERSION
585
+ remote_level = 2 <= level <= MAX_PRODUCT_VERSION
586
+ if outcome is None:
587
+ status = "skipped"
588
+ detail = "not evaluated"
589
+ reason = None
590
+ elif outcome.upload_allowed:
591
+ status = "pass"
592
+ detail = (
593
+ "Spot description without ids may be sent"
594
+ if spot_level
595
+ else "remote calls allowed"
596
+ if remote_level
597
+ else "optional instance-price POST when consented"
598
+ )
599
+ reason = None
600
+ else:
601
+ reason = outcome.reason_code or "upload_declined"
602
+ status = "skipped"
603
+ if reason in ("upload_declined", "upload_declined_stored"):
604
+ detail = (
605
+ "Spot lookup declined; the completely safe local move still runs"
606
+ if spot_level
607
+ else "local recommendations only; remote lookups stay off"
608
+ if remote_level
609
+ else "local pricing file only (weaker recommendations)"
610
+ )
611
+ elif reason == "upload_required":
612
+ detail = (
613
+ "Spot lookup stays off until you pass --consent-fleetfit-recommendations"
614
+ if spot_level
615
+ else (
616
+ "remote lookups stay off until you pass "
617
+ "--consent-fleetfit-recommendations"
618
+ )
619
+ if remote_level
620
+ else (
621
+ "local pricing file only until you pass "
622
+ "--consent-fleetfit-recommendations"
623
+ )
624
+ )
625
+ elif reason == "upload_missing_policy":
626
+ detail = fleetfit_missing_policy_message()
627
+ else:
628
+ detail = reason
629
+ print(
630
+ _format_status_first_line(
631
+ check_name,
632
+ status,
633
+ detail,
634
+ use_color=use_color,
635
+ )
636
+ )
637
+ indent = _remediation_indent(status)
638
+ if reason == "upload_missing_policy":
639
+ action = highlight_cli_commands(f"{indent}{FLEETFIT_POLICY_ACTION}", use_color)
640
+ print(action)
641
+ revoke = f"{indent}To revoke: maproom settings set service_upload_consent false"
642
+ print(highlight_cli_commands(revoke, use_color))
643
+ if outcome is None or not outcome.upload_allowed:
644
+ if reason == "upload_missing_policy":
645
+ return
646
+ if 2 <= product_version() <= MAX_PRODUCT_VERSION:
647
+ note = (
648
+ f"{indent}Declining leaves the completely safe local move. "
649
+ "Approving sends descriptions without ids to fleetfit.ai "
650
+ + (
651
+ "for a Spot instance you already run."
652
+ if product_version() == 2
653
+ else "for Spot and a same-type size change on AWS."
654
+ )
655
+ )
656
+ else:
657
+ note = (
658
+ f"{indent}aws and az still run on this machine. "
659
+ "Recommendations use the local pricing file only."
660
+ )
661
+ print(highlight_cli_commands(note, use_color))
662
+
663
+
664
+ def _print_readiness_summary(readiness: dict[str, Any], *, use_color: bool) -> None:
665
+ print(highlight_cli_commands(_doctor_finished_lead(readiness), use_color))
666
+ print()
667
+ for provider in ("aws", "azure"):
668
+ if readiness.get(provider, {}).get("can_analyze"):
669
+ print(f"Ready: {_provider_operation_label(provider)}")
670
+ for provider in ("aws", "azure"):
671
+ entry = readiness.get(provider, {})
672
+ if not entry.get("can_analyze"):
673
+ reason = entry.get("reason", "unavailable")
674
+ label = _READINESS_REASON_LABELS.get(reason, reason)
675
+ print(f"Off: {_provider_operation_label(provider)} - {label}")
676
+ print()
677
+
678
+
679
+ def _print_optional_improvements(
680
+ results: list[CheckResult],
681
+ *,
682
+ use_color: bool,
683
+ ) -> None:
684
+ print("Optional improvements:")
685
+ print(f" {_OPTIONAL_INVENTORY_NOTE}")
686
+ optional = [r for r in results if r.status == "optional"]
687
+ if not optional:
688
+ print(" (none)")
689
+ else:
690
+ for result in optional:
691
+ print(_optional_improvement_line(result, use_color=use_color))
692
+ print()
693
+
694
+
695
+ def _doctor_human_check_list(
696
+ *,
697
+ consent_checks: list[CheckResult],
698
+ combined: list[CheckResult],
699
+ ) -> list[CheckResult]:
700
+ return list(consent_checks) + list(combined)
701
+
702
+
703
+ def _format_readiness_line(readiness: dict[str, Any]) -> str:
704
+ parts: list[str] = []
705
+ for provider in ("aws", "azure"):
706
+ entry = readiness.get(provider, {})
707
+ tag = provider.upper()
708
+ if entry.get("can_analyze"):
709
+ parts.append(f"{tag} ready")
710
+ else:
711
+ reason = entry.get("reason", "unavailable")
712
+ label = _READINESS_REASON_LABELS.get(reason, reason)
713
+ parts.append(f"{tag} not ready ({label})")
714
+ return "Readiness: " + "; ".join(parts)
715
+
716
+
717
+ _DOCTOR_INTERACTIVE_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (
718
+ (
719
+ "This computer",
720
+ (
721
+ "python_version",
722
+ "platform_info",
723
+ "aws_cli_version_floor",
724
+ "az_cli_version_floor",
725
+ ),
726
+ ),
727
+ ("Consent", ("consent_cloud_reads", "fleetfit_ai")),
728
+ ("Cloud sign-in", ("cloud_identity_aws", "cloud_identity_azure")),
729
+ ("Local data", ("aws_price_file", "user_local_data")),
730
+ ("Inventory (optional)", ("inventory",)),
731
+ )
732
+
733
+
734
+ def _format_interactive_status_line(
735
+ result: CheckResult,
736
+ *,
737
+ use_color: bool,
738
+ ) -> str:
739
+ label = colorize_status_word(_status_label(result.status), use_color)
740
+ key = interactive_display_key(result.name)
741
+ fact = interactive_check_fact(result)
742
+ line = f"{label} - {key}"
743
+ if fact:
744
+ line += f" - {fact}"
745
+ line = highlight_cli_commands(line, use_color)
746
+ if use_color:
747
+ line += ANSI_RESET
748
+ return line
749
+
750
+
751
+ def _interactive_next_steps(
752
+ results: list[CheckResult],
753
+ readiness: dict[str, Any],
754
+ *,
755
+ context: DoctorContext | None,
756
+ ) -> list[str]:
757
+ steps: list[str] = []
758
+ for provider in ("aws", "azure"):
759
+ if readiness.get(provider, {}).get("can_analyze"):
760
+ steps.append(_NEXT_STEP_BY_CLOUD[provider])
761
+ if steps:
762
+ return steps
763
+ return [doctor_next_step(results, readiness=readiness, context=context)]
764
+
765
+
766
+ def _print_interactive_readiness_header(
767
+ readiness: dict[str, Any],
768
+ *,
769
+ use_color: bool,
770
+ ) -> None:
771
+ aws_ok = bool(readiness.get("aws", {}).get("can_analyze"))
772
+ az_ok = bool(readiness.get("azure", {}).get("can_analyze"))
773
+ if aws_ok and az_ok:
774
+ headline = colorize_success_text(
775
+ "Readiness: Ready for cloud analysis",
776
+ use_color,
777
+ )
778
+ else:
779
+ headline = _format_readiness_line(readiness)
780
+ print(highlight_cli_commands(headline, use_color))
781
+ for provider in ("aws", "azure"):
782
+ entry = readiness.get(provider, {})
783
+ tag = provider.upper()
784
+ if entry.get("can_analyze"):
785
+ print(colorize_success_text(f"{tag}: READY", use_color))
786
+ else:
787
+ print(f"{tag}: OFF")
788
+
789
+
790
+ def _print_interactive_next_steps(
791
+ steps: list[str],
792
+ *,
793
+ use_color: bool,
794
+ ) -> None:
795
+ print(highlight_cli_commands("Next steps:", use_color))
796
+ for step in steps:
797
+ print(highlight_cli_commands(step, use_color))
798
+
799
+
800
+ def _print_interactive_check_block(
801
+ result: CheckResult,
802
+ *,
803
+ use_color: bool,
804
+ ) -> None:
805
+ print(_format_interactive_status_line(result, use_color=use_color))
806
+ prefix = _remediation_indent(result.status)
807
+ for line in interactive_muted_detail_lines(result):
808
+ body = highlight_cli_commands(f"{prefix}{line}", use_color)
809
+ print(colorize_muted(body, use_color))
810
+
811
+
812
+ def _print_doctor_interactive_grouped(
813
+ *,
814
+ checks: list[CheckResult],
815
+ skip_prereqs: bool,
816
+ readiness: dict[str, Any],
817
+ next_step: str,
818
+ use_color: bool,
819
+ redact_identity: bool,
820
+ context: DoctorContext | None = None,
821
+ ) -> None:
822
+ del next_step
823
+ _print_interactive_readiness_header(readiness, use_color=use_color)
824
+ steps = _interactive_next_steps(checks, readiness, context=context)
825
+ _print_interactive_next_steps(steps, use_color=use_color)
826
+ print()
827
+ by_name = {check.name: check for check in checks}
828
+ for heading, names in _DOCTOR_INTERACTIVE_GROUPS:
829
+ if skip_prereqs and heading == "This computer":
830
+ continue
831
+ group = [by_name[name] for name in names if name in by_name]
832
+ if not group:
833
+ continue
834
+ print(heading)
835
+ for result in group:
836
+ displayed = result
837
+ if result.name in _IDENTITY_CHECK_NAMES and redact_identity:
838
+ displayed = _maybe_redact_identity([result], redact_identity=True)[0]
839
+ _print_interactive_check_block(displayed, use_color=use_color)
840
+ print()
841
+
842
+
843
+ def _print_doctor_one_page(
844
+ *,
845
+ checks: list[CheckResult],
846
+ skip_names: frozenset[str],
847
+ readiness: dict[str, Any],
848
+ next_step: str,
849
+ use_color: bool,
850
+ redact_identity: bool,
851
+ ) -> None:
852
+ for result in checks:
853
+ if result.name in skip_names:
854
+ continue
855
+ displayed = result
856
+ if result.name in _IDENTITY_CHECK_NAMES and redact_identity:
857
+ displayed = _maybe_redact_identity([result], redact_identity=True)[0]
858
+ _print_check_block(displayed, use_color=use_color)
859
+ print()
860
+ print(highlight_cli_commands(_format_readiness_line(readiness), use_color))
861
+ _print_next_step_line(next_step, use_color=use_color)
862
+
863
+
864
+ def _identity_clouds(results: list[CheckResult], *, status: str, reason_code: str | None = None) -> list[str]:
865
+ clouds: list[str] = []
866
+ for result in results:
867
+ if not result.name.startswith("cloud_identity_"):
868
+ continue
869
+ if result.status != status:
870
+ continue
871
+ if reason_code is not None and result.reason_code != reason_code:
872
+ continue
873
+ clouds.append(result.name.removeprefix("cloud_identity_"))
874
+ return clouds
875
+
876
+
877
+ def _login_next_step(clouds: list[str]) -> str:
878
+ commands: list[str] = []
879
+ if "aws" in clouds:
880
+ commands.append("aws login")
881
+ if "azure" in clouds:
882
+ commands.append("az login")
883
+ if len(commands) == 1:
884
+ return commands[0]
885
+ if len(commands) > 1:
886
+ return " or ".join(commands)
887
+ return DOCTOR_NEXT_STEP
888
+
889
+
890
+ def _consent_gate_next_step(context: DoctorContext | None) -> str | None:
891
+ if context is None:
892
+ return None
893
+ outcome = context.cloud_read_gate_outcome
894
+ if outcome is None or outcome.allowed:
895
+ return None
896
+ reason = outcome.reason_code or "consent_declined"
897
+ if reason == "consent_declined":
898
+ return "Run maproom doctor again and answer y to allow cloud reads"
899
+ if reason == "consent_snoozed":
900
+ state = load_consent_state(settings_read_file())
901
+ raw = state.get("cloud_read_consent_snoozed_until")
902
+ if isinstance(raw, str):
903
+ on_date = _snooze_calendar_date_utc(raw)
904
+ if on_date:
905
+ return (
906
+ f"Cloud read consent snoozed until {on_date} (UTC). "
907
+ "Doctor will not ask until then."
908
+ )
909
+ return "Cloud read consent is snoozed; doctor will not ask until the snooze ends"
910
+ if reason == "consent_required":
911
+ return (
912
+ "Re-run with --consent-cloud-reads after reviewing maproom privacy doctor"
913
+ )
914
+ return CLOUD_READ_CONSENT_REMEDIATION
915
+
916
+
917
+ def _strip_inventory_commands_from_step(step: str) -> str:
918
+ parts = [part.strip() for part in step.split(";")]
919
+ kept = [
920
+ part
921
+ for part in parts
922
+ if part
923
+ and "maproom inventory get" not in part
924
+ ]
925
+ if not kept:
926
+ return CLOUD_READ_CONSENT_REMEDIATION
927
+ return "; ".join(kept)
928
+
929
+
930
+ def _smallest_remediation(
931
+ results: list[CheckResult],
932
+ readiness: dict[str, Any],
933
+ *,
934
+ context: DoctorContext | None = None,
935
+ ) -> str:
936
+ consent_step = _consent_gate_next_step(context)
937
+ if consent_step is not None:
938
+ for provider in ("aws", "azure"):
939
+ if readiness.get(provider, {}).get("reason") == "consent_required":
940
+ return consent_step
941
+ consent = None
942
+ for provider in ("aws", "azure"):
943
+ if readiness.get(provider, {}).get("reason") == "consent_required":
944
+ consent = CLOUD_READ_CONSENT_REMEDIATION
945
+ break
946
+ az_missing = readiness.get("azure", {}).get("reason") == "cli_missing"
947
+ if consent and az_missing:
948
+ return f"{consent}; {AZURE_CLI_INSTALL_REMEDIATION}"
949
+ if consent:
950
+ return consent
951
+ aws_floor = _find_check(results, "aws_cli_version_floor")
952
+ if (
953
+ aws_floor
954
+ and aws_floor.status == "fail"
955
+ and aws_floor.reason_code == "not_installed"
956
+ and aws_floor.remediation
957
+ ):
958
+ return aws_floor.remediation
959
+ unsigned = _identity_clouds(results, status="fail", reason_code="not_logged_in")
960
+ if unsigned:
961
+ return _login_next_step(unsigned)
962
+ for name in ("aws_cli_version_floor", "az_cli_version_floor"):
963
+ floor = _find_check(results, name)
964
+ if floor and floor.status == "fail" and floor.remediation:
965
+ return floor.remediation
966
+ az_floor = _find_check(results, "az_cli_version_floor")
967
+ if (
968
+ az_floor
969
+ and az_floor.status == "skipped"
970
+ and az_floor.reason_code == "not_installed"
971
+ ):
972
+ return AZURE_CLI_INSTALL_REMEDIATION
973
+ return CLOUD_READ_CONSENT_REMEDIATION
974
+
975
+
976
+ def doctor_next_step(
977
+ results: list[CheckResult],
978
+ *,
979
+ readiness: dict[str, Any] | None = None,
980
+ context: DoctorContext | None = None,
981
+ ) -> str:
982
+ """Pick an analyze or remediation command from cloud readiness."""
983
+ ready = readiness if readiness is not None else doctor_readiness(results)
984
+ aws_ok = bool(ready.get("aws", {}).get("can_analyze"))
985
+ az_ok = bool(ready.get("azure", {}).get("can_analyze"))
986
+ if aws_ok and not az_ok:
987
+ step = "maproom analyze aws"
988
+ elif az_ok and not aws_ok:
989
+ step = "maproom analyze azure"
990
+ elif aws_ok and az_ok:
991
+ step = DOCTOR_NEXT_STEP
992
+ else:
993
+ step = _smallest_remediation(results, ready, context=context)
994
+ if product_version() <= 1:
995
+ return _strip_inventory_commands_from_step(step)
996
+ return step
997
+
998
+
999
+ _OPTIONAL_INVENTORY_NOTE = (
1000
+ "Analysis can run without the quota, reservation, and Savings Plans files; "
1001
+ "availability, reserved-instance coverage, and savings estimates stay incomplete."
1002
+ )
1003
+
1004
+
1005
+ def _doctor_finished_lead(readiness: dict[str, Any]) -> str:
1006
+ aws_ok = bool(readiness.get("aws", {}).get("can_analyze"))
1007
+ az_ok = bool(readiness.get("azure", {}).get("can_analyze"))
1008
+ if aws_ok and az_ok:
1009
+ return (
1010
+ "Doctor finished. Cloud analysis is available for AWS and Azure workloads."
1011
+ )
1012
+ if aws_ok:
1013
+ reason = readiness.get("azure", {}).get("reason", "")
1014
+ label = _READINESS_REASON_LABELS.get(reason, reason or "not configured")
1015
+ return (
1016
+ "Doctor finished. AWS analysis is available; Azure analysis stays off "
1017
+ f"because {label}."
1018
+ )
1019
+ if az_ok:
1020
+ reason = readiness.get("aws", {}).get("reason", "")
1021
+ label = _READINESS_REASON_LABELS.get(reason, reason or "not configured")
1022
+ return (
1023
+ "Doctor finished. Azure analysis is available; AWS analysis stays off "
1024
+ f"because {label}."
1025
+ )
1026
+ aws_reason = readiness.get("aws", {}).get("reason", "")
1027
+ az_reason = readiness.get("azure", {}).get("reason", "")
1028
+ if aws_reason == az_reason == "consent_required":
1029
+ return (
1030
+ "Doctor finished. Cloud analysis is off because cloud read consent is required."
1031
+ )
1032
+ if aws_reason:
1033
+ label = _READINESS_REASON_LABELS.get(aws_reason, aws_reason)
1034
+ return f"Doctor finished. Cloud analysis is off because {label}."
1035
+ if az_reason:
1036
+ label = _READINESS_REASON_LABELS.get(az_reason, az_reason)
1037
+ return f"Doctor finished. Cloud analysis is off because {label}."
1038
+ return "Doctor finished. Cloud analysis is off."
1039
+
1040
+
1041
+ def _provider_operation_label(provider: str) -> str:
1042
+ return f"{provider.upper()} analysis (maproom analyze {provider})"
1043
+
1044
+
1045
+ def _optional_improvement_line(
1046
+ result: CheckResult,
1047
+ *,
1048
+ use_color: bool,
1049
+ ) -> str:
1050
+ impact = result.impact or result.message or result.name
1051
+ line = f" - {result.name}: {impact}"
1052
+ refresh = result.remediation or ""
1053
+ if product_version() <= 1 and result.name in _INVENTORY_CHECK_NAMES:
1054
+ refresh = ""
1055
+ if refresh:
1056
+ line += f" Run: {refresh}"
1057
+ return highlight_cli_commands(line, use_color)
1058
+
1059
+
1060
+ def _print_next_step_line(step: str, *, use_color: bool) -> None:
1061
+ print(highlight_cli_commands(f"Next step: {step}", use_color))
1062
+
1063
+
1064
+ def _print_doctor_summary(
1065
+ results: list[CheckResult],
1066
+ *,
1067
+ use_color: bool,
1068
+ readiness: dict[str, Any] | None = None,
1069
+ context: DoctorContext | None = None,
1070
+ include_next_step: bool = True,
1071
+ ) -> None:
1072
+ ready = readiness if readiness is not None else doctor_readiness(results)
1073
+ step = doctor_next_step(results, readiness=ready, context=context)
1074
+ print(highlight_cli_commands(_doctor_finished_lead(ready), use_color))
1075
+ print()
1076
+ for provider in ("aws", "azure"):
1077
+ if ready.get(provider, {}).get("can_analyze"):
1078
+ print(f"Ready: {_provider_operation_label(provider)}")
1079
+ for provider in ("aws", "azure"):
1080
+ entry = ready.get(provider, {})
1081
+ if not entry.get("can_analyze"):
1082
+ reason = entry.get("reason", "unavailable")
1083
+ label = _READINESS_REASON_LABELS.get(reason, reason)
1084
+ print(f"Off: {_provider_operation_label(provider)} - {label}")
1085
+ print()
1086
+ fails = [r for r in results if r.status == "fail"]
1087
+ print("Blocking problems:")
1088
+ if not fails:
1089
+ print(" (none)")
1090
+ else:
1091
+ for result in fails:
1092
+ text = result.message or result.name
1093
+ print(f" - {result.name}: {text}")
1094
+ print()
1095
+ optional = [r for r in results if r.status == "optional"]
1096
+ print("Optional improvements:")
1097
+ print(f" {_OPTIONAL_INVENTORY_NOTE}")
1098
+ if not optional:
1099
+ print(" (none)")
1100
+ else:
1101
+ for result in optional:
1102
+ print(_optional_improvement_line(result, use_color=use_color))
1103
+ if include_next_step:
1104
+ print()
1105
+ _print_next_step_line(step, use_color=use_color)
1106
+
1107
+
1108
+ def _doctor_interactive_tty(*, as_json: bool) -> bool:
1109
+ if as_json:
1110
+ return False
1111
+ return sys.stdin.isatty() and sys.stdout.isatty()
1112
+
1113
+
1114
+ def _evaluate_cloud_read_gate(
1115
+ context: DoctorContext,
1116
+ *,
1117
+ consent_cloud_reads: bool = False,
1118
+ as_json: bool = False,
1119
+ ) -> None:
1120
+ if context.gate_evaluated:
1121
+ return
1122
+ interactive = _doctor_interactive_tty(as_json=as_json)
1123
+ context.cloud_read_gate_outcome = require_cloud_read_consent(
1124
+ consent_cloud_reads=consent_cloud_reads,
1125
+ stdin_is_tty=interactive,
1126
+ quiet=not interactive,
1127
+ )
1128
+ context.gate_evaluated = True
1129
+
1130
+
1131
+ def _fleetfit_active() -> bool:
1132
+ return product_version() > 1
1133
+
1134
+
1135
+ def _evaluate_fleetfit_gate(
1136
+ context: DoctorContext,
1137
+ *,
1138
+ consent_fleetfit_recommendations: bool = False,
1139
+ as_json: bool = False,
1140
+ ) -> None:
1141
+ if context.fleetfit_evaluated:
1142
+ return
1143
+ interactive = _doctor_interactive_tty(as_json=as_json)
1144
+ context.fleetfit_gate_outcome = require_service_upload_consent(
1145
+ consent_fleetfit_recommendations=consent_fleetfit_recommendations,
1146
+ stdin_is_tty=interactive,
1147
+ quiet=True,
1148
+ )
1149
+ context.fleetfit_evaluated = True
1150
+
1151
+
1152
+ def _run_identity_checks(context: DoctorContext) -> list[CheckResult]:
1153
+ return run_identity_checks(context)
1154
+
1155
+
1156
+ def _cloud_read_allowed(
1157
+ context: DoctorContext,
1158
+ *,
1159
+ consent_cloud_reads: bool,
1160
+ ) -> bool:
1161
+ if consent_cloud_reads:
1162
+ return True
1163
+ outcome = context.cloud_read_gate_outcome
1164
+ if outcome is not None:
1165
+ return outcome.allowed
1166
+ state = load_consent_state(settings_read_file())
1167
+ return bool(state.get("cloud_read_consent"))
1168
+
1169
+
1170
+ def _run_data_source_checks(
1171
+ context: DoctorContext,
1172
+ *,
1173
+ as_json: bool,
1174
+ consent_cloud_reads: bool,
1175
+ ) -> list[CheckResult]:
1176
+ context.cloud_read_allowed = _cloud_read_allowed(
1177
+ context,
1178
+ consent_cloud_reads=consent_cloud_reads,
1179
+ )
1180
+ return [check(context) for check in DATA_SOURCE_CHECKS]
1181
+
1182
+
1183
+ def _cli_floor_blocks_consent_prompt(
1184
+ prerequisite_results: list[CheckResult],
1185
+ ) -> bool:
1186
+ aws = _find_check(prerequisite_results, "aws_cli_version_floor")
1187
+ if aws is not None and aws.status == "fail":
1188
+ return True
1189
+ az = _find_check(prerequisite_results, "az_cli_version_floor")
1190
+ return az is not None and az.status == "fail"
1191
+
1192
+
1193
+ def _skip_consent_prompt_for_cli_floor(context: DoctorContext) -> None:
1194
+ context.cloud_read_gate_outcome = CloudReadGateOutcome(
1195
+ False,
1196
+ 0,
1197
+ "consent_required",
1198
+ "Cloud read consent was not requested because a CLI version check failed.",
1199
+ )
1200
+ context.gate_evaluated = True
1201
+
1202
+
1203
+ def _pending_consent_identity_results() -> list[CheckResult]:
1204
+ remediation = CLOUD_READ_CONSENT_REMEDIATION
1205
+ message = "Cloud read consent required before provider login checks"
1206
+ return [
1207
+ CheckResult(
1208
+ "cloud_identity_aws",
1209
+ "skipped",
1210
+ message,
1211
+ reason_code="consent_pending",
1212
+ remediation=remediation,
1213
+ impact="AWS analysis cannot run until cloud read consent is granted.",
1214
+ ),
1215
+ CheckResult(
1216
+ "cloud_identity_azure",
1217
+ "skipped",
1218
+ message,
1219
+ reason_code="consent_pending",
1220
+ remediation=remediation,
1221
+ impact="Azure analysis cannot run until cloud read consent is granted.",
1222
+ ),
1223
+ ]
1224
+
1225
+
1226
+ def _maybe_redact_identity(
1227
+ results: list[CheckResult],
1228
+ *,
1229
+ redact_identity: bool,
1230
+ ) -> list[CheckResult]:
1231
+ if not redact_identity:
1232
+ return results
1233
+ redacted: list[CheckResult] = []
1234
+ for result in results:
1235
+ if result.name in _IDENTITY_CHECK_NAMES and result.message is not None:
1236
+ redacted.append(
1237
+ CheckResult(
1238
+ result.name,
1239
+ result.status,
1240
+ "redacted",
1241
+ reason_code=result.reason_code,
1242
+ remediation=result.remediation,
1243
+ detail_lines=result.detail_lines,
1244
+ impact=result.impact,
1245
+ loaded_at=result.loaded_at,
1246
+ max_age_seconds=result.max_age_seconds,
1247
+ price_path=result.price_path,
1248
+ published_at=result.published_at,
1249
+ row_count=result.row_count,
1250
+ source_kind=result.source_kind,
1251
+ )
1252
+ )
1253
+ else:
1254
+ redacted.append(result)
1255
+ return redacted
1256
+
1257
+
1258
+ def _evaluate_consent_gates(
1259
+ context: DoctorContext,
1260
+ *,
1261
+ as_json: bool,
1262
+ consent_cloud_reads: bool,
1263
+ consent_fleetfit_recommendations: bool,
1264
+ prerequisite_results: list[CheckResult],
1265
+ defer_consent: bool,
1266
+ ) -> None:
1267
+ if context.gate_evaluated:
1268
+ return
1269
+ if (
1270
+ defer_consent
1271
+ and not as_json
1272
+ and _cli_floor_blocks_consent_prompt(prerequisite_results)
1273
+ ):
1274
+ _skip_consent_prompt_for_cli_floor(context)
1275
+ return
1276
+ _evaluate_cloud_read_gate(
1277
+ context,
1278
+ consent_cloud_reads=consent_cloud_reads,
1279
+ as_json=as_json,
1280
+ )
1281
+ if _fleetfit_active():
1282
+ _evaluate_fleetfit_gate(
1283
+ context,
1284
+ consent_fleetfit_recommendations=consent_fleetfit_recommendations,
1285
+ as_json=as_json,
1286
+ )
1287
+
1288
+
1289
+ def _collect_doctor_results(
1290
+ context: DoctorContext,
1291
+ *,
1292
+ as_json: bool,
1293
+ consent_cloud_reads: bool,
1294
+ consent_fleetfit_recommendations: bool,
1295
+ prerequisite_results: list[CheckResult],
1296
+ consent_pre_evaluated: bool,
1297
+ ) -> tuple[list[CheckResult], list[CheckResult], list[CheckResult], bool]:
1298
+ """Return prerequisite, identity, and data-source checks plus defer_consent flag."""
1299
+ defer_consent = not as_json and not _cloud_read_already_granted(
1300
+ consent_cloud_reads=consent_cloud_reads
1301
+ )
1302
+ if not consent_pre_evaluated:
1303
+ _evaluate_consent_gates(
1304
+ context,
1305
+ as_json=as_json,
1306
+ consent_cloud_reads=consent_cloud_reads,
1307
+ consent_fleetfit_recommendations=consent_fleetfit_recommendations,
1308
+ prerequisite_results=prerequisite_results,
1309
+ defer_consent=defer_consent,
1310
+ )
1311
+ identity_results = _run_identity_checks(context)
1312
+ elif context.cloud_read_gate_outcome is not None:
1313
+ identity_results = _run_identity_checks(context)
1314
+ else:
1315
+ identity_results = _pending_consent_identity_results()
1316
+
1317
+ data_source_results = _run_data_source_checks(
1318
+ context,
1319
+ as_json=as_json,
1320
+ consent_cloud_reads=consent_cloud_reads,
1321
+ )
1322
+ return prerequisite_results, identity_results, data_source_results, defer_consent
1323
+
1324
+
1325
+ def run_doctor(
1326
+ *,
1327
+ as_json: bool = False,
1328
+ consent_cloud_reads: bool = False,
1329
+ consent_fleetfit_recommendations: bool = False,
1330
+ force_color: bool = False,
1331
+ no_color: bool = False,
1332
+ redact_identity: bool = False,
1333
+ ctx: DoctorContext | None = None,
1334
+ ) -> int:
1335
+ started_at = datetime.now(timezone.utc)
1336
+ perf_start = time.perf_counter()
1337
+ context = ctx or DoctorContext()
1338
+ use_color = ansi_color_enabled(
1339
+ force_color=force_color,
1340
+ no_color=no_color,
1341
+ as_json=as_json,
1342
+ )
1343
+ prerequisite_results = run_prerequisite_checks(context)
1344
+ defer_consent = not as_json and not _cloud_read_already_granted(
1345
+ consent_cloud_reads=consent_cloud_reads
1346
+ )
1347
+ consent_pre_evaluated = False
1348
+ printed_prereqs_early = False
1349
+ if defer_consent and not as_json and _doctor_interactive_tty(as_json=as_json):
1350
+ _print_human(prerequisite_results, use_color=use_color)
1351
+ printed_prereqs_early = True
1352
+ if _cli_floor_blocks_consent_prompt(prerequisite_results):
1353
+ _skip_consent_prompt_for_cli_floor(context)
1354
+ else:
1355
+ _evaluate_cloud_read_gate(
1356
+ context,
1357
+ consent_cloud_reads=consent_cloud_reads,
1358
+ as_json=as_json,
1359
+ )
1360
+ if (
1361
+ consent_cloud_reads
1362
+ and _doctor_interactive_tty(as_json=as_json)
1363
+ and context.cloud_read_gate_outcome is not None
1364
+ and context.cloud_read_gate_outcome.allowed
1365
+ ):
1366
+ _print_cloud_read_flag_grant_line()
1367
+ if _fleetfit_active():
1368
+ _evaluate_fleetfit_gate(
1369
+ context,
1370
+ consent_fleetfit_recommendations=consent_fleetfit_recommendations,
1371
+ as_json=as_json,
1372
+ )
1373
+ consent_pre_evaluated = True
1374
+
1375
+ (
1376
+ prerequisite_results,
1377
+ identity_results,
1378
+ data_source_results,
1379
+ _defer_consent,
1380
+ ) = _collect_doctor_results(
1381
+ context,
1382
+ as_json=as_json,
1383
+ consent_cloud_reads=consent_cloud_reads,
1384
+ consent_fleetfit_recommendations=consent_fleetfit_recommendations,
1385
+ prerequisite_results=prerequisite_results,
1386
+ consent_pre_evaluated=consent_pre_evaluated,
1387
+ )
1388
+ combined = prerequisite_results + identity_results + data_source_results
1389
+ consent_checks: list[CheckResult] = []
1390
+ cloud_consent = _cloud_read_consent_check(context)
1391
+ if cloud_consent is not None:
1392
+ consent_checks.append(cloud_consent)
1393
+ fleetfit = _fleetfit_consent_check(context)
1394
+ if fleetfit is not None:
1395
+ consent_checks.append(fleetfit)
1396
+ readiness = doctor_readiness(combined)
1397
+ duration_ms = max(0, int((time.perf_counter() - perf_start) * 1000))
1398
+
1399
+ if not as_json:
1400
+ step = doctor_next_step(combined, readiness=readiness, context=context)
1401
+ skip_early = (
1402
+ _PREREQUISITE_CHECK_NAMES
1403
+ if printed_prereqs_early
1404
+ else frozenset()
1405
+ )
1406
+ check_list = _doctor_human_check_list(
1407
+ consent_checks=consent_checks,
1408
+ combined=combined,
1409
+ )
1410
+ if _doctor_interactive_tty(as_json=as_json):
1411
+ _print_doctor_interactive_grouped(
1412
+ checks=check_list,
1413
+ skip_prereqs=printed_prereqs_early,
1414
+ readiness=readiness,
1415
+ next_step=step,
1416
+ use_color=use_color,
1417
+ redact_identity=redact_identity,
1418
+ context=context,
1419
+ )
1420
+ else:
1421
+ _print_doctor_one_page(
1422
+ checks=check_list,
1423
+ skip_names=skip_early,
1424
+ readiness=readiness,
1425
+ next_step=step,
1426
+ use_color=use_color,
1427
+ redact_identity=redact_identity,
1428
+ )
1429
+ print()
1430
+ else:
1431
+ errors, warnings = _envelope_from_checks(combined)
1432
+ warnings = warnings + _stale_inventory_json_warnings()
1433
+ json_checks = [
1434
+ _result_to_dict(c, redact_identity=redact_identity) for c in consent_checks
1435
+ ]
1436
+ json_checks.extend(
1437
+ _result_to_dict(result, redact_identity=redact_identity)
1438
+ for result in combined
1439
+ )
1440
+ report_fields: dict[str, Any] = {
1441
+ "ready": doctor_ready(readiness),
1442
+ "readiness": readiness,
1443
+ "checks": json_checks,
1444
+ "next_step": doctor_next_step(
1445
+ combined,
1446
+ readiness=readiness,
1447
+ context=context,
1448
+ ),
1449
+ }
1450
+ print_json(
1451
+ build_document(
1452
+ schema_type="doctor",
1453
+ schema_id="maproom.doctor",
1454
+ schema_version=2, # doctor-only envelope version
1455
+ metadata=command_metadata(
1456
+ "doctor",
1457
+ started_at=started_at,
1458
+ duration_ms=duration_ms,
1459
+ ),
1460
+ errors=errors,
1461
+ warnings=warnings,
1462
+ payload=report_fields,
1463
+ )
1464
+ )
1465
+
1466
+ has_fail = any(r.status == "fail" for r in combined)
1467
+ return RUNTIME if has_fail else SUCCESS