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,91 @@
1
+ """Human and markdown formatting for plan items (NEXT-1 W7)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from maproom.analyze.provider_comparison import format_provider_tty
8
+ from maproom.analyze.recommendation import rejected_summary_line
9
+ from maproom.plan.model import PlanItem
10
+
11
+
12
+ def _provider_doc_from_item(item: PlanItem) -> dict[str, Any]:
13
+ return {
14
+ "provider_recommendation": item.provider_recommendation,
15
+ "provider_gap": item.provider_gap or {},
16
+ }
17
+
18
+
19
+ def format_item_tty_lines(item: PlanItem) -> list[str]:
20
+ """Lines after the chosen candidate summary for plan show."""
21
+ lines: list[str] = []
22
+ rec = item.evidence.recommendation
23
+ lines.append(
24
+ f" target: {item.instance_type} "
25
+ f"(USD {rec.get('savings_per_month_usd', '0')}/mo savings, "
26
+ f"confidence {rec.get('confidence', 'UNKNOWN')})"
27
+ )
28
+ if item.provider_gap is not None or item.provider_recommendation is not None:
29
+ lines.append(" Provider comparison:")
30
+ for provider_line in format_provider_tty(_provider_doc_from_item(item)):
31
+ lines.append(f" {provider_line}")
32
+ summary = item.rejected_summary
33
+ if summary:
34
+ line = rejected_summary_line(dict(summary.get("by_reason") or {}))
35
+ if line:
36
+ lines.append(f" {line}")
37
+ if item.pricing_data_as_of:
38
+ lines.append(f" Pricing data as of: {item.pricing_data_as_of}")
39
+ return lines
40
+
41
+
42
+ def format_item_markdown_sections(item: PlanItem) -> list[str]:
43
+ lines: list[str] = []
44
+ rec = item.evidence.recommendation
45
+ lines.extend(
46
+ [
47
+ f"## {item.item_id}",
48
+ f"- resource: {item.resource}",
49
+ f"- current type: {item.evidence.workload.get('instance_type')}",
50
+ f"- target type: {item.instance_type}",
51
+ f"- monthly savings: USD {rec.get('savings_per_month_usd', '0')}",
52
+ f"- confidence: {rec.get('confidence', 'UNKNOWN')}",
53
+ f"- migration_options: {', '.join(item.migration_options)}",
54
+ f"- validation_steps: {', '.join(item.validation_steps)}",
55
+ f"- evidence captured: {item.evidence.captured_at}",
56
+ ]
57
+ )
58
+ if item.pricing_data_as_of:
59
+ lines.append(f"- pricing data as of: {item.pricing_data_as_of}")
60
+ if item.spec_source:
61
+ lines.append(f"- spec source: {item.spec_source}")
62
+ if item.provider_gap is not None or item.provider_recommendation is not None:
63
+ lines.append("")
64
+ lines.append("## Provider comparison")
65
+ for provider_line in format_provider_tty(_provider_doc_from_item(item)):
66
+ lines.append(provider_line)
67
+ summary = item.rejected_summary
68
+ if summary:
69
+ lines.append("")
70
+ lines.append("## Rejected candidates")
71
+ lines.append("| reason | count |")
72
+ lines.append("| --- | ---: |")
73
+ by_reason = dict(summary.get("by_reason") or {})
74
+ for code, count in sorted(
75
+ by_reason.items(),
76
+ key=lambda pair: (-pair[1], pair[0]),
77
+ ):
78
+ lines.append(f"| {code} | {count} |")
79
+ top = list(summary.get("top") or [])
80
+ if top:
81
+ lines.append("")
82
+ lines.append("Top rejected (up to 5):")
83
+ for entry in top:
84
+ inst = entry.get("instance_type") or ""
85
+ reason = entry.get("reason") or ""
86
+ price = entry.get("price_per_month_usd") or "0"
87
+ lines.append(
88
+ f"- {inst}: {reason} (USD {price}/mo)"
89
+ )
90
+ lines.append("")
91
+ return lines
maproom/plan/ids.py ADDED
@@ -0,0 +1,13 @@
1
+ """Plan item id generation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+
7
+
8
+ def generate_item_id(existing_ids: set[str]) -> str:
9
+ for _ in range(32):
10
+ item_id = f"item-{secrets.token_hex(2)}"
11
+ if item_id not in existing_ids:
12
+ return item_id
13
+ raise RuntimeError("could not allocate unique plan item id")
@@ -0,0 +1,75 @@
1
+ """Migration option parsing and qualification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from maproom.plan.errors import PlanError
6
+
7
+ CANONICAL_MIGRATION_OPTIONS: tuple[str, ...] = (
8
+ "NO_MIGRATION",
9
+ "REBUILD_FOR_ARM",
10
+ "REBUILD_FOR_X86",
11
+ "VERIFY_CPU_HEADROOM",
12
+ "VERIFY_BURST_CREDITS",
13
+ "MIGRATE_REGION",
14
+ "MIGRATE_AVAILABILITY_ZONE",
15
+ "MIGRATE_LOCAL_STORAGE",
16
+ "RESIZE_WITH_DOWNTIME",
17
+ "UPDATE_MACHINE_IMAGE",
18
+ "PURCHASE_COMMITMENT",
19
+ "REQUEST_ADDITIONAL_QUOTA",
20
+ "REVIEW_LICENSE_OR_TENANCY",
21
+ "ROLL_GROUP_MEMBERS",
22
+ )
23
+
24
+ _ACCEPT_INPUT_ALIASES = {"ANY": "ANY"}
25
+
26
+
27
+ def _normalize_token(token: str) -> str:
28
+ return token.strip().replace("-", "_").upper()
29
+
30
+
31
+ def _canonicalize(token: str) -> str | None:
32
+ normalized = _normalize_token(token)
33
+ if normalized in _ACCEPT_INPUT_ALIASES:
34
+ return normalized
35
+ for value in CANONICAL_MIGRATION_OPTIONS:
36
+ if normalized == value:
37
+ return value
38
+ return None
39
+
40
+
41
+ def parse_accept_values(raw_values: list[str]) -> set[str] | PlanError:
42
+ parsed: set[str] = set()
43
+ for raw in raw_values:
44
+ for piece in raw.split(","):
45
+ piece = piece.strip()
46
+ if not piece:
47
+ continue
48
+ canonical = _canonicalize(piece)
49
+ if canonical is None:
50
+ allowed = ", ".join(CANONICAL_MIGRATION_OPTIONS + ("ANY",))
51
+ return PlanError(
52
+ f'unrecognized migration option "{piece}". '
53
+ f"Valid values: {allowed}"
54
+ )
55
+ parsed.add(canonical)
56
+ if not parsed:
57
+ return PlanError("at least one --accept value is required")
58
+ return parsed
59
+
60
+
61
+ def candidate_qualifies(migration_options: list[str], parsed_accept: set[str]) -> bool:
62
+ if "ANY" in parsed_accept:
63
+ return True
64
+ opts = {str(v) for v in migration_options}
65
+ if not opts:
66
+ return False
67
+ if opts == {"NO_MIGRATION"} and "NO_MIGRATION" in parsed_accept:
68
+ return True
69
+ return opts <= parsed_accept
70
+
71
+
72
+ def format_accept_example(migration_options: list[str], resource: str) -> str:
73
+ values = [v.lower().replace("_", "-") for v in migration_options]
74
+ joined = ",".join(values)
75
+ return f"maproom analyze {resource} --accept {joined}"
maproom/plan/model.py ADDED
@@ -0,0 +1,265 @@
1
+ """Plan record types and serialization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime, timezone
7
+ from typing import Any
8
+
9
+ from maproom.plan.analysis_context import analysis_fields_from_document
10
+ from maproom.plan.ids import generate_item_id
11
+
12
+
13
+ SCHEMA_VERSION = 1
14
+
15
+ PLAN_ADD_ITEMS_HINT = (
16
+ "To add one, run maproom analyze and choose a recommendation."
17
+ )
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class CreatePlanResult:
22
+ record: "PlanRecord"
23
+ created: bool
24
+
25
+
26
+ def _utc_now_iso() -> str:
27
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
28
+
29
+
30
+ @dataclass
31
+ class EvidenceSnapshot:
32
+ captured_at: str
33
+ recommendation: dict[str, Any]
34
+ workload: dict[str, Any]
35
+
36
+ def to_dict(self) -> dict[str, Any]:
37
+ return {
38
+ "captured_at": self.captured_at,
39
+ "recommendation": self.recommendation,
40
+ "workload": self.workload,
41
+ }
42
+
43
+ @classmethod
44
+ def from_dict(cls, data: dict[str, Any]) -> EvidenceSnapshot:
45
+ return cls(
46
+ captured_at=str(data.get("captured_at") or ""),
47
+ recommendation=dict(data.get("recommendation") or {}),
48
+ workload=dict(data.get("workload") or {}),
49
+ )
50
+
51
+
52
+ @dataclass
53
+ class PlanItem:
54
+ item_id: str
55
+ resource: str
56
+ cloud: str
57
+ region: str
58
+ candidate_id: str
59
+ instance_type: str
60
+ target_count: int
61
+ migration_options: list[str]
62
+ validation_steps: list[str]
63
+ quota_dependency: str | None
64
+ evidence: EvidenceSnapshot
65
+ provider_recommendation: dict[str, Any] | None = None
66
+ provider_gap: dict[str, Any] | None = None
67
+ rejected_summary: dict[str, Any] | None = None
68
+ engine: dict[str, Any] | None = None
69
+ pricing_data_as_of: str | None = None
70
+ spec_source: str | None = None
71
+
72
+ def to_dict(self) -> dict[str, Any]:
73
+ payload: dict[str, Any] = {
74
+ "item_id": self.item_id,
75
+ "resource": self.resource,
76
+ "cloud": self.cloud,
77
+ "region": self.region,
78
+ "candidate_id": self.candidate_id,
79
+ "instance_type": self.instance_type,
80
+ "target_count": self.target_count,
81
+ "migration_options": list(self.migration_options),
82
+ "validation_steps": list(self.validation_steps),
83
+ "quota_dependency": self.quota_dependency,
84
+ "evidence": self.evidence.to_dict(),
85
+ }
86
+ if self.provider_recommendation is not None:
87
+ payload["provider_recommendation"] = self.provider_recommendation
88
+ if self.provider_gap is not None:
89
+ payload["provider_gap"] = self.provider_gap
90
+ if self.rejected_summary is not None:
91
+ payload["rejected_summary"] = self.rejected_summary
92
+ if self.engine is not None:
93
+ payload["engine"] = self.engine
94
+ if self.pricing_data_as_of is not None:
95
+ payload["pricing_data_as_of"] = self.pricing_data_as_of
96
+ if self.spec_source is not None:
97
+ payload["spec_source"] = self.spec_source
98
+ return payload
99
+
100
+ @classmethod
101
+ def from_dict(cls, data: dict[str, Any]) -> PlanItem:
102
+ return cls(
103
+ item_id=str(data["item_id"]),
104
+ resource=str(data["resource"]),
105
+ cloud=str(data.get("cloud") or "aws"),
106
+ region=str(data.get("region") or ""),
107
+ candidate_id=str(data["candidate_id"]),
108
+ instance_type=str(data.get("instance_type") or ""),
109
+ target_count=int(data.get("target_count") or 1),
110
+ migration_options=[str(v) for v in (data.get("migration_options") or [])],
111
+ validation_steps=[str(v) for v in (data.get("validation_steps") or [])],
112
+ quota_dependency=data.get("quota_dependency"),
113
+ evidence=EvidenceSnapshot.from_dict(dict(data.get("evidence") or {})),
114
+ provider_recommendation=(
115
+ dict(data["provider_recommendation"])
116
+ if data.get("provider_recommendation") is not None
117
+ else None
118
+ ),
119
+ provider_gap=(
120
+ dict(data["provider_gap"]) if data.get("provider_gap") is not None else None
121
+ ),
122
+ rejected_summary=(
123
+ dict(data["rejected_summary"])
124
+ if data.get("rejected_summary") is not None
125
+ else None
126
+ ),
127
+ engine=dict(data["engine"]) if data.get("engine") is not None else None,
128
+ pricing_data_as_of=(
129
+ str(data["pricing_data_as_of"])
130
+ if data.get("pricing_data_as_of")
131
+ else None
132
+ ),
133
+ spec_source=(
134
+ str(data["spec_source"]) if data.get("spec_source") else None
135
+ ),
136
+ )
137
+
138
+
139
+ @dataclass
140
+ class PlanRecord:
141
+ name: str
142
+ revision: int
143
+ created_at: str
144
+ updated_at: str
145
+ items: list[PlanItem] = field(default_factory=list)
146
+
147
+ def to_dict(self) -> dict[str, Any]:
148
+ return {
149
+ "schema_version": SCHEMA_VERSION,
150
+ "name": self.name,
151
+ "revision": self.revision,
152
+ "created_at": self.created_at,
153
+ "updated_at": self.updated_at,
154
+ "items": [item.to_dict() for item in self.items],
155
+ }
156
+
157
+ @classmethod
158
+ def from_dict(cls, data: dict[str, Any]) -> PlanRecord:
159
+ return cls(
160
+ name=str(data["name"]),
161
+ revision=int(data.get("revision") or 1),
162
+ created_at=str(data.get("created_at") or _utc_now_iso()),
163
+ updated_at=str(data.get("updated_at") or _utc_now_iso()),
164
+ items=[PlanItem.from_dict(item) for item in (data.get("items") or [])],
165
+ )
166
+
167
+ @classmethod
168
+ def new_empty(cls, name: str) -> PlanRecord:
169
+ now = _utc_now_iso()
170
+ return cls(name=name, revision=1, created_at=now, updated_at=now, items=[])
171
+
172
+
173
+ @dataclass(frozen=True)
174
+ class PlanSummary:
175
+ name: str
176
+ item_count: int
177
+ updated_at: str
178
+ is_current: bool
179
+
180
+
181
+ @dataclass(frozen=True)
182
+ class AddItemResult:
183
+ record: PlanRecord
184
+ item_id: str
185
+ replaced: bool
186
+
187
+
188
+ def build_evidence_snapshot(
189
+ *,
190
+ candidate: dict[str, Any],
191
+ profile: dict[str, Any],
192
+ pricing_data_as_of: str | None = None,
193
+ ) -> EvidenceSnapshot:
194
+ workload = {
195
+ "instance_type": profile.get("instance_type"),
196
+ "region": profile.get("region"),
197
+ "utilization": profile.get("utilization") or {},
198
+ "account_id": profile.get("account_id"),
199
+ }
200
+ recommendation = {
201
+ "candidate_id": candidate.get("candidate_id"),
202
+ "instance_type": candidate.get("instance_type"),
203
+ "price_per_month_usd": candidate.get("price_per_month_usd"),
204
+ "savings_per_month_usd": candidate.get("savings_per_month_usd"),
205
+ "confidence": candidate.get("confidence"),
206
+ "migration_options": list(candidate.get("migration_options") or []),
207
+ "validation_steps": list(candidate.get("validation_steps") or []),
208
+ }
209
+ if pricing_data_as_of:
210
+ recommendation["pricing_data_as_of"] = pricing_data_as_of
211
+ return EvidenceSnapshot(
212
+ captured_at=_utc_now_iso(),
213
+ recommendation=recommendation,
214
+ workload=workload,
215
+ )
216
+
217
+
218
+ def build_plan_item(
219
+ *,
220
+ candidate: dict[str, Any],
221
+ profile: dict[str, Any],
222
+ resource: str,
223
+ cloud: str,
224
+ region: str,
225
+ existing_ids: set[str],
226
+ analysis_doc: dict[str, Any] | None = None,
227
+ ) -> PlanItem:
228
+ pricing_as_of = (
229
+ str(analysis_doc.get("pricing_data_as_of"))
230
+ if analysis_doc and analysis_doc.get("pricing_data_as_of")
231
+ else None
232
+ )
233
+ evidence = build_evidence_snapshot(
234
+ candidate=candidate,
235
+ profile=profile,
236
+ pricing_data_as_of=pricing_as_of,
237
+ )
238
+ context = (
239
+ analysis_fields_from_document(analysis_doc, region=region)
240
+ if analysis_doc
241
+ else {}
242
+ )
243
+ return PlanItem(
244
+ item_id=generate_item_id_from_existing(existing_ids),
245
+ resource=resource,
246
+ cloud=cloud,
247
+ region=region,
248
+ candidate_id=str(candidate.get("candidate_id") or ""),
249
+ instance_type=str(candidate.get("instance_type") or ""),
250
+ target_count=1,
251
+ migration_options=[str(v) for v in (candidate.get("migration_options") or [])],
252
+ validation_steps=[str(v) for v in (candidate.get("validation_steps") or [])],
253
+ quota_dependency=candidate.get("quota_dependency"),
254
+ evidence=evidence,
255
+ provider_recommendation=context.get("provider_recommendation"),
256
+ provider_gap=context.get("provider_gap"),
257
+ rejected_summary=context.get("rejected_summary"),
258
+ engine=context.get("engine"),
259
+ pricing_data_as_of=context.get("pricing_data_as_of"),
260
+ spec_source=context.get("spec_source"),
261
+ )
262
+
263
+
264
+ def generate_item_id_from_existing(existing_ids: set[str]) -> str:
265
+ return generate_item_id(existing_ids)
maproom/plan/names.py ADDED
@@ -0,0 +1,24 @@
1
+ """Plan name validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from maproom.plan.errors import PlanError
8
+
9
+ _PLAN_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$")
10
+
11
+
12
+ def validate_plan_name(name: str) -> str | PlanError:
13
+ text = (name or "").strip()
14
+ if not text:
15
+ return PlanError(
16
+ "Plan name is required. Use lowercase letters, digits, hyphens, and "
17
+ "underscores (example: q3-rightsizing)."
18
+ )
19
+ if not _PLAN_NAME_RE.match(text):
20
+ return PlanError(
21
+ f'Invalid plan name "{text}". Names must match [a-z0-9][a-z0-9_-]{{0,62}} '
22
+ "(example: q3-rightsizing)."
23
+ )
24
+ return text
maproom/plan/store.py ADDED
@@ -0,0 +1,193 @@
1
+ """Atomic plan persistence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ from maproom.paths import data_subdir, prepare_data_write, readable_data_dir, readable_data_file
11
+ from maproom.plan.errors import PlanError
12
+ from maproom.plan.model import (
13
+ AddItemResult,
14
+ CreatePlanResult,
15
+ PlanItem,
16
+ PlanRecord,
17
+ PlanSummary,
18
+ _utc_now_iso,
19
+ )
20
+ from maproom.plan.names import validate_plan_name
21
+ from maproom.redaction import redact_tree
22
+
23
+
24
+ def plans_dir() -> Path:
25
+ return data_subdir("plans")
26
+
27
+
28
+ def _plan_path(name: str) -> Path:
29
+ return plans_dir() / f"{name}.json"
30
+
31
+
32
+ def _atomic_write_json(path: Path, payload: dict) -> PlanError | None:
33
+ try:
34
+ path.parent.mkdir(parents=True, exist_ok=True)
35
+ fd, tmp_name = tempfile.mkstemp(
36
+ dir=path.parent,
37
+ prefix=f".{path.stem}-",
38
+ suffix=".tmp",
39
+ )
40
+ tmp_path = Path(tmp_name)
41
+ try:
42
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
43
+ json.dump(redact_tree(payload), handle, indent=2)
44
+ handle.write("\n")
45
+ os.replace(tmp_path, path)
46
+ except OSError:
47
+ tmp_path.unlink(missing_ok=True)
48
+ raise
49
+ except OSError as exc:
50
+ return PlanError(f"could not write plan at {path}: {exc}")
51
+ return None
52
+
53
+
54
+ def _read_json(path: Path) -> dict | PlanError:
55
+ try:
56
+ text = path.read_text(encoding="utf-8")
57
+ except OSError as exc:
58
+ return PlanError(f"could not read plan at {path}: {exc}")
59
+ try:
60
+ data = json.loads(text)
61
+ except json.JSONDecodeError as exc:
62
+ return PlanError(f"corrupt plan file {path}: {exc}")
63
+ if not isinstance(data, dict):
64
+ return PlanError(f"corrupt plan file {path}: expected JSON object")
65
+ return data
66
+
67
+
68
+ def load_plan(name: str) -> PlanRecord | PlanError:
69
+ validated = validate_plan_name(name)
70
+ if isinstance(validated, PlanError):
71
+ return validated
72
+ path = readable_data_file("plans", f"{validated}.json")
73
+ if not path.is_file():
74
+ return PlanError(f'plan "{validated}" does not exist ({path})')
75
+ data = _read_json(path)
76
+ if isinstance(data, PlanError):
77
+ return data
78
+ try:
79
+ record = PlanRecord.from_dict(data)
80
+ except (KeyError, TypeError, ValueError) as exc:
81
+ return PlanError(f"corrupt plan file {path}: {exc}")
82
+ return record
83
+
84
+
85
+ def save_plan(record: PlanRecord) -> PlanError | None:
86
+ validated = validate_plan_name(record.name)
87
+ if isinstance(validated, PlanError):
88
+ return validated
89
+ record.updated_at = _utc_now_iso()
90
+ prepare_data_write()
91
+ return _atomic_write_json(_plan_path(validated), record.to_dict())
92
+
93
+
94
+ def list_plans(current_name: str | None = None) -> list[PlanSummary] | PlanError:
95
+ directory = readable_data_dir("plans")
96
+ if not directory.is_dir():
97
+ return []
98
+ summaries: list[PlanSummary] = []
99
+ for path in sorted(directory.glob("*.json")):
100
+ if path.name == "_current.json":
101
+ continue
102
+ name = path.stem
103
+ data = _read_json(path)
104
+ if isinstance(data, PlanError):
105
+ return data
106
+ try:
107
+ record = PlanRecord.from_dict(data)
108
+ except (KeyError, TypeError, ValueError) as exc:
109
+ return PlanError(f"corrupt plan file {path}: {exc}")
110
+ summaries.append(
111
+ PlanSummary(
112
+ name=record.name,
113
+ item_count=len(record.items),
114
+ updated_at=record.updated_at,
115
+ is_current=record.name == current_name,
116
+ )
117
+ )
118
+ return summaries
119
+
120
+
121
+ def create_plan(name: str) -> CreatePlanResult | PlanError:
122
+ validated = validate_plan_name(name)
123
+ if isinstance(validated, PlanError):
124
+ return validated
125
+ prepare_data_write()
126
+ path = _plan_path(validated)
127
+ if path.is_file():
128
+ loaded = load_plan(validated)
129
+ if isinstance(loaded, PlanError):
130
+ return loaded
131
+ return CreatePlanResult(record=loaded, created=False)
132
+ record = PlanRecord.new_empty(validated)
133
+ err = _atomic_write_json(path, record.to_dict())
134
+ if err is not None:
135
+ return err
136
+ return CreatePlanResult(record=record, created=True)
137
+
138
+
139
+ def add_item(
140
+ name: str,
141
+ item: PlanItem,
142
+ *,
143
+ force: bool = False,
144
+ ) -> AddItemResult | PlanError:
145
+ record = load_plan(name)
146
+ if isinstance(record, PlanError):
147
+ return record
148
+ replaced = False
149
+ for existing in record.items:
150
+ if existing.resource == item.resource:
151
+ if not force:
152
+ return PlanError(
153
+ f'resource "{item.resource}" is already in plan "{name}" '
154
+ "(use --force to replace)"
155
+ )
156
+ record.items = [i for i in record.items if i.resource != item.resource]
157
+ replaced = True
158
+ break
159
+ record.items.append(item)
160
+ record.revision += 1
161
+ err = save_plan(record)
162
+ if err is not None:
163
+ return err
164
+ return AddItemResult(record=record, item_id=item.item_id, replaced=replaced)
165
+
166
+
167
+ def remove_item(name: str, item_id: str) -> PlanRecord | PlanError:
168
+ record = load_plan(name)
169
+ if isinstance(record, PlanError):
170
+ return record
171
+ remaining = [item for item in record.items if item.item_id != item_id]
172
+ if len(remaining) == len(record.items):
173
+ return PlanError(f'item "{item_id}" not found in plan "{name}"')
174
+ record.items = remaining
175
+ record.revision += 1
176
+ err = save_plan(record)
177
+ if err is not None:
178
+ return err
179
+ return record
180
+
181
+
182
+ def clear_plan(name: str) -> PlanRecord | PlanError:
183
+ record = load_plan(name)
184
+ if isinstance(record, PlanError):
185
+ return record
186
+ if not record.items:
187
+ return record
188
+ record.items = []
189
+ record.revision += 1
190
+ err = save_plan(record)
191
+ if err is not None:
192
+ return err
193
+ return record
maproom/plan/tty.py ADDED
@@ -0,0 +1,34 @@
1
+ """Shared TTY confirmation helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class PromptClosed(Exception):
7
+ """The operator closed stdin or cancelled before answering a prompt."""
8
+
9
+ def __init__(self, message: str) -> None:
10
+ self.message = message
11
+ super().__init__(message)
12
+
13
+
14
+ def confirm_yes_no(prompt: str, *, default_no: bool = True) -> bool:
15
+ import sys
16
+
17
+ suffix = "[y/N]" if default_no else "[Y/n]"
18
+ while True:
19
+ try:
20
+ answer = input(f"{prompt} {suffix}: ").strip().lower()
21
+ except EOFError as exc:
22
+ raise PromptClosed(
23
+ "confirmation closed before an answer. Pass --force to skip the prompt."
24
+ ) from exc
25
+ except KeyboardInterrupt as exc:
26
+ print(file=sys.stderr)
27
+ raise PromptClosed("confirmation cancelled.") from exc
28
+ if not answer:
29
+ return not default_no
30
+ if answer in {"y", "yes"}:
31
+ return True
32
+ if answer in {"n", "no"}:
33
+ return False
34
+ print("Please answer y or n.", file=sys.stderr)