cometric 0.1.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 (83) hide show
  1. cometric/__init__.py +50 -0
  2. cometric/cli.py +210 -0
  3. cometric/core/__init__.py +0 -0
  4. cometric/core/api.py +835 -0
  5. cometric/core/engine.py +1386 -0
  6. cometric/core/enums.py +273 -0
  7. cometric/core/fingerprint.py +91 -0
  8. cometric/core/issues.py +68 -0
  9. cometric/core/ledger.py +165 -0
  10. cometric/core/models.py +450 -0
  11. cometric/core/money.py +110 -0
  12. cometric/core/packs.py +446 -0
  13. cometric/core/periods.py +102 -0
  14. cometric/core/predicates.py +139 -0
  15. cometric/core/quantities.py +138 -0
  16. cometric/core/schema.py +97 -0
  17. cometric/core/templates.py +338 -0
  18. cometric/core/tiers.py +78 -0
  19. cometric/core/validation.py +738 -0
  20. cometric/examples/case_a.json +293 -0
  21. cometric/examples/case_b.json +212 -0
  22. cometric/examples/case_c.json +233 -0
  23. cometric/examples/case_d.json +253 -0
  24. cometric/examples/case_e.json +258 -0
  25. cometric/examples/case_f.json +298 -0
  26. cometric/examples/case_g.json +243 -0
  27. cometric/examples/case_h.json +271 -0
  28. cometric/examples/spec_example.json +134 -0
  29. cometric/mcp/__init__.py +0 -0
  30. cometric/mcp/__main__.py +3 -0
  31. cometric/mcp/server.py +470 -0
  32. cometric/packs/alsp/concepts/provider_types.yaml +154 -0
  33. cometric/packs/alsp/concepts/service_categories.yaml +132 -0
  34. cometric/packs/alsp/concepts/unit_templates.yaml +132 -0
  35. cometric/packs/alsp/coverage.yaml +17 -0
  36. cometric/packs/alsp/evidence/claims.yaml +446 -0
  37. cometric/packs/alsp/evidence/sources.yaml +545 -0
  38. cometric/packs/alsp/overlays/levers.yaml +82 -0
  39. cometric/packs/alsp/overlays/mechanisms.yaml +19 -0
  40. cometric/packs/alsp/overlays/metrics.yaml +15 -0
  41. cometric/packs/alsp/overlays/pricing_models.yaml +186 -0
  42. cometric/packs/alsp/pack.yaml +9 -0
  43. cometric/packs/alsp/rules/rules.yaml +303 -0
  44. cometric/packs/base/concepts/automation_structures.yaml +207 -0
  45. cometric/packs/base/concepts/billing_bases.yaml +239 -0
  46. cometric/packs/base/concepts/cost_categories.yaml +494 -0
  47. cometric/packs/base/concepts/dimensions.yaml +404 -0
  48. cometric/packs/base/concepts/fee_components.yaml +105 -0
  49. cometric/packs/base/concepts/layers.yaml +146 -0
  50. cometric/packs/base/concepts/levers.yaml +1449 -0
  51. cometric/packs/base/concepts/mechanisms.yaml +295 -0
  52. cometric/packs/base/concepts/metrics.yaml +1149 -0
  53. cometric/packs/base/concepts/negotiation_exchanges.yaml +226 -0
  54. cometric/packs/base/concepts/offers.yaml +88 -0
  55. cometric/packs/base/concepts/pricing_models.yaml +821 -0
  56. cometric/packs/base/concepts/schema_map.yaml +1100 -0
  57. cometric/packs/base/concepts/selection_framework.yaml +215 -0
  58. cometric/packs/base/concepts/selection_heuristics.yaml +285 -0
  59. cometric/packs/base/coverage.yaml +33 -0
  60. cometric/packs/base/evidence/claims.yaml +442 -0
  61. cometric/packs/base/evidence/sources.yaml +293 -0
  62. cometric/packs/base/excluded.yaml +42 -0
  63. cometric/packs/base/pack.yaml +10 -0
  64. cometric/packs/base/rules/rules.yaml +521 -0
  65. cometric/packs/consulting/concepts/consulting_concepts.yaml +82 -0
  66. cometric/packs/consulting/concepts/provider_types.yaml +35 -0
  67. cometric/packs/consulting/concepts/service_categories.yaml +41 -0
  68. cometric/packs/consulting/concepts/unit_templates.yaml +36 -0
  69. cometric/packs/consulting/coverage.yaml +17 -0
  70. cometric/packs/consulting/overlays/pricing_models.yaml +29 -0
  71. cometric/packs/consulting/pack.yaml +11 -0
  72. cometric/packs/consulting/rules/rules.yaml +45 -0
  73. cometric/packs/consulting/templates/capped_tm.json +132 -0
  74. cometric/packs/consulting/templates/fixed_fee_plus_success.json +163 -0
  75. cometric/packs/consulting/templates/phased_fixed_fee.json +133 -0
  76. cometric/packs/consulting/templates/retainer_hours_drawdown.json +144 -0
  77. cometric/packs/consulting/templates/role_based_tm.json +123 -0
  78. cometric/py.typed +0 -0
  79. cometric-0.1.0.dist-info/METADATA +137 -0
  80. cometric-0.1.0.dist-info/RECORD +83 -0
  81. cometric-0.1.0.dist-info/WHEEL +4 -0
  82. cometric-0.1.0.dist-info/entry_points.txt +2 -0
  83. cometric-0.1.0.dist-info/licenses/LICENSE +202 -0
