@fantastic.dev/better-stripe 0.94.0 → 0.95.1

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 (89) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts +6 -0
  4. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/internal/operationJournal.js +10 -0
  6. package/dist/client/billing/renewalAttach/internal/operationJournal.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +5 -0
  8. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +40 -0
  10. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts +13 -0
  12. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js +43 -0
  14. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js.map +1 -0
  15. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts +32 -0
  16. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js +102 -0
  18. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js.map +1 -0
  19. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.d.ts +3 -0
  20. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.js +59 -0
  22. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.js.map +1 -0
  23. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.d.ts +11 -0
  24. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.js +132 -0
  26. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.js.map +1 -0
  27. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts +6 -0
  28. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js +16 -0
  30. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js.map +1 -0
  31. package/dist/client/billing/renewalObservation/evidence-invoice-lines.d.ts +27 -0
  32. package/dist/client/billing/renewalObservation/evidence-invoice-lines.d.ts.map +1 -0
  33. package/dist/client/billing/renewalObservation/evidence-invoice-lines.js +164 -0
  34. package/dist/client/billing/renewalObservation/evidence-invoice-lines.js.map +1 -0
  35. package/dist/client/billing/renewalObservation/evidence-invoice.d.ts +4 -0
  36. package/dist/client/billing/renewalObservation/evidence-invoice.d.ts.map +1 -0
  37. package/dist/client/billing/renewalObservation/evidence-invoice.js +190 -0
  38. package/dist/client/billing/renewalObservation/evidence-invoice.js.map +1 -0
  39. package/dist/client/billing/renewalObservation/evidence-material.d.ts +26 -0
  40. package/dist/client/billing/renewalObservation/evidence-material.d.ts.map +1 -0
  41. package/dist/client/billing/renewalObservation/evidence-material.js +253 -0
  42. package/dist/client/billing/renewalObservation/evidence-material.js.map +1 -0
  43. package/dist/client/billing/renewalObservation/evidence-v1-types.d.ts +156 -0
  44. package/dist/client/billing/renewalObservation/evidence-v1-types.d.ts.map +1 -0
  45. package/dist/client/billing/renewalObservation/evidence-v1-types.js +2 -0
  46. package/dist/client/billing/renewalObservation/evidence-v1-types.js.map +1 -0
  47. package/dist/client/billing/renewalObservation/evidence-v1.d.ts +4 -0
  48. package/dist/client/billing/renewalObservation/evidence-v1.d.ts.map +1 -0
  49. package/dist/client/billing/renewalObservation/evidence-v1.js +263 -0
  50. package/dist/client/billing/renewalObservation/evidence-v1.js.map +1 -0
  51. package/dist/client/billing/renewalObservation/terminal-evidence.d.ts +17 -0
  52. package/dist/client/billing/renewalObservation/terminal-evidence.d.ts.map +1 -0
  53. package/dist/client/billing/renewalObservation/terminal-evidence.js +289 -0
  54. package/dist/client/billing/renewalObservation/terminal-evidence.js.map +1 -0
  55. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  56. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  57. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  58. package/dist/component/balanceFunding/queries.d.ts +1 -1
  59. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  60. package/dist/component/earnings/triggers.d.ts +16 -16
  61. package/dist/component/payoutRelease/queries.d.ts +2 -2
  62. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  63. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  64. package/docs/renewal-context-reads.md +28 -0
  65. package/docs/renewal-material-observation.md +50 -0
  66. package/package.json +1 -1
  67. package/src/client/billing/renewalAttach/internal/operationJournal.ts +12 -0
  68. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +59 -0
  69. package/src/client/billing/renewalAttach/internal/producer/invocationProducer.ts +58 -0
  70. package/src/client/billing/renewalAttach/internal/producer/lineageAuthority.ts +158 -0
  71. package/src/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.ts +54 -0
  72. package/src/client/billing/renewalAttach/internal/producer/ownerFactory.ts +136 -0
  73. package/src/client/billing/renewalAttach/internal/producer/producerClock.integration.test.ts +175 -0
  74. package/src/client/billing/renewalAttach/internal/producer/producerOwner.integration.test.ts +449 -0
  75. package/src/client/billing/renewalAttach/internal/producer/stockDelegateFactory.ts +23 -0
  76. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialDeclarations.ts +5 -0
  77. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +142 -0
  78. package/src/client/billing/renewalObservation/evidence-admission.test.ts +219 -0
  79. package/src/client/billing/renewalObservation/evidence-history.test.ts +187 -0
  80. package/src/client/billing/renewalObservation/evidence-invoice-controls.test.ts +293 -0
  81. package/src/client/billing/renewalObservation/evidence-invoice-lines.ts +238 -0
  82. package/src/client/billing/renewalObservation/evidence-invoice.test.ts +177 -0
  83. package/src/client/billing/renewalObservation/evidence-invoice.ts +271 -0
  84. package/src/client/billing/renewalObservation/evidence-material.test.ts +289 -0
  85. package/src/client/billing/renewalObservation/evidence-material.ts +313 -0
  86. package/src/client/billing/renewalObservation/evidence-v1-types.ts +186 -0
  87. package/src/client/billing/renewalObservation/evidence-v1.test.ts +371 -0
  88. package/src/client/billing/renewalObservation/evidence-v1.ts +286 -0
  89. package/src/client/billing/renewalObservation/terminal-evidence.ts +379 -0
