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
@@ -0,0 +1,138 @@
1
+ """Turn scenario assumptions into exact monthly quantities (spec 4.7, 6.1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from decimal import Decimal
7
+
8
+ from .enums import Distribution, Origin, UnitKind
9
+ from .issues import Issues, pointer
10
+ from .models import Engagement, Scenario
11
+ from .money import ZERO, allocate_exact, allocate_weighted
12
+ from .periods import Month, months_between, parse_month
13
+
14
+ GENERIC_UNITS = {"hours": 2, "fte": 4, "flag": 0, "count": 0, "currency": 2, "ratio": 6}
15
+
16
+
17
+ def _scale_for(unit: str, value: Decimal, engagement: Engagement) -> int:
18
+ exponent_scale = (
19
+ max(0, -value.as_tuple().exponent) if isinstance(value.as_tuple().exponent, int) else 0
20
+ )
21
+ for u in engagement.unit_definitions:
22
+ if u.code == unit:
23
+ if u.kind == UnitKind.COUNT:
24
+ return 0
25
+ if u.kind == UnitKind.HOURS:
26
+ return max(2, exponent_scale)
27
+ return max(4, exponent_scale)
28
+ if unit in GENERIC_UNITS:
29
+ return max(GENERIC_UNITS[unit], exponent_scale)
30
+ if unit == engagement.currency:
31
+ return max(2, exponent_scale)
32
+ return max(4, exponent_scale)
33
+
34
+
35
+ def known_units(engagement: Engagement) -> set[str]:
36
+ units = (
37
+ {u.code for u in engagement.unit_definitions} | set(GENERIC_UNITS) | {engagement.currency}
38
+ )
39
+ for wt in engagement.weight_tables:
40
+ units.add(wt.weighted_unit)
41
+ return units
42
+
43
+
44
+ def _months_for(period: str, months: list[Month]) -> list[Month]:
45
+ if period == "TERM":
46
+ return list(months)
47
+ if re.match(r"^\d{4}$", period):
48
+ return [m for m in months if m[0] == int(period)]
49
+ if ".." in period:
50
+ a, b = period.split("..")
51
+ span = set(months_between(parse_month(a), parse_month(b)))
52
+ return [m for m in months if m in span]
53
+ m = parse_month(period)
54
+ return [m] if m in months else []
55
+
56
+
57
+ class Quantities:
58
+ """name -> month -> Decimal, plus provenance."""
59
+
60
+ def __init__(self) -> None:
61
+ self.values: dict[str, dict[Month, Decimal]] = {}
62
+ self.units: dict[str, str] = {}
63
+ self.origins: dict[str, set[Origin]] = {}
64
+
65
+ def get(self, name: str, m: Month) -> Decimal | None:
66
+ series = self.values.get(name)
67
+ if series is None:
68
+ return None
69
+ return series.get(m, ZERO)
70
+
71
+ def has(self, name: str) -> bool:
72
+ return name in self.values
73
+
74
+ def total(self, name: str) -> Decimal:
75
+ return sum(self.values.get(name, {}).values(), ZERO)
76
+
77
+ def set(self, name: str, m: Month, value: Decimal) -> None:
78
+ self.values.setdefault(name, {})[m] = value
79
+
80
+
81
+ def build_quantities(
82
+ engagement: Engagement, scenario: Scenario, months: list[Month], issues: Issues
83
+ ) -> Quantities:
84
+ q = Quantities()
85
+ seen: dict[str, set[Month]] = {}
86
+ units = known_units(engagement)
87
+ for i, a in enumerate(scenario.assumptions):
88
+ path = pointer("scenario", "assumptions", i)
89
+ if a.unit not in units:
90
+ issues.error(
91
+ "UNKNOWN_UNIT",
92
+ f"assumption {a.name!r} uses unit {a.unit!r}, which is not defined",
93
+ path + "/unit",
94
+ )
95
+ continue
96
+ targets = _months_for(a.time_period, months)
97
+ if not targets:
98
+ issues.warn(
99
+ "ASSUMPTION_OUTSIDE_HORIZON",
100
+ f"assumption {a.name!r} covers no month in the horizon",
101
+ path + "/time_period",
102
+ )
103
+ continue
104
+ overlap = seen.setdefault(a.name, set()) & set(targets)
105
+ if overlap:
106
+ issues.error(
107
+ "ASSUMPTION_OVERLAP",
108
+ f"assumption {a.name!r} is given twice for the same month",
109
+ path + "/time_period",
110
+ )
111
+ continue
112
+ seen[a.name] |= set(targets)
113
+ if a.value < 0:
114
+ issues.error("NEGATIVE_QUANTITY", f"assumption {a.name!r} is negative", path + "/value")
115
+ continue
116
+ scale = _scale_for(a.unit, a.value, engagement)
117
+ try:
118
+ if len(targets) == 1:
119
+ shares = [a.value]
120
+ elif a.distribution == Distribution.PROFILE:
121
+ if len(a.profile) != len(targets):
122
+ issues.error(
123
+ "PROFILE_LENGTH",
124
+ f"profile for {a.name!r} needs {len(targets)} weights",
125
+ path + "/profile",
126
+ )
127
+ continue
128
+ shares = allocate_weighted(a.value, list(a.profile), scale)
129
+ else:
130
+ shares = allocate_exact(a.value, len(targets), scale)
131
+ except ValueError as exc:
132
+ issues.error("NOT_ALLOCATABLE", str(exc), path + "/value")
133
+ continue
134
+ for m, s in zip(targets, shares, strict=True):
135
+ q.set(a.name, m, s)
136
+ q.units[a.name] = a.unit
137
+ q.origins.setdefault(a.name, set()).add(a.origin)
138
+ return q
@@ -0,0 +1,97 @@
1
+ """JSON Schema export for every input model (spec 8.3 describe_schema)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pydantic import BaseModel
6
+
7
+ from . import models
8
+
9
+ MODELS: dict[str, type[BaseModel]] = {
10
+ "engagement": models.Engagement,
11
+ "scenario": models.Scenario,
12
+ "cost_policy": models.CostPolicy,
13
+ "tolerance_policy": models.TolerancePolicy,
14
+ "arrangement_version": models.ArrangementVersion,
15
+ "fee_component": models.FeeComponent,
16
+ "rate_schedule": models.RateSchedule,
17
+ "entitlement": models.Entitlement,
18
+ "commitment": models.Commitment,
19
+ "adjustment": models.Adjustment,
20
+ "delivery_plan": models.DeliveryPlan,
21
+ "cost_component": models.CostComponent,
22
+ "assumption": models.Assumption,
23
+ }
24
+
25
+ SEARCH_SPEC_SCHEMA = {
26
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
27
+ "title": "SearchSpec",
28
+ "type": "object",
29
+ "required": ["engagement", "scenarios", "parameters"],
30
+ "properties": {
31
+ "engagement": {
32
+ "type": "object",
33
+ "description": "Base engagement; parameters overwrite values at JSON Pointers.",
34
+ },
35
+ "scenarios": {"type": "array", "items": {"type": "object"}},
36
+ "cost_policy": {
37
+ "description": "Cost policy object or the name of a built-in policy such as 'reference'."
38
+ },
39
+ "parameters": {
40
+ "type": "array",
41
+ "items": {
42
+ "type": "object",
43
+ "required": ["name", "pointer"],
44
+ "properties": {
45
+ "name": {"type": "string"},
46
+ "pointer": {
47
+ "type": "string",
48
+ "description": "JSON Pointer into the engagement, e.g. /arrangement_versions/0/components/0/fixed_amount",
49
+ },
50
+ "values": {"type": "array", "items": {"type": "string"}},
51
+ "range": {
52
+ "type": "object",
53
+ "properties": {
54
+ "from": {"type": "string"},
55
+ "to": {"type": "string"},
56
+ "step": {"type": "string"},
57
+ },
58
+ },
59
+ },
60
+ },
61
+ },
62
+ "constraints": {
63
+ "type": "object",
64
+ "description": "Predicate over {scenarios: {id: metrics}, parameters: {...}}",
65
+ },
66
+ "objective": {
67
+ "type": "object",
68
+ "properties": {
69
+ "metric": {"type": "string"},
70
+ "sense": {"enum": ["max", "min"]},
71
+ "aggregation": {"enum": ["BASE", "WORST", "MEAN"]},
72
+ "base_scenario": {"type": "string"},
73
+ },
74
+ },
75
+ "frontier_metrics": {
76
+ "type": "array",
77
+ "items": {
78
+ "type": "object",
79
+ "properties": {"path": {"type": "string"}, "sense": {"enum": ["max", "min"]}},
80
+ },
81
+ },
82
+ "max_candidates": {"type": "integer", "maximum": 10000},
83
+ "max_returned": {"type": "integer"},
84
+ },
85
+ }
86
+
87
+
88
+ def describe_schema(model: str) -> dict:
89
+ if model == "search_spec":
90
+ return SEARCH_SPEC_SCHEMA
91
+ if model not in MODELS:
92
+ raise KeyError(f"no model {model!r}; models: {sorted([*MODELS, 'search_spec'])}")
93
+ return MODELS[model].model_json_schema(by_alias=True)
94
+
95
+
96
+ def model_names() -> list[str]:
97
+ return sorted([*MODELS, "search_spec"])
@@ -0,0 +1,338 @@
1
+ """Domain-neutral engagement templates (spec 8.3 get_template, T-029).
2
+
3
+ Unknown values are the string "<required>". Each template lists the pointers to fill and an
4
+ illustrative example for each, so an agent knows the expected shape.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+
11
+ R = "<required>"
12
+
13
+
14
+ def _base(
15
+ eid: str, unit_code: str, components: list, *, entitlements=None, schedules=None, costs=None
16
+ ) -> dict:
17
+ return {
18
+ "schema_version": "0.2",
19
+ "engagement_id": eid,
20
+ "name": R,
21
+ "currency": R,
22
+ "start_date": R,
23
+ "end_date": R,
24
+ "unit_definitions": [
25
+ {"code": unit_code, "kind": "COUNT", "counting_rule": R, "acceptance_rule": R}
26
+ ],
27
+ "services": [{"id": "service", "unit_definition_id": unit_code}],
28
+ "arrangement_versions": [
29
+ {
30
+ "id": "v1",
31
+ "effective_from": R,
32
+ "components": components,
33
+ "entitlements": entitlements or [],
34
+ "rate_schedules": schedules or [],
35
+ }
36
+ ],
37
+ "delivery_plan": {"cost_components": costs or []},
38
+ }
39
+
40
+
41
+ def _comp(cid: str, method: str, basis: str, cadence: str, **kw) -> dict:
42
+ c = {
43
+ "id": cid,
44
+ "service_id": "service",
45
+ "calculation_method": method,
46
+ "billing_basis": basis,
47
+ "charge_cadence": cadence,
48
+ "currency": R,
49
+ "quantity_source": None,
50
+ "unit": None,
51
+ "effective_period": {"from": R, "to": None},
52
+ "depends_on": [],
53
+ }
54
+ c.update(kw)
55
+ return c
56
+
57
+
58
+ def _schedule(sid: str, unit: str) -> dict:
59
+ return {
60
+ "id": sid,
61
+ "currency": R,
62
+ "unit": unit,
63
+ "tier_method": "MARGINAL",
64
+ "tier_scope": "ALL_ELIGIBLE",
65
+ "accumulation_period": "MONTH",
66
+ "tiers": [{"from": "0", "to": None, "rate": R}],
67
+ }
68
+
69
+
70
+ def _scenario(name: str, unit: str) -> dict:
71
+ return {
72
+ "id": "base",
73
+ "assumptions": [{"name": name, "value": R, "unit": unit, "time_period": R, "origin": R}],
74
+ }
75
+
76
+
77
+ COMMON_EXAMPLES = {
78
+ "/engagement/name": "Contract review managed service",
79
+ "/engagement/currency": "USD",
80
+ "/engagement/start_date": "2027-01-01",
81
+ "/engagement/end_date": "2027-12-31",
82
+ "/engagement/unit_definitions/0/counting_rule": "One completed review of one eligible contract",
83
+ "/engagement/unit_definitions/0/acceptance_rule": "Accepted on client sign-off",
84
+ "/engagement/arrangement_versions/0/effective_from": "2027-01-01",
85
+ "/scenario/assumptions/0/time_period": "TERM",
86
+ "/scenario/assumptions/0/origin": "ESTIMATED",
87
+ }
88
+
89
+
90
+ def _template(tid: str, description: str, engagement: dict, scenario: dict, examples: dict) -> dict:
91
+ ex = dict(COMMON_EXAMPLES)
92
+ ex.update(examples)
93
+ for i, _c in enumerate(engagement["arrangement_versions"][0]["components"]):
94
+ ex[f"/engagement/arrangement_versions/0/components/{i}/currency"] = "USD"
95
+ ex[f"/engagement/arrangement_versions/0/components/{i}/effective_period/from"] = (
96
+ "2027-01-01"
97
+ )
98
+ for i, _ in enumerate(engagement["arrangement_versions"][0]["rate_schedules"]):
99
+ ex[f"/engagement/arrangement_versions/0/rate_schedules/{i}/currency"] = "USD"
100
+ return {
101
+ "template_id": tid,
102
+ "description": description,
103
+ "engagement": engagement,
104
+ "scenario": scenario,
105
+ "examples": ex,
106
+ }
107
+
108
+
109
+ def _all() -> dict[str, dict]:
110
+ t = {}
111
+ t["fixed_managed_service"] = _template(
112
+ "fixed_managed_service",
113
+ "Fixed monthly managed service with an included allowance and overage, so volume exposure is bounded.",
114
+ _base(
115
+ "TEMPLATE-FIXED-MANAGED",
116
+ "unit",
117
+ [
118
+ _comp("base", "FIXED_RECURRING", "FIXED", "MONTHLY", fixed_amount=R),
119
+ _comp(
120
+ "overage",
121
+ "ALLOWANCE_OVERAGE",
122
+ "OUTPUT",
123
+ "MONTHLY",
124
+ quantity_source="scenario.units",
125
+ unit="unit",
126
+ entitlement_id="allowance",
127
+ rate_schedule_id="overage_rate",
128
+ depends_on=["allowance"],
129
+ ),
130
+ ],
131
+ entitlements=[
132
+ {
133
+ "id": "allowance",
134
+ "granted_by": "base",
135
+ "unit": "unit",
136
+ "included_quantity": R,
137
+ "accumulation_period": "MONTH",
138
+ "overage_recognition": "PER_SEGMENT",
139
+ "rollover": {"policy": "NONE"},
140
+ }
141
+ ],
142
+ schedules=[_schedule("overage_rate", "unit")],
143
+ ),
144
+ _scenario("units", "unit"),
145
+ {
146
+ "/engagement/arrangement_versions/0/components/0/fixed_amount": "100000",
147
+ "/engagement/arrangement_versions/0/entitlements/0/included_quantity": "1000",
148
+ "/engagement/arrangement_versions/0/rate_schedules/0/tiers/0/rate": "120",
149
+ "/scenario/assumptions/0/value": "12000",
150
+ },
151
+ )
152
+ t["base_plus_overage"] = _template(
153
+ "base_plus_overage",
154
+ "Base fee with an annual included allowance and overage recognized as consumption crosses the allowance.",
155
+ _base(
156
+ "TEMPLATE-BASE-OVERAGE",
157
+ "unit",
158
+ [
159
+ _comp("base", "FIXED_RECURRING", "FIXED", "ANNUAL", fixed_amount=R),
160
+ _comp(
161
+ "overage",
162
+ "ALLOWANCE_OVERAGE",
163
+ "OUTPUT",
164
+ "MONTHLY",
165
+ quantity_source="scenario.units",
166
+ unit="unit",
167
+ entitlement_id="allowance",
168
+ rate_schedule_id="overage_rate",
169
+ depends_on=["allowance"],
170
+ ),
171
+ ],
172
+ entitlements=[
173
+ {
174
+ "id": "allowance",
175
+ "granted_by": "base",
176
+ "unit": "unit",
177
+ "included_quantity": R,
178
+ "accumulation_period": "YEAR",
179
+ "overage_recognition": "CUMULATIVE",
180
+ "rollover": {"policy": "NONE"},
181
+ }
182
+ ],
183
+ schedules=[_schedule("overage_rate", "unit")],
184
+ ),
185
+ _scenario("units", "unit"),
186
+ {
187
+ "/engagement/arrangement_versions/0/components/0/fixed_amount": "1200000",
188
+ "/engagement/arrangement_versions/0/entitlements/0/included_quantity": "12000",
189
+ "/engagement/arrangement_versions/0/rate_schedules/0/tiers/0/rate": "120",
190
+ "/scenario/assumptions/0/value": "10000",
191
+ },
192
+ )
193
+ t["dedicated_team"] = _template(
194
+ "dedicated_team",
195
+ "Dedicated team priced per FTE per month; client effective price depends on utilization.",
196
+ _base(
197
+ "TEMPLATE-DEDICATED",
198
+ "fte_month",
199
+ [
200
+ _comp(
201
+ "team",
202
+ "DEDICATED_RESOURCE",
203
+ "RESOURCE",
204
+ "MONTHLY",
205
+ resources=[{"role": R, "fte": R, "rate_per_fte_month": R}],
206
+ )
207
+ ],
208
+ ),
209
+ {
210
+ "id": "base",
211
+ "assumptions": [
212
+ {"name": "hours_used", "value": R, "unit": "hours", "time_period": R, "origin": R}
213
+ ],
214
+ },
215
+ {
216
+ "/engagement/arrangement_versions/0/components/0/resources/0/role": "analyst",
217
+ "/engagement/arrangement_versions/0/components/0/resources/0/fte": "8",
218
+ "/engagement/arrangement_versions/0/components/0/resources/0/rate_per_fte_month": "16000",
219
+ "/scenario/assumptions/0/value": "10240",
220
+ },
221
+ )
222
+ t["dedicated_team"]["engagement"]["unit_definitions"][0]["kind"] = "FTE_MONTHS"
223
+ t["fixed_project"] = _template(
224
+ "fixed_project",
225
+ "Fixed project fee paid on a schedule; the provider bears effort and overrun risk inside the defined scope.",
226
+ _base(
227
+ "TEMPLATE-FIXED-PROJECT",
228
+ "project",
229
+ [
230
+ _comp(
231
+ "project",
232
+ "FIXED_PROJECT",
233
+ "FIXED",
234
+ "EVENT",
235
+ project_fee=R,
236
+ payment_schedule=[{"month": R, "amount": R}],
237
+ )
238
+ ],
239
+ ),
240
+ {
241
+ "id": "base",
242
+ "assumptions": [
243
+ {
244
+ "name": "delivery_hours",
245
+ "value": R,
246
+ "unit": "hours",
247
+ "time_period": R,
248
+ "origin": R,
249
+ }
250
+ ],
251
+ },
252
+ {
253
+ "/engagement/arrangement_versions/0/components/0/project_fee": "900000",
254
+ "/engagement/arrangement_versions/0/components/0/payment_schedule/0/month": "2027-06",
255
+ "/engagement/arrangement_versions/0/components/0/payment_schedule/0/amount": "900000",
256
+ "/scenario/assumptions/0/value": "6000",
257
+ },
258
+ )
259
+ t["time_and_materials"] = _template(
260
+ "time_and_materials",
261
+ "Hourly rates by role; the client bears duration and productivity risk.",
262
+ _base(
263
+ "TEMPLATE-TM",
264
+ "hour",
265
+ [
266
+ _comp(
267
+ "time",
268
+ "TIME",
269
+ "TIME",
270
+ "MONTHLY",
271
+ quantity_source="scenario.hours",
272
+ role_rates=[{"role": "consultant", "rate": R}],
273
+ )
274
+ ],
275
+ ),
276
+ {
277
+ "id": "base",
278
+ "assumptions": [
279
+ {
280
+ "name": "hours.consultant",
281
+ "value": R,
282
+ "unit": "hours",
283
+ "time_period": R,
284
+ "origin": R,
285
+ }
286
+ ],
287
+ },
288
+ {
289
+ "/engagement/arrangement_versions/0/components/0/role_rates/0/rate": "250",
290
+ "/scenario/assumptions/0/value": "2000",
291
+ },
292
+ )
293
+ t["time_and_materials"]["engagement"]["unit_definitions"][0]["kind"] = "HOURS"
294
+ return t
295
+
296
+
297
+ TEMPLATES = _all()
298
+
299
+
300
+ def list_templates() -> list[dict]:
301
+ return [
302
+ {"template_id": k, "description": v["description"], "source": "core"}
303
+ for k, v in TEMPLATES.items()
304
+ ]
305
+
306
+
307
+ def get_template(template_id: str, pack: str | None = None) -> dict:
308
+ if pack:
309
+ from .packs import load_pack
310
+
311
+ p = load_pack(pack)
312
+ if template_id not in p.templates:
313
+ raise KeyError(
314
+ f"pack {pack} has no template {template_id!r}; templates: {sorted(p.templates)}"
315
+ )
316
+ return copy.deepcopy(p.templates[template_id])
317
+ if template_id not in TEMPLATES:
318
+ raise KeyError(f"no template {template_id!r}; templates: {sorted(TEMPLATES)}")
319
+ return copy.deepcopy(TEMPLATES[template_id])
320
+
321
+
322
+ def fill_template(template: dict, values: dict[str, str]) -> dict:
323
+ """Apply pointer -> value fills to a template's engagement and scenario."""
324
+ doc = {
325
+ "engagement": copy.deepcopy(template["engagement"]),
326
+ "scenario": copy.deepcopy(template["scenario"]),
327
+ }
328
+ for ptr, value in values.items():
329
+ parts = ptr.lstrip("/").split("/")
330
+ cur = doc
331
+ for p in parts[:-1]:
332
+ cur = cur[int(p)] if isinstance(cur, list) else cur[p]
333
+ last = parts[-1]
334
+ if isinstance(cur, list):
335
+ cur[int(last)] = value
336
+ else:
337
+ cur[last] = value
338
+ return doc
cometric/core/tiers.py ADDED
@@ -0,0 +1,78 @@
1
+ """Tiered rate evaluation and ALL_UNITS cliff detection (spec 4.2)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from decimal import Decimal
6
+ from typing import Protocol
7
+
8
+ from .enums import TierMethod
9
+ from .money import ZERO
10
+
11
+
12
+ class TierLike(Protocol):
13
+ from_: Decimal
14
+ to: Decimal | None
15
+ rate: Decimal
16
+
17
+
18
+ def check_contiguous(tiers: list[TierLike]) -> list[str]:
19
+ """Return problems with a tier list: must start at 0, be contiguous, end open-ended."""
20
+ problems = []
21
+ if not tiers:
22
+ return ["schedule has no tiers"]
23
+ if tiers[0].from_ != 0:
24
+ problems.append("first tier must start at 0")
25
+ for i, t in enumerate(tiers):
26
+ if t.to is not None and t.to <= t.from_:
27
+ problems.append(f"tier {i} has to <= from")
28
+ if t.rate < 0:
29
+ problems.append(f"tier {i} has a negative rate")
30
+ if i + 1 < len(tiers):
31
+ if t.to is None:
32
+ problems.append(f"tier {i} is open-ended but is not the last tier")
33
+ elif tiers[i + 1].from_ != t.to:
34
+ problems.append(f"tier {i + 1} does not start where tier {i} ends")
35
+ if tiers[-1].to is not None:
36
+ problems.append("last tier must be open-ended (to = null)")
37
+ return problems
38
+
39
+
40
+ def price(quantity: Decimal, tiers: list[TierLike], method: TierMethod) -> Decimal:
41
+ """Total price for `quantity` units under the schedule."""
42
+ if quantity <= 0:
43
+ return ZERO
44
+ if method == TierMethod.ALL_UNITS:
45
+ for t in tiers:
46
+ if quantity >= t.from_ and (t.to is None or quantity < t.to):
47
+ return quantity * t.rate
48
+ return quantity * tiers[-1].rate
49
+ total = ZERO
50
+ for t in tiers:
51
+ upper = quantity if t.to is None else min(quantity, t.to)
52
+ if upper > t.from_:
53
+ total += (upper - t.from_) * t.rate
54
+ return total
55
+
56
+
57
+ def incremental(
58
+ before: Decimal, quantity: Decimal, tiers: list[TierLike], method: TierMethod
59
+ ) -> Decimal:
60
+ """Price of `quantity` more units given `before` already counted in the accumulation period."""
61
+ return price(before + quantity, tiers, method) - price(before, tiers, method)
62
+
63
+
64
+ def all_units_cliffs(tiers: list[TierLike]) -> list[dict]:
65
+ """Quantities that cost more than the next threshold under ALL_UNITS (W-TIER-CLIFF)."""
66
+ cliffs = []
67
+ for prev, cur in zip(tiers, tiers[1:], strict=False):
68
+ if cur.rate < prev.rate and prev.rate > 0:
69
+ threshold = cur.from_
70
+ lower = threshold * cur.rate / prev.rate
71
+ cliffs.append(
72
+ {
73
+ "threshold": threshold,
74
+ "band_lower_exclusive": lower,
75
+ "band_upper_exclusive": threshold,
76
+ }
77
+ )
78
+ return cliffs