cometric/core/enums.py ADDED
@@ -0,0 +1,273 @@
1
+ """Core controlled vocabularies. Domain vocabulary lives in packs (P-09)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import StrEnum
6
+
7
+
8
+ class BillingBasis(StrEnum):
9
+ TIME = "TIME"
10
+ RESOURCE = "RESOURCE"
11
+ CAPACITY = "CAPACITY"
12
+ OUTPUT = "OUTPUT"
13
+ USAGE = "USAGE"
14
+ FIXED = "FIXED"
15
+ COST = "COST"
16
+ OUTCOME = "OUTCOME"
17
+
18
+
19
+ class ChargeCadence(StrEnum):
20
+ ONE_TIME = "ONE_TIME"
21
+ MONTHLY = "MONTHLY"
22
+ QUARTERLY = "QUARTERLY"
23
+ ANNUAL = "ANNUAL"
24
+ EVENT = "EVENT"
25
+ USAGE_TRIGGERED = "USAGE_TRIGGERED"
26
+
27
+
28
+ class CalculationMethod(StrEnum):
29
+ FIXED_RECURRING = "FIXED_RECURRING"
30
+ TIME = "TIME"
31
+ DEDICATED_RESOURCE = "DEDICATED_RESOURCE"
32
+ UNIT_OUTPUT = "UNIT_OUTPUT"
33
+ WEIGHTED_UNIT_OUTPUT = "WEIGHTED_UNIT_OUTPUT"
34
+ ALLOWANCE_OVERAGE = "ALLOWANCE_OVERAGE"
35
+ FIXED_PROJECT = "FIXED_PROJECT"
36
+ COST_PLUS = "COST_PLUS"
37
+ OUTCOME_ADJUSTMENT = "OUTCOME_ADJUSTMENT"
38
+
39
+
40
+ POST_V1_METHODS = {CalculationMethod.COST_PLUS}
41
+
42
+ METHOD_BASES: dict[CalculationMethod, set[BillingBasis]] = {
43
+ CalculationMethod.FIXED_RECURRING: {BillingBasis.FIXED, BillingBasis.CAPACITY},
44
+ CalculationMethod.TIME: {BillingBasis.TIME},
45
+ CalculationMethod.DEDICATED_RESOURCE: {BillingBasis.RESOURCE},
46
+ CalculationMethod.UNIT_OUTPUT: {BillingBasis.OUTPUT, BillingBasis.USAGE},
47
+ CalculationMethod.WEIGHTED_UNIT_OUTPUT: {BillingBasis.OUTPUT},
48
+ CalculationMethod.ALLOWANCE_OVERAGE: {BillingBasis.OUTPUT, BillingBasis.USAGE},
49
+ CalculationMethod.FIXED_PROJECT: {BillingBasis.FIXED},
50
+ CalculationMethod.COST_PLUS: {BillingBasis.COST},
51
+ CalculationMethod.OUTCOME_ADJUSTMENT: {BillingBasis.OUTCOME},
52
+ }
53
+
54
+ FIXED_METHODS = {
55
+ CalculationMethod.FIXED_RECURRING,
56
+ CalculationMethod.FIXED_PROJECT,
57
+ CalculationMethod.DEDICATED_RESOURCE,
58
+ }
59
+
60
+
61
+ class TierMethod(StrEnum):
62
+ MARGINAL = "MARGINAL"
63
+ ALL_UNITS = "ALL_UNITS"
64
+ GRADUATED_BLOCK = "GRADUATED_BLOCK"
65
+
66
+
67
+ class TierScope(StrEnum):
68
+ ALL_ELIGIBLE = "ALL_ELIGIBLE"
69
+ EXCESS_ONLY = "EXCESS_ONLY"
70
+
71
+
72
+ class AccumulationPeriod(StrEnum):
73
+ MONTH = "MONTH"
74
+ QUARTER = "QUARTER"
75
+ YEAR = "YEAR"
76
+ CONTRACT_YEAR = "CONTRACT_YEAR"
77
+ TERM = "TERM"
78
+
79
+
80
+ class Recognition(StrEnum):
81
+ CUMULATIVE = "CUMULATIVE"
82
+ PERIOD_END = "PERIOD_END"
83
+ PER_SEGMENT = "PER_SEGMENT"
84
+
85
+
86
+ class RolloverPolicy(StrEnum):
87
+ NONE = "NONE"
88
+ NEXT_PERIOD = "NEXT_PERIOD"
89
+ TERM = "TERM"
90
+
91
+
92
+ class CommitmentKind(StrEnum):
93
+ MINIMUM_SPEND = "MINIMUM_SPEND"
94
+ MINIMUM_VOLUME = "MINIMUM_VOLUME"
95
+ RESERVED_CAPACITY = "RESERVED_CAPACITY"
96
+ PREPAID_CREDIT = "PREPAID_CREDIT"
97
+
98
+
99
+ class AggregationScope(StrEnum):
100
+ COMPONENT = "COMPONENT"
101
+ SERVICE = "SERVICE"
102
+ ENGAGEMENT = "ENGAGEMENT"
103
+
104
+
105
+ class TestedAgainst(StrEnum):
106
+ GROSS = "GROSS"
107
+ NET_OF_DISCOUNTS = "NET_OF_DISCOUNTS"
108
+ NET_OF_CREDITS = "NET_OF_CREDITS"
109
+
110
+
111
+ class ShortfallRule(StrEnum):
112
+ PERIOD_END_TRUE_UP = "PERIOD_END_TRUE_UP"
113
+ PER_SEGMENT = "PER_SEGMENT"
114
+
115
+
116
+ class AdjustmentType(StrEnum):
117
+ DISCOUNT = "DISCOUNT"
118
+ REBATE = "REBATE"
119
+ COLLAR = "COLLAR"
120
+ SLA_CREDIT = "SLA_CREDIT"
121
+ HOLDBACK = "HOLDBACK"
122
+ BONUS = "BONUS"
123
+ CAP = "CAP"
124
+ INDEXATION = "INDEXATION"
125
+
126
+
127
+ class ProrationPolicy(StrEnum):
128
+ CALENDAR_DAYS = "CALENDAR_DAYS"
129
+ FULL_MONTH_FROM_NEXT = "FULL_MONTH_FROM_NEXT"
130
+ FULL_MONTH_FROM_CURRENT = "FULL_MONTH_FROM_CURRENT"
131
+
132
+
133
+ class RoundingMode(StrEnum):
134
+ HALF_UP = "HALF_UP"
135
+ HALF_EVEN = "HALF_EVEN"
136
+
137
+
138
+ class RoundingLevel(StrEnum):
139
+ LINE_ITEM = "LINE_ITEM"
140
+ PERIOD_TOTAL = "PERIOD_TOTAL"
141
+
142
+
143
+ class UnitKind(StrEnum):
144
+ COUNT = "COUNT"
145
+ WEIGHTED = "WEIGHTED"
146
+ HOURS = "HOURS"
147
+ FTE_MONTHS = "FTE_MONTHS"
148
+ METER = "METER"
149
+
150
+
151
+ class CostBehavior(StrEnum):
152
+ FIXED = "FIXED"
153
+ VARIABLE = "VARIABLE"
154
+ STEP = "STEP"
155
+ TIERED_VARIABLE = "TIERED_VARIABLE"
156
+ ONE_TIME = "ONE_TIME"
157
+
158
+
159
+ class CostPeriod(StrEnum):
160
+ MONTHLY = "MONTHLY"
161
+ ANNUAL = "ANNUAL"
162
+ TERM = "TERM"
163
+
164
+
165
+ class MarginLayer(StrEnum):
166
+ DIRECT_DELIVERY = "DIRECT_DELIVERY"
167
+ ENGAGEMENT_AVOIDABLE = "ENGAGEMENT_AVOIDABLE"
168
+ PORTFOLIO_SHARED = "PORTFOLIO_SHARED"
169
+ CORPORATE_OVERHEAD = "CORPORATE_OVERHEAD"
170
+
171
+
172
+ class CostCategory(StrEnum):
173
+ DEDICATED_LABOR = "DEDICATED_LABOR"
174
+ POOLED_LABOR = "POOLED_LABOR"
175
+ DELIVERY_MANAGEMENT = "DELIVERY_MANAGEMENT"
176
+ QA_REWORK = "QA_REWORK"
177
+ AI_INFERENCE = "AI_INFERENCE"
178
+ PLATFORM_OPERATIONS = "PLATFORM_OPERATIONS"
179
+ THIRD_PARTY = "THIRD_PARTY"
180
+ CLIENT_IMPLEMENTATION = "CLIENT_IMPLEMENTATION"
181
+ REUSABLE_ENGINEERING = "REUSABLE_ENGINEERING"
182
+ TRANSITION = "TRANSITION"
183
+ ENGAGEMENT_OVERHEAD = "ENGAGEMENT_OVERHEAD"
184
+ IDLE_POOLED_CAPACITY = "IDLE_POOLED_CAPACITY"
185
+ CORPORATE_OVERHEAD = "CORPORATE_OVERHEAD"
186
+
187
+
188
+ class Avoidability(StrEnum):
189
+ AVOIDABLE = "AVOIDABLE"
190
+ UNAVOIDABLE = "UNAVOIDABLE"
191
+ UNKNOWN = "UNKNOWN"
192
+
193
+
194
+ class TransitionView(StrEnum):
195
+ INCURRED = "INCURRED"
196
+ AMORTIZED = "AMORTIZED"
197
+
198
+
199
+ class BreachMode(StrEnum):
200
+ OVERFLOW_COST = "OVERFLOW_COST"
201
+ BACKLOG = "BACKLOG"
202
+ INFEASIBLE = "INFEASIBLE"
203
+
204
+
205
+ class Topology(StrEnum):
206
+ DEDICATED = "DEDICATED"
207
+ POOLED = "POOLED"
208
+ HYBRID = "HYBRID"
209
+
210
+
211
+ class Origin(StrEnum):
212
+ OBSERVED = "OBSERVED"
213
+ CONTRACTED = "CONTRACTED"
214
+ ESTIMATED = "ESTIMATED"
215
+ ILLUSTRATIVE = "ILLUSTRATIVE"
216
+ INTERNAL_POLICY = "INTERNAL_POLICY"
217
+
218
+
219
+ class Distribution(StrEnum):
220
+ FLAT = "FLAT"
221
+ PROFILE = "PROFILE"
222
+
223
+
224
+ class RiskBearer(StrEnum):
225
+ CLIENT = "CLIENT"
226
+ PROVIDER = "PROVIDER"
227
+ SHARED = "SHARED"
228
+ THIRD_PARTY = "THIRD_PARTY"
229
+ NONE_ADVERSE = "NONE_ADVERSE"
230
+
231
+
232
+ class PartyRole(StrEnum):
233
+ CLIENT = "CLIENT"
234
+ PROVIDER = "PROVIDER"
235
+ SUBCONTRACTOR = "SUBCONTRACTOR"
236
+
237
+
238
+ class ClassificationAuthority(StrEnum):
239
+ PROVIDER = "PROVIDER"
240
+ CLIENT = "CLIENT"
241
+ JOINT = "JOINT"
242
+
243
+
244
+ class Severity(StrEnum):
245
+ INFO = "INFO"
246
+ WARNING = "WARNING"
247
+ APPROVAL_REQUIRED = "APPROVAL_REQUIRED"
248
+ ERROR = "ERROR"
249
+
250
+
251
+ class EvidenceClass(StrEnum):
252
+ A_DIRECT = "A_DIRECT"
253
+ B_CORROBORATED = "B_CORROBORATED"
254
+ C_INFERENCE = "C_INFERENCE"
255
+ D_PROPOSED = "D_PROPOSED"
256
+
257
+
258
+ class Prevalence(StrEnum):
259
+ ESTABLISHED_COMMON = "ESTABLISHED_COMMON"
260
+ DOCUMENTED_SPECIALIZED = "DOCUMENTED_SPECIALIZED"
261
+ EMERGING = "EMERGING"
262
+ UNVERIFIED = "UNVERIFIED"
263
+
264
+
265
+ class OutcomeForm(StrEnum):
266
+ SHARE = "SHARE" # share of measured improvement against a baseline
267
+ SUCCESS = "SUCCESS" # fixed amount when a target is met
268
+ PERCENT_OF_OUTCOME = "PERCENT_OF_OUTCOME" # share of a measured result such as a recovery
269
+
270
+
271
+ class OutcomeDirection(StrEnum):
272
+ HIGHER_IS_BETTER = "HIGHER_IS_BETTER"
273
+ LOWER_IS_BETTER = "LOWER_IS_BETTER"
@@ -0,0 +1,91 @@
1
+ """Canonical serialization and input fingerprint (spec 8.4, T-012, T-019)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from datetime import date
8
+ from decimal import Decimal
9
+ from enum import Enum
10
+ from typing import Any
11
+
12
+ from pydantic import BaseModel
13
+
14
+ from .money import dec_str
15
+
16
+ # Arrays whose order carries no meaning; sorted by id/code (or name+period for assumptions).
17
+ UNORDERED_KEYS = {
18
+ "components",
19
+ "entitlements",
20
+ "rate_schedules",
21
+ "commitments",
22
+ "adjustments",
23
+ "cost_components",
24
+ "unit_definitions",
25
+ "services",
26
+ "parties",
27
+ "weight_tables",
28
+ "bands",
29
+ "capacity",
30
+ "roles",
31
+ "arrangement_versions",
32
+ "packs",
33
+ "assumptions",
34
+ "risk_allocations",
35
+ "production_standards",
36
+ "depends_on",
37
+ "applies_to",
38
+ "component_ids",
39
+ "overflow_replaces",
40
+ "exclusions",
41
+ "role_rates",
42
+ "resources",
43
+ }
44
+
45
+
46
+ def to_jsonable(obj: Any) -> Any:
47
+ if isinstance(obj, BaseModel):
48
+ return to_jsonable(obj.model_dump(mode="python", by_alias=True))
49
+ if isinstance(obj, Decimal):
50
+ return dec_str(obj)
51
+ if isinstance(obj, Enum):
52
+ return obj.value
53
+ if isinstance(obj, date):
54
+ return obj.isoformat()
55
+ if isinstance(obj, dict):
56
+ return {str(k.value if isinstance(k, Enum) else k): to_jsonable(v) for k, v in obj.items()}
57
+ if isinstance(obj, (list, tuple, set)):
58
+ return [to_jsonable(v) for v in obj]
59
+ return obj
60
+
61
+
62
+ def _sort_key(item: Any) -> str:
63
+ if isinstance(item, dict):
64
+ for k in ("id", "code", "role"):
65
+ if k in item:
66
+ return str(item[k])
67
+ if "name" in item:
68
+ return f"{item['name']}|{item.get('time_period', '')}"
69
+ return json.dumps(item, sort_keys=True)
70
+ return json.dumps(item, sort_keys=True)
71
+
72
+
73
+ def canonicalize(obj: Any, key: str | None = None) -> Any:
74
+ if isinstance(obj, dict):
75
+ return {k: canonicalize(v, k) for k, v in obj.items()}
76
+ if isinstance(obj, list):
77
+ items = [canonicalize(v) for v in obj]
78
+ if key in UNORDERED_KEYS:
79
+ items = sorted(items, key=_sort_key)
80
+ return items
81
+ return obj
82
+
83
+
84
+ def canonical_json(obj: Any) -> str:
85
+ return json.dumps(
86
+ canonicalize(to_jsonable(obj)), sort_keys=True, separators=(",", ":"), ensure_ascii=False
87
+ )
88
+
89
+
90
+ def fingerprint(payload: dict) -> str:
91
+ return "sha256:" + hashlib.sha256(canonical_json(payload).encode("utf-8")).hexdigest()
@@ -0,0 +1,68 @@
1
+ """Structured issues with JSON Pointer paths so callers (and agents) can repair input."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from .enums import Severity
8
+
9
+
10
+ def pointer(*parts: object) -> str:
11
+ out = []
12
+ for p in parts:
13
+ s = str(p).replace("~", "~0").replace("/", "~1")
14
+ out.append(s)
15
+ return "/" + "/".join(out) if out else ""
16
+
17
+
18
+ @dataclass
19
+ class Issue:
20
+ code: str
21
+ severity: Severity
22
+ message: str
23
+ path: str = ""
24
+ detail: dict = field(default_factory=dict)
25
+
26
+ def as_dict(self) -> dict:
27
+ d = {
28
+ "code": self.code,
29
+ "severity": str(self.severity),
30
+ "message": self.message,
31
+ "path": self.path,
32
+ }
33
+ if self.detail:
34
+ d["detail"] = self.detail
35
+ return d
36
+
37
+
38
+ class Issues(list):
39
+ def add(self, code: str, severity: Severity, message: str, path: str = "", **detail) -> None:
40
+ self.append(Issue(code, severity, message, path, detail))
41
+
42
+ def error(self, code: str, message: str, path: str = "", **detail) -> None:
43
+ self.add(code, Severity.ERROR, message, path, **detail)
44
+
45
+ def warn(self, code: str, message: str, path: str = "", **detail) -> None:
46
+ self.add(code, Severity.WARNING, message, path, **detail)
47
+
48
+ def approval(self, code: str, message: str, path: str = "", **detail) -> None:
49
+ self.add(code, Severity.APPROVAL_REQUIRED, message, path, **detail)
50
+
51
+ def info(self, code: str, message: str, path: str = "", **detail) -> None:
52
+ self.add(code, Severity.INFO, message, path, **detail)
53
+
54
+ @property
55
+ def has_errors(self) -> bool:
56
+ return any(i.severity == Severity.ERROR for i in self)
57
+
58
+ def as_list(self) -> list[dict]:
59
+ return [i.as_dict() for i in self]
60
+
61
+
62
+ class CometricError(Exception):
63
+ """Raised when inputs cannot be evaluated; carries structured issues."""
64
+
65
+ def __init__(self, issues: Issues, status: str = "invalid"):
66
+ self.issues = issues
67
+ self.status = status
68
+ super().__init__("; ".join(f"{i.code}: {i.message} ({i.path})" for i in issues[:5]))
@@ -0,0 +1,165 @@
1
+ """Entitlement ledger: grants, FIFO consumption, rollover, expiry (spec 4.4, T-006)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from decimal import Decimal
7
+
8
+ from .enums import RolloverPolicy
9
+ from .models import Entitlement
10
+ from .money import ZERO
11
+ from .periods import Month, month_str
12
+
13
+
14
+ @dataclass
15
+ class Lot:
16
+ lot_id: str
17
+ origin: str # GRANT or ROLLOVER_IN
18
+ period: tuple
19
+ quantity: Decimal
20
+ remaining: Decimal
21
+ source_lot: str | None = None
22
+
23
+
24
+ @dataclass
25
+ class LedgerEntry:
26
+ period: str
27
+ entitlement_id: str
28
+ entry_type: str
29
+ quantity: Decimal
30
+ lot_id: str
31
+ accumulation_period: str
32
+ contract_version: str
33
+ unit: str
34
+
35
+ def as_dict(self) -> dict:
36
+ return {
37
+ "period": self.period,
38
+ "entitlement_id": self.entitlement_id,
39
+ "entry_type": self.entry_type,
40
+ "quantity": self.quantity,
41
+ "lot_id": self.lot_id,
42
+ "accumulation_period": self.accumulation_period,
43
+ "contract_version": self.contract_version,
44
+ "unit": self.unit,
45
+ }
46
+
47
+
48
+ @dataclass
49
+ class EntitlementLedger:
50
+ entitlement: Entitlement
51
+ lots: list[Lot] = field(default_factory=list)
52
+ entries: list[LedgerEntry] = field(default_factory=list)
53
+ current_period: tuple | None = None
54
+ last_month: Month | None = None
55
+ version_id: str = ""
56
+ _seq: int = 0
57
+
58
+ def _entry(self, m: Month, kind: str, qty: Decimal, lot: Lot) -> None:
59
+ self.entries.append(
60
+ LedgerEntry(
61
+ month_str(m),
62
+ self.entitlement.id,
63
+ kind,
64
+ qty,
65
+ lot.lot_id,
66
+ str(self.entitlement.accumulation_period),
67
+ self.version_id,
68
+ self.entitlement.unit,
69
+ )
70
+ )
71
+
72
+ def start_month(self, m: Month, key: tuple, entitlement: Entitlement, version_id: str) -> None:
73
+ """Open the accumulation period for month m, closing the previous one if it changed."""
74
+ self.entitlement = entitlement
75
+ self.version_id = version_id
76
+ if key != self.current_period:
77
+ if self.current_period is not None and self.last_month is not None:
78
+ self._close(self.last_month, final=False)
79
+ self.current_period = key
80
+ self._seq += 1
81
+ lot = Lot(
82
+ f"{entitlement.id}#{self._seq}",
83
+ "GRANT",
84
+ key,
85
+ entitlement.included_quantity,
86
+ entitlement.included_quantity,
87
+ )
88
+ self.lots.append(lot)
89
+ self._entry(m, "GRANT", entitlement.included_quantity, lot)
90
+ self.last_month = m
91
+
92
+ def consume(self, m: Month, quantity: Decimal) -> tuple[Decimal, Decimal]:
93
+ """FIFO consumption: rolled-in lots first, then the current grant. Returns (in_allowance, excess)."""
94
+ remaining = quantity
95
+ open_lots = sorted(
96
+ (lot for lot in self.lots if lot.remaining > 0),
97
+ key=lambda lot: (lot.origin != "ROLLOVER_IN", lot.lot_id),
98
+ )
99
+ for lot in open_lots:
100
+ if remaining <= 0:
101
+ break
102
+ take = min(lot.remaining, remaining)
103
+ lot.remaining -= take
104
+ remaining -= take
105
+ self._entry(m, "CONSUME", take, lot)
106
+ return quantity - remaining, remaining
107
+
108
+ def _close(self, m: Month, final: bool) -> None:
109
+ policy = self.entitlement.rollover.policy
110
+ ceiling = self.entitlement.rollover.ceiling
111
+ for lot in list(self.lots):
112
+ if lot.remaining <= 0:
113
+ continue
114
+ roll = ZERO
115
+ if not final and policy == RolloverPolicy.TERM:
116
+ roll = lot.remaining
117
+ elif not final and policy == RolloverPolicy.NEXT_PERIOD and lot.origin == "GRANT":
118
+ roll = lot.remaining if ceiling is None else min(lot.remaining, ceiling)
119
+ expire = lot.remaining - roll
120
+ if roll > 0:
121
+ self._seq += 1
122
+ self._entry(m, "ROLLOVER_OUT", roll, lot)
123
+ new = Lot(
124
+ f"{self.entitlement.id}#{self._seq}",
125
+ "ROLLOVER_IN",
126
+ ("next",),
127
+ roll,
128
+ roll,
129
+ lot.lot_id,
130
+ )
131
+ self.lots.append(new)
132
+ self._entry(m, "ROLLOVER_IN", roll, new)
133
+ if expire > 0:
134
+ self._entry(m, "EXPIRE", expire, lot)
135
+ lot.remaining = ZERO
136
+
137
+ def finish(self, m: Month, engagement_ended: bool) -> None:
138
+ """Close at the end of the run. Expire at engagement end; otherwise leave lots open."""
139
+ if engagement_ended and self.last_month is not None:
140
+ self._close(self.last_month, final=True)
141
+
142
+ def granted(self) -> Decimal:
143
+ return sum((e.quantity for e in self.entries if e.entry_type == "GRANT"), ZERO)
144
+
145
+ def consumed(self) -> Decimal:
146
+ return sum((e.quantity for e in self.entries if e.entry_type == "CONSUME"), ZERO)
147
+
148
+ def check_invariant(self) -> list[str]:
149
+ """Every lot: in = consumed + rolled out + expired + still open (T-006)."""
150
+ problems = []
151
+ for lot in self.lots:
152
+ out = sum(
153
+ (
154
+ e.quantity
155
+ for e in self.entries
156
+ if e.lot_id == lot.lot_id
157
+ and e.entry_type in {"CONSUME", "ROLLOVER_OUT", "EXPIRE"}
158
+ ),
159
+ ZERO,
160
+ )
161
+ if out + lot.remaining != lot.quantity:
162
+ problems.append(
163
+ f"lot {lot.lot_id}: {lot.quantity} in, {out} out, {lot.remaining} open"
164
+ )
165
+ return problems