@@ -0,0 +1,289 @@
1
+ import assert from "node:assert/strict";
2
+ import { afterEach, expect, it, vi } from "vitest";
3
+ import { observationInput } from "../../../../tests/renewalObservation/fixtures.js";
4
+ import {
5
+ recipe,
6
+ identity,
7
+ evidence,
8
+ activeLifecycle,
9
+ facts,
10
+ complete,
11
+ completionLifecycle,
12
+ prerequisites,
13
+ suppliedC9,
14
+ bounded,
15
+ set,
16
+ } from "../../../../tests/renewalObservation/evidenceFixtures.js";
17
+ import { object, array, get, Stop } from "./common.js";
18
+ import { inspectRenewalEvidenceV1 } from "./evidence-v1.js";
19
+ import type {
20
+ CurrentMaterialV1,
21
+ LifecycleV1,
22
+ RenewalEvidenceResultV1,
23
+ } from "./evidence-v1-types.js";
24
+
25
+ afterEach(() => vi.unstubAllGlobals());
26
+ const currentCases = [
27
+ "attached",
28
+ "pending",
29
+ "active",
30
+ "foreign-sub",
31
+ "duplicate-items",
32
+ "default-drift",
33
+ "native-period-drift",
34
+ "cancel-reset",
35
+ ] as const;
36
+ it.each(currentCases)(
37
+ "private evidence current material %s",
38
+ async (control) => {
39
+ const mode =
40
+ control === "attached" || control === "pending" ? control : "active";
41
+ const h = recipe(mode);
42
+ const sub = object(h.input.reads.subscription),
43
+ schedule = object(h.input.reads.schedule);
44
+ const item = object(array(get(sub, "items").data)[0]);
45
+ if (control === "foreign-sub") set(sub, "id", "sub_foreign");
46
+ if (control === "duplicate-items") {
47
+ const extra = structuredClone(item);
48
+ set(extra, "id", "si_duplicate");
49
+ set(get(sub, "items"), "data", [item, extra]);
50
+ }
51
+ if (control === "default-drift")
52
+ set(
53
+ get(schedule, "default_settings"),
54
+ "description",
55
+ "TEST_DECLARED_DRIFT",
56
+ );
57
+ if (control === "native-period-drift")
58
+ set(item, "current_period_end", Number(item.current_period_end) + 1);
59
+ if (control === "cancel-reset")
60
+ set(sub, "cancel_at", identity(h.input).targetBoundary);
61
+ const lifecycle: LifecycleV1 =
62
+ control === "foreign-sub"
63
+ ? {
64
+ predicate: "conflict",
65
+ providerStatus: "active",
66
+ facts: facts(h.input),
67
+ completion: null,
68
+ reason: "owned_identity_mismatch",
69
+ }
70
+ : activeLifecycle;
71
+ let current: CurrentMaterialV1;
72
+ if (control === "attached" || control === "pending")
73
+ current = {
74
+ predicate:
75
+ control === "attached"
76
+ ? "attached_unconfigured_match"
77
+ : "pending_material_match",
78
+ observedItemId: null,
79
+ nativePeriod: null,
80
+ reason: null,
81
+ };
82
+ else if (control === "active")
83
+ current = {
84
+ predicate: "current_target_material_match",
85
+ observedItemId: "si_successor",
86
+ nativePeriod: {
87
+ start: identity(h.input).targetBoundary,
88
+ end: Number(object(array(schedule.phases)[1]).end_date),
89
+ },
90
+ reason: null,
91
+ };
92
+ else if (control === "foreign-sub")
93
+ current = {
94
+ predicate: "conflict",
95
+ observedItemId: null,
96
+ nativePeriod: null,
97
+ reason: "owned_identity_mismatch",
98
+ };
99
+ else if (control === "duplicate-items" || control === "native-period-drift")
100
+ current = {
101
+ predicate: "unknown",
102
+ observedItemId: null,
103
+ nativePeriod: null,
104
+ reason:
105
+ control === "duplicate-items"
106
+ ? "ambiguous_items"
107
+ : "incomplete_material",
108
+ };
109
+ else
110
+ current = {
111
+ predicate: "conflict",
112
+ observedItemId: null,
113
+ nativePeriod: null,
114
+ reason: "material_mismatch",
115
+ };
116
+ const expected = evidence(h.input, lifecycle, current);
117
+ let fetchCalls = 0;
118
+ vi.stubGlobal("fetch", () => {
119
+ fetchCalls++;
120
+ throw Error("UNEXPECTED_FETCH");
121
+ });
122
+ await prerequisites(h);
123
+ const before = bounded(h.input);
124
+ let targetFailed = false;
125
+ try {
126
+ const actual = await inspectRenewalEvidenceV1(h.input);
127
+ expect(actual).toEqual(expected);
128
+ expect(Reflect.ownKeys(actual)).toHaveLength(12);
129
+ } catch (error) {
130
+ targetFailed = true;
131
+ throw error;
132
+ } finally {
133
+ try {
134
+ expect(h.input).toEqual(before);
135
+ expect(fetchCalls).toBe(0);
136
+ console.info(
137
+ "EVIDENCE_CURRENT_SETTLEMENT",
138
+ JSON.stringify({
139
+ control,
140
+ targetReached: true,
141
+ inputUnchanged: true,
142
+ fetchCalls,
143
+ }),
144
+ );
145
+ } catch (error) {
146
+ if (!targetFailed) throw error;
147
+ console.info("EVIDENCE_MATERIAL_INSPECTION_FAILED");
148
+ }
149
+ }
150
+ },
151
+ );
152
+
153
+ const c9Cases = [
154
+ "completed",
155
+ "pending",
156
+ "default-drift",
157
+ "arbitrary-weekly-end",
158
+ "repeated-configuration",
159
+ "incomplete-history",
160
+ ] as const;
161
+ it.each(c9Cases)("private evidence supplied C9 %s", async (control) => {
162
+ const h = recipe(control === "pending" ? "pending" : "active");
163
+ // Actual retained response recipe stays active/original-stage. Never rewrite a
164
+ // terminal read to manufacture active historical proof.
165
+ const snapshot = structuredClone(
166
+ observationInput(false, true).reads.schedule,
167
+ );
168
+ const c9Configuration = structuredClone(h.input.configuration);
169
+ if (control !== "pending") complete(h.input);
170
+ if (control === "default-drift") {
171
+ set(snapshot.default_settings, "description", "TEST_DECLARED_C9_DRIFT");
172
+ set(
173
+ get(object(h.input.reads.schedule), "default_settings"),
174
+ "description",
175
+ "TEST_DECLARED_C9_DRIFT",
176
+ );
177
+ }
178
+ if (control === "arbitrary-weekly-end") {
179
+ const wrongEnd = snapshot.phases[1].end_date + 86400;
180
+ set(snapshot.phases[1], "end_date", wrongEnd);
181
+ set(
182
+ object(array(object(h.input.reads.schedule).phases)[1]),
183
+ "end_date",
184
+ wrongEnd,
185
+ );
186
+ set(object(h.input.reads.schedule), "completed_at", wrongEnd + 60);
187
+ }
188
+ if (control === "repeated-configuration")
189
+ set(
190
+ c9Configuration,
191
+ "configureKey",
192
+ "TEST_DIFFERENT_COMPLETE_CONFIGURE_KEY",
193
+ );
194
+ if (control === "incomplete-history")
195
+ set(snapshot, "phases", [snapshot.phases[0]]);
196
+ let lifecycle: LifecycleV1;
197
+ if (control === "pending") lifecycle = activeLifecycle;
198
+ else if (control === "completed") lifecycle = completionLifecycle(h.input);
199
+ else
200
+ lifecycle = {
201
+ predicate:
202
+ control === "default-drift" || control === "repeated-configuration"
203
+ ? "conflict"
204
+ : "unknown",
205
+ providerStatus: "completed",
206
+ facts: facts(h.input),
207
+ completion: null,
208
+ reason:
209
+ control === "default-drift" || control === "repeated-configuration"
210
+ ? "material_mismatch"
211
+ : "terminal_completion_unproven",
212
+ };
213
+ const expected: RenewalEvidenceResultV1 = evidence(
214
+ h.input,
215
+ lifecycle,
216
+ control === "pending"
217
+ ? {
218
+ predicate: "pending_material_match",
219
+ observedItemId: null,
220
+ nativePeriod: null,
221
+ reason: null,
222
+ }
223
+ : {
224
+ predicate: "unknown",
225
+ observedItemId: null,
226
+ nativePeriod: null,
227
+ reason: "terminal_completion_unproven",
228
+ },
229
+ );
230
+ let fetchCalls = 0;
231
+ vi.stubGlobal("fetch", () => {
232
+ fetchCalls++;
233
+ throw Error("UNEXPECTED_FETCH");
234
+ });
235
+ await prerequisites(h);
236
+ const proof = await suppliedC9(h, snapshot, c9Configuration);
237
+ if (control === "default-drift") {
238
+ expect(proof.baseline).toBeNull();
239
+ expect(proof.baselineError).toBeInstanceOf(Stop);
240
+ assert(proof.baselineError instanceof Stop);
241
+ expect(proof.baselineError.reason).toBe("full_phase_or_default_read_drift");
242
+ } else if (control === "incomplete-history") {
243
+ expect(proof.baselineError).toBeUndefined();
244
+ expect(proof.baseline?.predicate).toBe("attached_unconfigured_match");
245
+ } else {
246
+ expect(proof.baselineError).toBeUndefined();
247
+ expect(proof.baseline?.predicate).toBe(
248
+ "configured_baseline_material_match",
249
+ );
250
+ expect(proof.baseline?.proofStage).toBe("original");
251
+ expect(proof.baseline?.proofTargetEnd).toBe(snapshot.phases[1].end_date);
252
+ expect(proof.baseline?.comparableSchedule).toBeDefined();
253
+ }
254
+ if (control === "arbitrary-weekly-end") {
255
+ // Existing C9/baseline can agree on an arbitrary end. It is a prerequisite,
256
+ // not an actual proof of the requested native UTC-week duration.
257
+ expect(snapshot.phases[1].end_date).not.toBe(
258
+ identity(h.input).targetBoundary + 604800,
259
+ );
260
+ }
261
+ const before = bounded(h.input);
262
+ let targetFailed = false;
263
+ try {
264
+ const actual = await inspectRenewalEvidenceV1(h.input);
265
+ expect(actual).toEqual(expected);
266
+ expect(Reflect.ownKeys(actual)).toHaveLength(12);
267
+ } catch (error) {
268
+ targetFailed = true;
269
+ throw error;
270
+ } finally {
271
+ try {
272
+ expect(h.input).toEqual(before);
273
+ expect(fetchCalls).toBe(0);
274
+ console.info(
275
+ "EVIDENCE_C9_SETTLEMENT",
276
+ JSON.stringify({
277
+ control,
278
+ targetReached: true,
279
+ baseline: proof.baseline?.predicate ?? "threw",
280
+ inputUnchanged: true,
281
+ fetchCalls,
282
+ }),
283
+ );
284
+ } catch (error) {
285
+ if (!targetFailed) throw error;
286
+ console.info("EVIDENCE_MATERIAL_INSPECTION_FAILED");
287
+ }
288
+ }
289
+ });
@@ -0,0 +1,313 @@
1
+ import type {
2
+ CurrentMaterialV1,
3
+ HistoricalMaterialV1,
4
+ Reason,
5
+ } from "./evidence-v1-types.js";
6
+ import {
7
+ constructRenewalConfigurationReceiptV2,
8
+ reconstructConfigurationV2,
9
+ type ProjectRenewalConfigurationV2Options,
10
+ type ConstructRenewalConfigurationReceiptV2Options,
11
+ } from "../renewalV2/index.js";
12
+ import {
13
+ inspectRenewalScheduleMaterialV2,
14
+ type InspectRenewalScheduleMaterialV2Options,
15
+ } from "../renewalV2/observation.js";
16
+ import { captureObservation } from "../renewalV2/observationInput.js";
17
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
18
+ import { inspectInvoiceEvidenceV1 } from "./evidence-invoice.js";
19
+ import { createContext } from "./scheduled-context.js";
20
+ import { runStages } from "./stage-runner.js";
21
+ import { weeklyPending } from "./weeklyPending.js";
22
+ import { object, array, get, equal, Stop } from "./common.js";
23
+
24
+ /** Unsigned configuration consistency, never an acknowledgement capability. */
25
+ export type ConfiguredEvidenceV1 =
26
+ | { predicate: "absent" }
27
+ | {
28
+ predicate: "qualified";
29
+ snapshot: Record<string, unknown>;
30
+ targetEnd: number;
31
+ }
32
+ | { predicate: "unknown" | "conflict"; reason: Reason };
33
+
34
+ /** A request-bound C9 hash alone does not validate response material or duration. */
35
+ export async function inspectConfiguredEvidenceV1(input: {
36
+ configuration: ProjectRenewalConfigurationV2Options;
37
+ configureReceipt: ConstructRenewalConfigurationReceiptV2Options | null;
38
+ owned: Parameters<typeof createContext>[0];
39
+ }): Promise<ConfiguredEvidenceV1> {
40
+ if (input.configureReceipt === null) return { predicate: "absent" };
41
+ try {
42
+ if (!equal(input.configureReceipt.configuration, input.configuration))
43
+ return { predicate: "conflict", reason: "material_mismatch" };
44
+ const receipt = await constructRenewalConfigurationReceiptV2(
45
+ input.configureReceipt,
46
+ );
47
+ const originalSub = get(
48
+ get(object(input.owned.prepared), "providerSnapshot"),
49
+ "subscription",
50
+ );
51
+ const originalItem = object(array(get(originalSub, "items").data)[0]);
52
+ const coupons = new Map<string, Record<string, unknown>>();
53
+ for (const raw of [
54
+ ...array(originalSub.discounts),
55
+ ...array(originalItem.discounts),
56
+ ]) {
57
+ const coupon = get(get(object(raw), "source"), "coupon");
58
+ if (
59
+ typeof coupon.id !== "string" ||
60
+ (coupons.has(coupon.id) && !equal(coupons.get(coupon.id), coupon))
61
+ )
62
+ return { predicate: "unknown", reason: "terminal_completion_unproven" };
63
+ coupons.set(coupon.id, coupon);
64
+ }
65
+ const historical = {
66
+ schedule: receipt.providerSnapshot,
67
+ subscription: input.configuration.freshSubscription,
68
+ targetPrice: input.configuration.targetPrice,
69
+ billingCustomer: input.configuration.billingCustomer,
70
+ coupons: [...coupons.values()],
71
+ };
72
+ const context = createContext(input.owned, historical, "baseline");
73
+ const proof = runStages(context);
74
+ if (
75
+ proof.predicate !== "configured_baseline_material_match" ||
76
+ typeof proof.proofTargetEnd !== "number" ||
77
+ !Number.isSafeInteger(proof.proofTargetEnd) ||
78
+ !proof.proofStage ||
79
+ !proof.comparableSchedule
80
+ )
81
+ return { predicate: "unknown", reason: "terminal_completion_unproven" };
82
+ const phases = array(receipt.providerSnapshot.phases);
83
+ if (phases.length !== 2)
84
+ return { predicate: "unknown", reason: "terminal_completion_unproven" };
85
+ const targetPhase = object(phases[1]);
86
+ // Baseline comparison can retain the same arbitrary end in both views.
87
+ // Independently require the maintained requested native-duration predicate.
88
+ // Unproven calendar profiles remain unknown; do not invent month arithmetic.
89
+ if (
90
+ !weeklyPending({
91
+ desired: object(input.owned.request),
92
+ originalSub,
93
+ sub: object(historical.subscription),
94
+ expected: context.expected,
95
+ target: object(historical.targetPrice),
96
+ targetPhase,
97
+ schedule: receipt.providerSnapshot,
98
+ phases,
99
+ }) ||
100
+ targetPhase.end_date !== proof.proofTargetEnd
101
+ )
102
+ return { predicate: "unknown", reason: "terminal_completion_unproven" };
103
+ return {
104
+ predicate: "qualified",
105
+ snapshot: receipt.providerSnapshot,
106
+ targetEnd: proof.proofTargetEnd,
107
+ };
108
+ } catch (error) {
109
+ if (error instanceof Stop) {
110
+ if (error.reason === "target_phase_duration_mismatch")
111
+ return { predicate: "unknown", reason: "terminal_completion_unproven" };
112
+ return {
113
+ predicate: error.kind,
114
+ reason:
115
+ error.kind === "conflict"
116
+ ? "material_mismatch"
117
+ : "terminal_completion_unproven",
118
+ };
119
+ }
120
+ return { predicate: "unknown", reason: "incomplete_material" };
121
+ }
122
+ }
123
+
124
+ /** Map the unchanged maintained full current-material comparison into this DTO. */
125
+ export async function inspectCurrentMaterialEvidenceV1(
126
+ input: InspectRenewalScheduleMaterialV2Options,
127
+ invoiceContext: unknown = null,
128
+ ): Promise<CurrentMaterialV1> {
129
+ let comparison = input;
130
+ try {
131
+ const original = object(input.configuration.preparation.subscription);
132
+ const current = object(input.reads.subscription);
133
+ if (!equal(original.latest_invoice, current.latest_invoice)) {
134
+ // Recompute the entire paired proof from this exact raw configuration and
135
+ // read bundle. No caller-supplied proof flag or stored digest can unlock it.
136
+ const proof = await inspectInvoiceEvidenceV1({
137
+ configuration: input.configuration,
138
+ reads: input.reads,
139
+ invoiceContext,
140
+ });
141
+ if (proof.predicate !== "invoice_lines_correlated")
142
+ return {
143
+ predicate: "unknown",
144
+ observedItemId: null,
145
+ nativePeriod: null,
146
+ reason: "incomplete_material",
147
+ };
148
+ const items = array(get(current, "items").data);
149
+ if (items.length !== 1) throw Error("invalid comparison item");
150
+ const item = object(items[0]),
151
+ expected = input.configuration.preparation.expected;
152
+ if (
153
+ proof.original.subscriptionItemId !== expected.itemId ||
154
+ proof.current.subscriptionItemId !== item.id ||
155
+ proof.original.nativePeriod.start !== expected.periodStart ||
156
+ proof.original.nativePeriod.end !== expected.periodEnd ||
157
+ proof.current.nativePeriod.start !== item.current_period_start ||
158
+ proof.current.nativePeriod.end !== item.current_period_end
159
+ )
160
+ throw Error("invalid comparison binding");
161
+ // Explicit comparison view ONLY. Preserve the actual I0/I1 input, source,
162
+ // hashes and every other field; full material validation still follows.
163
+ const reads = renewalSnapshot(input.reads);
164
+ object(reads.subscription).latest_invoice = renewalSnapshot(
165
+ original.latest_invoice,
166
+ );
167
+ comparison = { ...input, reads };
168
+ }
169
+ } catch {
170
+ return {
171
+ predicate: "unknown",
172
+ observedItemId: null,
173
+ nativePeriod: null,
174
+ reason: "incomplete_material",
175
+ };
176
+ }
177
+ const result = await inspectRenewalScheduleMaterialV2(comparison);
178
+ if (
179
+ result.predicate === "current_target_material_match" &&
180
+ result.observedItemId &&
181
+ result.nativePeriod
182
+ )
183
+ return {
184
+ predicate: result.predicate,
185
+ observedItemId: result.observedItemId,
186
+ nativePeriod: result.nativePeriod,
187
+ reason: null,
188
+ };
189
+ if (
190
+ result.predicate === "attached_unconfigured_match" ||
191
+ result.predicate === "pending_material_match"
192
+ )
193
+ return {
194
+ predicate: result.predicate,
195
+ observedItemId: null,
196
+ nativePeriod: null,
197
+ reason: null,
198
+ };
199
+ if (result.predicate === "conflict") {
200
+ const identity =
201
+ result.reason?.includes("identity") ||
202
+ result.reason?.includes("association") ||
203
+ result.reason?.includes("relation_mismatch");
204
+ return {
205
+ predicate: "conflict",
206
+ observedItemId: null,
207
+ nativePeriod: null,
208
+ reason: identity ? "owned_identity_mismatch" : "material_mismatch",
209
+ };
210
+ }
211
+ return {
212
+ predicate: "unknown",
213
+ observedItemId: null,
214
+ nativePeriod: null,
215
+ reason:
216
+ result.reason === "incomplete_or_ambiguous_current_items"
217
+ ? "ambiguous_items"
218
+ : "incomplete_material",
219
+ };
220
+ }
221
+
222
+ /** Complete unsigned snapshot consistency, never proof of an actual past time. */
223
+ export async function inspectHistoricalMaterialEvidenceV1(
224
+ input: unknown,
225
+ ): Promise<HistoricalMaterialV1> {
226
+ const unknown = (reason: Reason): HistoricalMaterialV1 => ({
227
+ predicate: "unknown",
228
+ observedItemId: null,
229
+ nativePeriod: null,
230
+ reason,
231
+ });
232
+ try {
233
+ const root = object(input);
234
+ if (root.historicalSnapshot === null) return unknown("not_supplied");
235
+ const snapshot = object(root.historicalSnapshot);
236
+ if (
237
+ Object.keys(snapshot).length !== 2 ||
238
+ !Object.prototype.hasOwnProperty.call(snapshot, "reads") ||
239
+ !Object.prototype.hasOwnProperty.call(snapshot, "invoiceContext")
240
+ )
241
+ return unknown("incomplete_material");
242
+ const captured = captureObservation({
243
+ configuration: root.configuration,
244
+ reads: snapshot.reads,
245
+ ...(root.configureReceipt === null
246
+ ? {}
247
+ : { configureReceipt: root.configureReceipt }),
248
+ });
249
+ const configuration =
250
+ captured.configuration as ProjectRenewalConfigurationV2Options;
251
+ const reconstruction = await reconstructConfigurationV2(configuration);
252
+ if (!reconstruction.material) return unknown("incomplete_material");
253
+ const configured = await inspectConfiguredEvidenceV1({
254
+ configuration,
255
+ configureReceipt: captured.configureReceipt
256
+ ? (captured.configureReceipt as ConstructRenewalConfigurationReceiptV2Options)
257
+ : null,
258
+ owned: { ...reconstruction.material, request: reconstruction.result },
259
+ });
260
+ if (configured.predicate === "conflict")
261
+ return {
262
+ predicate: "conflict",
263
+ observedItemId: null,
264
+ nativePeriod: null,
265
+ reason: "material_mismatch",
266
+ };
267
+ if (configured.predicate === "unknown")
268
+ return unknown("incomplete_material");
269
+ const current = await inspectCurrentMaterialEvidenceV1(
270
+ {
271
+ configuration,
272
+ reads: {
273
+ schedule: captured.reads.schedule,
274
+ subscription: captured.reads.subscription,
275
+ targetPrice: captured.reads.targetPrice,
276
+ billingCustomer: captured.reads.billingCustomer,
277
+ coupons: captured.reads.coupons,
278
+ },
279
+ ...(captured.configureReceipt
280
+ ? {
281
+ configureReceipt:
282
+ captured.configureReceipt as ConstructRenewalConfigurationReceiptV2Options,
283
+ }
284
+ : {}),
285
+ },
286
+ snapshot.invoiceContext,
287
+ );
288
+ if (current.predicate === "current_target_material_match")
289
+ return {
290
+ predicate: "snapshot_target_material_match",
291
+ observedItemId: current.observedItemId,
292
+ nativePeriod: current.nativePeriod,
293
+ reason: null,
294
+ };
295
+ if (current.predicate === "conflict")
296
+ return {
297
+ predicate: "conflict",
298
+ observedItemId: null,
299
+ nativePeriod: null,
300
+ reason:
301
+ current.reason === "owned_identity_mismatch"
302
+ ? "snapshot_relation_mismatch"
303
+ : "material_mismatch",
304
+ };
305
+ return unknown(
306
+ current.reason === "ambiguous_items"
307
+ ? "ambiguous_items"
308
+ : "incomplete_material",
309
+ );
310
+ } catch {
311
+ return unknown("incomplete_material");
312
+ }
313
+ }