diff --git a/.prettierignore b/.prettierignore index cea134cb0..505ce5541 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,2 +1,4 @@ # Canonical Catalog files must remain byte-identical; hash checked in tests. lib/intelligent-ui/playground/catalog/scenario/vendor/ +# Pinned synthetic API output; preserve exact producer bytes. +lib/intelligent-ui/retained-field/__tests__/fixtures/api-fieldContext.json diff --git a/lib/intelligent-ui/retained-field/README.md b/lib/intelligent-ui/retained-field/README.md new file mode 100644 index 000000000..7b291a227 --- /dev/null +++ b/lib/intelligent-ui/retained-field/README.md @@ -0,0 +1,88 @@ +# Offline retained-field companion consumer + +Source-only prerequisite for App #2207. No chat/history route imports this module; +no live capability is registered. `consumeRetainedField(input)` returns only +`{state:"unavailable"}` by default. The explicit admission object used in tests is +**not an authorization proof**. Its disclosure flag cannot establish a held server +read, current membership, withdrawal state, or permission to display private data. + +The inner companion implements API's +[retained-field contract](https://github.com/recoupable/api/blob/30c4d442c75137fa803802091dbb3991f4646e8b/docs/contracts/catalog-field-consumer-2207.md): +`catalog-retained-field-projection/1`, without `state`. The exact method pins come +from that adopted design contract. No executable retained-field App schema existed +at the base; existing ObjectRef, descriptor, collection, surface, text and indexing +contracts are reused instead of copied. + +## Proposed offline producer handshake + +```ts +import type { Surface } from "../schema"; +import type { FieldContext } from "./schemas"; + +type RetainedFieldPart = { + type: "data-retained-field-snapshot"; + capability: "retained-field-companion/1"; + data: { + surface: Surface; // existing strict schema-v1 surface + fieldContext: FieldContext; // catalog-retained-field-projection/1 without state + }; +}; +``` + +This is a separate, explicitly versioned envelope, not a silent new schema-v1 field. +Legacy parsing still rejects a `fieldContext` property inside a surface. Context's +producer must negotiate this exact envelope and deterministic projection before +integration. It is not a currently accepted chat data part. The reusable executable +example is `__tests__/fixture.ts`; it contains synthetic identities, not an actual +authorized receipt. `projectRetainedField` constructs the exact expected rendering; +consumer rejects any conflicting surface field, answer, row, numeric cell or text. + +The admission captures expected request, surface ID/revision and account/workspace/ +session/chat/message/generation scope. Changing any scope or full selection binding +refuses the complete output. Its `disclosure` status is an injected offline stand-in +for the missing owning server disclosure integration. Before activation, the real +producer and every initial/replay/history/export/model path must obtain current +server-held authorization for the exact Context result/document/source versions. +No local boolean or successful preparation can replace that requirement. + +One current_streams descriptor is indexed per unchanged full ContextObjectRef; +no metric-specific IDs, title inference or parsing display numbers. Query, method, +ordered full binding selection, source versions and reconstructed half-open periods +must agree. Zero stays known zero; unknown has no amount. Descriptor end date is the +last included UTC day; the companion retains both original half-open periods. +Collection population stays partial/page scope with unknown catalog total. Text is +historical and states retrieval is not provider freshness. Companion and all derived +projections are returned together or not at all; there is no fallback or local cache. +Previously returned JavaScript objects cannot be revoked by this pure function. The +owning host must clear them on invalidation; this module makes no erasure claim. + +Normalized inner ready JSON including state is bounded to 32 KiB, full received +part to 256 KiB, and displayed text to 24 KiB UTF-8. Additionally, the complete +App ready result (companion, collection, surface, text and descriptor index entries) +must fit 32 KiB before any output is returned. Index entries are counted explicitly +because ordinary JSON serialization hides Map contents. This conservative App +output limit may refuse an otherwise valid eight-item inner payload; it does not +change the API inner-response contract. Excess is rejected, never truncated. +The consumer stores no controls or working state and performs no external action. +Mutable durable working-surface save/reopen remains separate and incomplete. + +Run focused tests with `pnpm exec vitest run lib/intelligent-ui/retained-field +lib/intelligent-ui/descriptors/__tests__/descriptors.test.ts`. Tests qualify local +shape/binding/projection/refusal only, not API adapter authority, SQL transaction +locking, disclosure, production deployment or native/account acceptance. + +The API-generated synthetic inner payload is copied byte-for-byte into +`__tests__/fixtures/api-fieldContext.json`; `source-pin.json` records API commit +`4ca23de6a6cea3226c2f0392a454eb57861aedf8`, original path and SHA-256. +`producerCompatibility.test.ts` verifies that hash and consumes the payload with +unchanged values, periods, refs and document revision through the proposed outer +envelope. The test derives its expected selection from this synthetic fixture; it +therefore qualifies shape/projection compatibility, **not** independent receipt +origin or authority. Default and unavailable disclosure still withhold all output. + +Coverage validation follows the pinned evaluator/helper: absent and null dates are +disjoint, their sum equals missing dates across the two periods, and a comparable +known value has no gaps. Incomplete comparisons are unknown and have at least one +missing date. Counts cannot exceed the actual two-period length. Retrieval must +end at or before `asOf`, and the current period must have ended by that evaluation +time. These consistency checks do not prove provider freshness or authorization. diff --git a/lib/intelligent-ui/retained-field/__tests__/budgets.test.ts b/lib/intelligent-ui/retained-field/__tests__/budgets.test.ts new file mode 100644 index 000000000..848a8a2e4 --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/budgets.test.ts @@ -0,0 +1,27 @@ +import { expect, it } from "vitest"; +import { fitsRetainedFieldBudget } from "../fitsRetainedFieldBudget"; + +it.each([ + ["part", 256 * 1024], + ["ready", 32 * 1024], + ["text", 24 * 1024], +] as const)( + "enforces exact %s UTF-8 budget without truncation", + (kind, cap) => { + const quotes = kind === "text" ? 0 : 2; + const available = cap - quotes; + const exact = + "界".repeat(Math.floor(available / 3)) + "x".repeat(available % 3); + expect(exact.length).toBeLessThan(cap); + expect(fitsRetainedFieldBudget(kind, exact)).toBe(true); + expect(fitsRetainedFieldBudget(kind, exact + "x")).toBe(false); + expect(fitsRetainedFieldBudget(kind, exact + "界")).toBe(false); + }, +); +it("refuses nonserializable payloads and nontext output", () => { + const cycle: { self?: unknown } = {}; + cycle.self = cycle; + expect(fitsRetainedFieldBudget("part", cycle)).toBe(false); + expect(fitsRetainedFieldBudget("ready", undefined)).toBe(false); + expect(fitsRetainedFieldBudget("text", {})).toBe(false); +}); diff --git a/lib/intelligent-ui/retained-field/__tests__/consumer.test.ts b/lib/intelligent-ui/retained-field/__tests__/consumer.test.ts new file mode 100644 index 000000000..2821cfad3 --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/consumer.test.ts @@ -0,0 +1,461 @@ +import { describe, expect, it } from "vitest"; +import { fitsRetainedFieldBudget } from "../fitsRetainedFieldBudget"; +import { consumeRetainedField } from "../consumeRetainedField"; +import { projectRetainedField } from "../projectRetainedField"; +import { fieldContextSchema } from "../schemas"; +import { surfaceSchema } from "../../schema"; +import { objectRefKey } from "../../descriptors/objectRefKey"; +import { fixture } from "./fixture"; +import { id } from "./id"; +import { resolveSelection } from "../../descriptors/resolveSelection"; + +describe("offline retained field consumer", () => { + it("defaults unavailable and does not extend schema-v1", () => { + const { part } = fixture(); + expect(consumeRetainedField(part)).toEqual({ state: "unavailable" }); + expect( + surfaceSchema.safeParse({ + ...part.data.surface, + fieldContext: part.data.fieldContext, + }).success, + ).toBe(false); + }); + it("roundtrips exact refs, zero/unknown, both periods and deterministic text", () => { + const { part, admission } = fixture(); + const result = consumeRetainedField( + JSON.parse(JSON.stringify(part)), + admission, + ); + expect(result.state).toBe("ready"); + if (result.state !== "ready") throw new Error("Expected fixture admission"); + expect(result.descriptors.size).toBe(2); + expect(result.collection.selection).toEqual( + part.data.fieldContext.items.map((item) => item.ref), + ); + for (const item of part.data.fieldContext.items) { + const descriptor = result.descriptors.get(objectRefKey(item.ref)); + expect(descriptor?.ref).toEqual(item.ref); + expect(descriptor?.field.value).toEqual(item.value); + expect(descriptor?.label).toBe(item.binding.subjectId); + } + expect(result.collection.items[0].field.periodEnd).toBe("2026-10-02"); + expect(result.text).toContain("0 streams"); + expect(result.text).toContain("unknown"); + expect(result.text).toContain("Previous period [2026-09-29, 2026-10-01)"); + expect(result.text).toContain("current period [2026-10-01, 2026-10-03)"); + expect(result.text).toContain("not provider freshness"); + expect(result.fieldContext).toEqual(part.data.fieldContext); + expect(result.collection).toMatchObject({ + completeness: "partial", + aggregationScope: "page", + knownTotal: null, + hasMore: false, + nextCursor: null, + }); + expect(result.surface.fallbackText).toBe(result.text); + }); + const mutations: [string, (f: ReturnType) => void][] = [ + [ + "result", + (f) => { + f.part.data.fieldContext.items[0].binding.resultId = id(99); + }, + ], + [ + "request", + (f) => { + f.part.data.fieldContext.items[0].binding.requestId = id(99); + }, + ], + [ + "revision", + (f) => { + f.part.data.fieldContext.items[0].binding.revision++; + }, + ], + [ + "owner", + (f) => { + f.part.data.fieldContext.items[0].binding.ownerId = id(99); + }, + ], + [ + "catalog", + (f) => { + f.part.data.fieldContext.items[0].binding.catalogId = id(99); + }, + ], + [ + "ref-version", + (f) => { + f.part.data.fieldContext.items[0].ref.sourceVersionIds = [id(99)]; + }, + ], + [ + "full-version", + (f) => { + f.part.data.fieldContext.items[0].ref.sourceVersionIds = [id(99)]; + f.part.data.fieldContext.items[0].binding.sourceVersionIds = [id(99)]; + }, + ], + [ + "subject", + (f) => { + f.part.data.fieldContext.items[0].ref.id = id(99); + }, + ], + [ + "order", + (f) => { + f.part.data.fieldContext.items.reverse(); + }, + ], + [ + "duplicate", + (f) => { + f.part.data.fieldContext.items[1] = structuredClone( + f.part.data.fieldContext.items[0], + ); + }, + ], + [ + "query", + (f) => { + f.part.data.fieldContext.query.days = 3; + }, + ], + [ + "previous-period", + (f) => { + f.part.data.fieldContext.items[0].periods.previous.start = "2026-09-28"; + }, + ], + [ + "current-period", + (f) => { + f.part.data.fieldContext.items[0].periods.current.end_exclusive = + "2026-10-04"; + }, + ], + [ + "incomplete-known", + (f) => { + f.part.data.fieldContext.items[0].coverage.comparisonState = + "incomplete"; + }, + ], + [ + "negative-count", + (f) => { + f.part.data.fieldContext.items[0].coverage.nullDateCount = -1; + }, + ], + [ + "negative-value", + (f) => { + f.part.data.fieldContext.items[0].value = { + state: "known", + amount: -1, + }; + }, + ], + [ + "unsafe-value", + (f) => { + f.part.data.fieldContext.items[0].value = { + state: "known", + amount: 2 ** 53, + }; + }, + ], + [ + "retrieval-order", + (f) => { + f.part.data.fieldContext.items[0].source.retrievalRange.earliest = + "2026-10-05T00:00:00Z"; + }, + ], + [ + "text", + (f) => { + f.part.data.surface.fallbackText += " 999999 streams"; + }, + ], + [ + "label", + (f) => { + f.part.data.surface.title = "Current verified values"; + }, + ], + [ + "missing-row", + (f) => { + f.part.data.surface.components = []; + }, + ], + [ + "wrong-surface", + (f) => { + f.admission.surfaceId = "other"; + }, + ], + [ + "surface-revision", + (f) => { + f.admission.surfaceRevision++; + }, + ], + [ + "generation", + (f) => { + f.admission.currentScope.generation++; + }, + ], + [ + "account", + (f) => { + f.admission.currentScope.accountId = id(99); + }, + ], + [ + "workspace", + (f) => { + f.admission.currentScope.workspaceId = id(99); + }, + ], + [ + "session", + (f) => { + f.admission.currentScope.sessionId = id(99); + }, + ], + [ + "chat", + (f) => { + f.admission.currentScope.chatId = id(99); + }, + ], + [ + "message", + (f) => { + f.admission.currentScope.messageId = id(99); + }, + ], + ]; + it.each(mutations)( + "withholds companion AND values/text for %s mismatch", + (_label, mutate) => { + const f = fixture(); + mutate(f); + expect(consumeRetainedField(f.part, f.admission)).toEqual({ + state: "unavailable", + }); + }, + ); + it.each(["unavailable", "error"] as const)( + "does not reuse a prior result on %s disclosure", + (disclosure) => { + const f = fixture(); + expect(consumeRetainedField(f.part, f.admission).state).toBe("ready"); + expect( + consumeRetainedField(f.part, { ...f.admission, disclosure }), + ).toEqual({ state: "unavailable" }); + }, + ); + it("rejects unknown keys at envelope, context, item and method boundaries", () => { + const f = fixture(); + const candidates = [ + { ...f.part, unexpected: true }, + { ...f.part, data: { ...f.part.data, unexpected: true } }, + { + ...f.part, + data: { + ...f.part.data, + fieldContext: { ...f.part.data.fieldContext, state: "ready" }, + }, + }, + { + ...f.part, + data: { + ...f.part.data, + fieldContext: { + ...f.part.data.fieldContext, + method: { + ...f.part.data.fieldContext.method, + url: "https://example.invalid", + }, + }, + }, + }, + { + ...f.part, + data: { + ...f.part.data, + fieldContext: { + ...f.part.data.fieldContext, + items: [ + { ...f.part.data.fieldContext.items[0], rawEvidence: "private" }, + ], + }, + }, + }, + ]; + for (const input of candidates) + expect(consumeRetainedField(input, f.admission)).toEqual({ + state: "unavailable", + }); + }); + it("rejects a changed registered method even when request and response agree", () => { + const f = fixture(); + const method = { + ...f.part.data.fieldContext.method, + evaluatorSha256: "f".repeat(64), + }; + const part = { + ...f.part, + data: { + ...f.part.data, + fieldContext: { ...f.part.data.fieldContext, method }, + }, + }; + expect(consumeRetainedField(f.part, f.admission).state).toBe("ready"); + const admission = { + ...f.admission, + request: { ...f.admission.request, method }, + }; + // The changed literal is intentionally invalid on both sides of this input. + expect(consumeRetainedField(part, admission as typeof f.admission)).toEqual( + { state: "unavailable" }, + ); + }); + it("directly refuses the UTF-8 budget of an oversized part (separate from strict unknown-key rejection)", () => { + const f = fixture(); + const oversized = { ...f.part, padding: "界".repeat(90000) }; + expect(fitsRetainedFieldBudget("part", f.part)).toBe(true); + expect(fitsRetainedFieldBudget("part", oversized)).toBe(false); + expect(consumeRetainedField(oversized, f.admission)).toEqual({ + state: "unavailable", + }); + }); + it("rejects amount attached to unknown, more than eight items and two source versions", () => { + const f = fixture(); + const context = f.part.data.fieldContext; + expect( + fieldContextSchema.safeParse({ + ...context, + items: [ + { ...context.items[0], value: { state: "unknown", amount: 0 } }, + ], + }).success, + ).toBe(false); + expect( + fieldContextSchema.safeParse({ + ...context, + items: Array(9).fill(context.items[0]), + }).success, + ).toBe(false); + expect( + fieldContextSchema.safeParse({ + ...context, + items: [ + { + ...context.items[0], + binding: { + ...context.items[0].binding, + sourceVersionIds: [id(30), id(31)], + }, + }, + ], + }).success, + ).toBe(false); + }); + it("rejects a changed display amount instead of publishing it as a typed value", () => { + const f = fixture(); + const component = f.part.data.surface.components[0]; + if (component.type !== "collection") throw new Error("Expected collection"); + const before = consumeRetainedField(f.part, f.admission); + expect(before.state).toBe("ready"); + if (before.state === "ready") + expect(before.collection.items[0].field.value).toEqual({ + state: "known", + amount: 0, + }); + component.rows[0].values.value = "27 streams"; + expect(consumeRetainedField(f.part, f.admission)).toEqual({ + state: "unavailable", + }); + }); +}); + +it("joins selections by the full Context ref, never subject ID alone", () => { + const f = fixture(); + const result = consumeRetainedField(f.part, f.admission); + if (result.state !== "ready") throw new Error("Expected fixture admission"); + expect( + resolveSelection( + f.admission.request.workspaceId, + result.descriptors, + result.collection.selection, + ), + ).toEqual({ state: "available", items: result.collection.items }); + const changed = { + ...result.collection.selection[0], + sourceVersionIds: [id(99)], + }; + expect( + resolveSelection(f.admission.request.workspaceId, result.descriptors, [ + changed, + ]), + ).toEqual({ state: "unavailable" }); +}); +it("rejects internally consistent but unrequested period and version substitution", () => { + for (const mode of ["period", "version"] as const) { + const f = fixture(); + const context = f.part.data.fieldContext; + if (mode === "period") { + context.query.since = "2026-10-02"; + for (const item of context.items) { + item.periods.previous = { + start: "2026-09-30", + end_exclusive: "2026-10-02", + }; + item.periods.current = { + start: "2026-10-02", + end_exclusive: "2026-10-04", + }; + } + } else { + context.items[0].ref.sourceVersionIds = [id(99)]; + context.items[0].binding.sourceVersionIds = [id(99)]; + } + f.part.data.surface = projectRetainedField( + context, + "retained-1", + 1, + ).surface; + expect(consumeRetainedField(f.part, f.admission)).toEqual({ + state: "unavailable", + }); + } +}); +it("keeps valid leap-day periods and document revision distinct from surface revision", () => { + const f = fixture(); + const context = f.part.data.fieldContext; + context.query = { since: "2024-03-01", days: 1, timezone: "UTC" }; + f.admission.request.query = structuredClone(context.query); + for (const item of context.items) + item.periods = { + previous: { start: "2024-02-29", end_exclusive: "2024-03-01" }, + current: { start: "2024-03-01", end_exclusive: "2024-03-02" }, + days: 1, + timezone: "UTC", + }; + f.part.data.surface = projectRetainedField(context, "retained-1", 7).surface; + f.admission.surfaceRevision = 7; + const result = consumeRetainedField(f.part, f.admission); + expect(result.state).toBe("ready"); + if (result.state === "ready") { + expect(result.fieldContext.items[0].binding.revision).toBe(4); + expect(result.surface.revision).toBe(7); + } +}); diff --git a/lib/intelligent-ui/retained-field/__tests__/coverageTime.test.ts b/lib/intelligent-ui/retained-field/__tests__/coverageTime.test.ts new file mode 100644 index 000000000..521bbdc14 --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/coverageTime.test.ts @@ -0,0 +1,104 @@ +import { expect, it } from "vitest"; +import { fieldContextSchema } from "../schemas"; +import { consumeRetainedField } from "../consumeRetainedField"; +import { projectRetainedField } from "../projectRetainedField"; +import { fixture } from "./fixture"; + +it.each(["not-a-date", "2026-02-30", "", "999999-01-01"])( + "invalid since %s refuses safely without a refinement exception", + (since) => { + const f = fixture(); + f.part.data.fieldContext.query.since = since; + expect(() => + fieldContextSchema.safeParse(f.part.data.fieldContext), + ).not.toThrow(); + expect(fieldContextSchema.safeParse(f.part.data.fieldContext).success).toBe( + false, + ); + expect(consumeRetainedField(f.part, f.admission)).toEqual({ + state: "unavailable", + }); + }, +); +it.each(["absentDateCount", "nullDateCount", "missingDateCount"] as const)( + "bounds %s by the actual two periods", + (key) => { + const f = fixture(); + const item = f.part.data.fieldContext.items[1]; + item.coverage[key] = 5; // Two two-day periods contain four dates, not 732. + expect(fieldContextSchema.safeParse(f.part.data.fieldContext).success).toBe( + false, + ); + expect(consumeRetainedField(f.part, f.admission)).toEqual({ + state: "unavailable", + }); + }, +); +it.each(["known-gap", "incomplete-no-gap", "count-sum"])( + "refuses evaluator-impossible %s coverage", + (mode) => { + const f = fixture(); + const coverage = + f.part.data.fieldContext.items[mode === "known-gap" ? 0 : 1].coverage; + if (mode === "known-gap") { + coverage.absentDateCount = 1; + coverage.missingDateCount = 1; + } + if (mode === "incomplete-no-gap") { + coverage.absentDateCount = 0; + coverage.missingDateCount = 0; + } + if (mode === "count-sum") { + coverage.nullDateCount = 1; + } + expect(fieldContextSchema.safeParse(f.part.data.fieldContext).success).toBe( + false, + ); + expect(consumeRetainedField(f.part, f.admission)).toEqual({ + state: "unavailable", + }); + }, +); +it("rejects retrieval after evaluation and unfinished comparison periods", () => { + for (const asOf of ["2026-10-03T01:59:59Z", "2026-10-02T23:59:59Z"]) { + const f = fixture(); + f.part.data.fieldContext.asOf = asOf; + if (asOf === "2026-10-02T23:59:59Z") { + // Keep retrieval before asOf so only the unfinished period causes refusal. + for (const item of f.part.data.fieldContext.items) { + item.source.retrievalRange = { + earliest: "2026-10-02T01:00:00Z", + latest: "2026-10-02T02:00:00Z", + }; + } + } + expect(fieldContextSchema.safeParse(f.part.data.fieldContext).success).toBe( + false, + ); + expect(consumeRetainedField(f.part, f.admission)).toEqual({ + state: "unavailable", + }); + } +}); +it("accepts evaluator-consistent zero/unknown with boundary counts and retrieval exactly at asOf", () => { + const f = fixture(); + const context = f.part.data.fieldContext; + context.asOf = context.items[0].source.retrievalRange.latest; + context.items[1].coverage = { + comparisonState: "incomplete", + absentDateCount: 3, + nullDateCount: 1, + missingDateCount: 4, + }; + expect(fieldContextSchema.safeParse(context).success).toBe(true); + f.part.data.surface = projectRetainedField(context, "retained-1", 1).surface; + const result = consumeRetainedField(f.part, f.admission); + expect(result.state).toBe("ready"); + if (result.state === "ready") { + expect(result.collection.items.map((item) => item.field.value)).toEqual([ + { state: "known", amount: 0 }, + { state: "unknown" }, + ]); + expect(result.fieldContext.items[1].coverage.missingDateCount).toBe(4); + } +}); diff --git a/lib/intelligent-ui/retained-field/__tests__/fixture.ts b/lib/intelligent-ui/retained-field/__tests__/fixture.ts new file mode 100644 index 000000000..044c2a8a2 --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/fixture.ts @@ -0,0 +1,103 @@ +import type { FieldContext, RetainedFieldRequest } from "../schemas"; +import { projectRetainedField } from "../projectRetainedField"; +import { id } from "./id"; +export function fixture() { + const method = { + recipe: "catalog-retained-stream-fields/1" as const, + recipeHash: + "65a06a785aa496e1232fe3a9f1606595f19c1a152b710ca30c4c06612f01864a" as const, + evaluatorSha256: + "163563e15dd92d473aa51899c54c96300f20d27072b83e39ffb01c84f3adc64e" as const, + helperSha256: + "91dcca66c8dec0851c1f6e110257a63b730e9b7ae33a60bceb0e9ffcf318dd81" as const, + }; + const request: RetainedFieldRequest = { + mode: "retained_field", + workspaceId: id(1), + catalogId: id(2), + field: "current_streams", + method, + query: { since: "2026-10-01", days: 2, timezone: "UTC" }, + selections: [0, 1].map((n) => ({ + ownerId: id(1), + requestId: id(3), + subjectId: id(10 + n), + catalogId: id(2), + resultId: id(20 + n), + revision: 4 + n, + topic: "catalog_retained_streams", + sourceVersionIds: [id(30 + n)], + })), + }; + const fieldContext: FieldContext = { + contract: "catalog-retained-field-projection/1", + workspaceId: request.workspaceId, + catalogId: request.catalogId, + field: request.field, + method, + query: request.query, + asOf: "2026-10-04T00:00:00Z", + semantics: "historical_snapshot", + items: request.selections.map((binding, n) => ({ + ref: { + workspaceId: binding.ownerId, + authority: "context", + kind: "recording", + id: binding.subjectId, + sourceVersionIds: binding.sourceVersionIds, + }, + binding, + value: n ? { state: "unknown" } : { state: "known", amount: 0 }, + periods: { + previous: { start: "2026-09-29", end_exclusive: "2026-10-01" }, + current: { start: "2026-10-01", end_exclusive: "2026-10-03" }, + days: 2, + timezone: "UTC", + }, + coverage: { + comparisonState: n ? "incomplete" : "comparable", + absentDateCount: n, + nullDateCount: 0, + missingDateCount: n, + }, + source: { + provider: "luminate", + metric: "daily_streams", + platform: "all_dsps", + territory: "worldwide", + timezone: "UTC", + retrievalRange: { + earliest: "2026-10-03T01:00:00Z", + latest: "2026-10-03T02:00:00Z", + }, + }, + })), + }; + const scope = { + accountId: id(90), + workspaceId: id(1), + sessionId: id(91), + chatId: id(92), + messageId: id(93), + generation: 1, + }; + return { + part: { + type: "data-retained-field-snapshot" as const, + capability: "retained-field-companion/1" as const, + data: { + fieldContext, + surface: projectRetainedField(fieldContext, "retained-1", 1).surface, + }, + }, + admission: { + capability: "retained-field-companion/1" as const, + disclosure: "available" as const, + capturedScope: { ...scope }, + currentScope: { ...scope }, + surfaceId: "retained-1", + surfaceRevision: 1, + request: structuredClone(request), + }, + }; +} diff --git a/lib/intelligent-ui/retained-field/__tests__/fixtures/api-fieldContext.json b/lib/intelligent-ui/retained-field/__tests__/fixtures/api-fieldContext.json new file mode 100644 index 000000000..c53e71597 --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/fixtures/api-fieldContext.json @@ -0,0 +1,77 @@ +{ + "contract": "catalog-retained-field-projection/1", + "workspaceId": "10000000-0000-4000-8000-000000000001", + "catalogId": "10000000-0000-4000-8000-000000000003", + "field": "current_streams", + "method": { + "recipe": "catalog-retained-stream-fields/1", + "recipeHash": "65a06a785aa496e1232fe3a9f1606595f19c1a152b710ca30c4c06612f01864a", + "evaluatorSha256": "163563e15dd92d473aa51899c54c96300f20d27072b83e39ffb01c84f3adc64e", + "helperSha256": "91dcca66c8dec0851c1f6e110257a63b730e9b7ae33a60bceb0e9ffcf318dd81" + }, + "query": { + "since": "2026-10-24", + "days": 1, + "timezone": "UTC" + }, + "asOf": "2026-10-27T00:00:00Z", + "semantics": "historical_snapshot", + "items": [ + { + "ref": { + "workspaceId": "10000000-0000-4000-8000-000000000001", + "authority": "context", + "kind": "recording", + "id": "10000000-0000-4000-8000-000000000004", + "sourceVersionIds": [ + "10000000-0000-4000-8000-000000000006" + ] + }, + "binding": { + "ownerId": "10000000-0000-4000-8000-000000000001", + "requestId": "10000000-0000-4000-8000-000000000002", + "subjectId": "10000000-0000-4000-8000-000000000004", + "catalogId": "10000000-0000-4000-8000-000000000003", + "resultId": "10000000-0000-4000-8000-000000000005", + "revision": 7, + "topic": "catalog_retained_streams", + "sourceVersionIds": [ + "10000000-0000-4000-8000-000000000006" + ] + }, + "value": { + "state": "known", + "amount": 100 + }, + "periods": { + "previous": { + "start": "2026-10-23", + "end_exclusive": "2026-10-24" + }, + "current": { + "start": "2026-10-24", + "end_exclusive": "2026-10-25" + }, + "days": 1, + "timezone": "UTC" + }, + "coverage": { + "comparisonState": "comparable", + "absentDateCount": 0, + "nullDateCount": 0, + "missingDateCount": 0 + }, + "source": { + "provider": "luminate", + "metric": "daily_streams", + "platform": "all_dsps", + "territory": "worldwide", + "timezone": "UTC", + "retrievalRange": { + "earliest": "2026-10-25T01:00:00Z", + "latest": "2026-10-25T01:00:00Z" + } + } + } + ] +} diff --git a/lib/intelligent-ui/retained-field/__tests__/fixtures/source-pin.json b/lib/intelligent-ui/retained-field/__tests__/fixtures/source-pin.json new file mode 100644 index 000000000..a12d5c891 --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/fixtures/source-pin.json @@ -0,0 +1,7 @@ +{ + "repository": "recoupable/api", + "commit": "4ca23de6a6cea3226c2f0392a454eb57861aedf8", + "path": "scripts/proposals/catalog-retained-selection/fixtures/fieldContext.json", + "sha256": "ed979fc2ea72c3a3e51deb2ba259980f171a550b88fb488afb783a70e02ec322", + "qualification": "Synthetic producer output. Not an authorization receipt or live disclosure proof." +} diff --git a/lib/intelligent-ui/retained-field/__tests__/id.ts b/lib/intelligent-ui/retained-field/__tests__/id.ts new file mode 100644 index 000000000..eda2f393c --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/id.ts @@ -0,0 +1,2 @@ +export const id = (n: number) => + `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`; diff --git a/lib/intelligent-ui/retained-field/__tests__/producerCompatibility.test.ts b/lib/intelligent-ui/retained-field/__tests__/producerCompatibility.test.ts new file mode 100644 index 000000000..e6dacc0a6 --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/producerCompatibility.test.ts @@ -0,0 +1,77 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { expect, it } from "vitest"; +import sourcePin from "./fixtures/source-pin.json"; +import { consumeRetainedField } from "../consumeRetainedField"; +import { projectRetainedField } from "../projectRetainedField"; +import { fieldContextSchema, retainedFieldRequestSchema } from "../schemas"; +import { objectRefKey } from "../../descriptors/objectRefKey"; + +it("consumes pinned API-generated synthetic field context without adapting its identities or amounts", () => { + const bytes = readFileSync( + new URL("./fixtures/api-fieldContext.json", import.meta.url), + ); + expect(createHash("sha256").update(bytes).digest("hex")).toBe( + sourcePin.sha256, + ); + const context = fieldContextSchema.parse(JSON.parse(bytes.toString("utf8"))); + const request = retainedFieldRequestSchema.parse({ + mode: "retained_field", + workspaceId: context.workspaceId, + catalogId: context.catalogId, + field: context.field, + method: context.method, + query: context.query, + selections: context.items.map((item) => item.binding), + }); + // This synthetic expected selection is NOT a receipt-origin or authority test. + const scope = { + accountId: "synthetic-actor", + workspaceId: context.workspaceId, + sessionId: "synthetic-session", + chatId: "synthetic-chat", + messageId: "synthetic-message", + generation: 1, + }; + const part = { + type: "data-retained-field-snapshot", + capability: "retained-field-companion/1", + data: { + fieldContext: context, + surface: projectRetainedField(context, "api-fixture", 3).surface, + }, + }; + expect(consumeRetainedField(part)).toEqual({ state: "unavailable" }); + const admission = { + capability: "retained-field-companion/1" as const, + disclosure: "available" as const, + capturedScope: scope, + currentScope: scope, + surfaceId: "api-fixture", + surfaceRevision: 3, + request, + }; + const result = consumeRetainedField(part, admission); + expect(result.state).toBe("ready"); + if (result.state !== "ready") + throw new Error("Expected synthetic compatible payload"); + expect(result.fieldContext).toEqual(context); + expect( + result.descriptors.get(objectRefKey(context.items[0].ref))?.field.value, + ).toEqual({ state: "known", amount: 100 }); + expect(result.text).toContain("100 streams"); + expect(result.fieldContext.items[0].binding.revision).toBe(7); + expect(result.surface.revision).toBe(3); + expect( + consumeRetainedField(part, { ...admission, disclosure: "unavailable" }), + ).toEqual({ state: "unavailable" }); + expect( + consumeRetainedField(part, { + ...admission, + request: { + ...request, + selections: [{ ...request.selections[0], revision: 8 }], + }, + }), + ).toEqual({ state: "unavailable" }); +}); diff --git a/lib/intelligent-ui/retained-field/__tests__/projectionOrder.test.ts b/lib/intelligent-ui/retained-field/__tests__/projectionOrder.test.ts new file mode 100644 index 000000000..18666df40 --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/projectionOrder.test.ts @@ -0,0 +1,31 @@ +import { expect, it } from "vitest"; +import { consumeRetainedField } from "../consumeRetainedField"; +import { fixture } from "./fixture"; + +it("accepts identical parsed display records regardless of object key insertion order", () => { + const f = fixture(); + expect(consumeRetainedField(f.part, f.admission).state).toBe("ready"); + const collection = f.part.data.surface.components[0]; + if (collection.type !== "collection") throw new Error("Expected collection"); + for (const row of collection.rows) { + row.values = Object.fromEntries(Object.entries(row.values).reverse()); + } + expect(consumeRetainedField(f.part, f.admission).state).toBe("ready"); +}); +it.each(["value", "rows", "columns"])( + "still rejects a changed %s projection", + (mode) => { + const f = fixture(); + const collection = f.part.data.surface.components[0]; + if (collection.type !== "collection") + throw new Error("Expected collection"); + for (const row of collection.rows) + row.values = Object.fromEntries(Object.entries(row.values).reverse()); + if (mode === "value") collection.rows[0].values.value = "1000 streams"; + if (mode === "rows") collection.rows.reverse(); + if (mode === "columns") collection.columns.reverse(); + expect(consumeRetainedField(f.part, f.admission)).toEqual({ + state: "unavailable", + }); + }, +); diff --git a/lib/intelligent-ui/retained-field/__tests__/readyBudget.test.ts b/lib/intelligent-ui/retained-field/__tests__/readyBudget.test.ts new file mode 100644 index 000000000..bc8dc5e04 --- /dev/null +++ b/lib/intelligent-ui/retained-field/__tests__/readyBudget.test.ts @@ -0,0 +1,67 @@ +import { expect, it } from "vitest"; +import { consumeRetainedField } from "../consumeRetainedField"; +import { projectRetainedField } from "../projectRetainedField"; +import { fieldContextSchema } from "../schemas"; +import { fitsRetainedFieldBudget } from "../fitsRetainedFieldBudget"; +import { fixture } from "./fixture"; +import { id } from "./id"; + +it("withholds a valid eight-item projection whose complete ready JSON exceeds 32 KiB", () => { + const f = fixture(); + const context = f.part.data.fieldContext; + const original = structuredClone(context.items[0]); + context.items = Array.from({ length: 8 }, (_, n) => { + const item = structuredClone(original); + item.binding.subjectId = id(100 + n); + item.binding.resultId = id(200 + n); + item.binding.sourceVersionIds = [id(300 + n)]; + item.ref.id = item.binding.subjectId; + item.ref.sourceVersionIds = [...item.binding.sourceVersionIds]; + item.source.retrievalRange.earliest = `2026-10-03T01:00:00.${"0".repeat(40)}Z`; + item.source.retrievalRange.latest = `2026-10-03T02:00:00.${"0".repeat(40)}Z`; + return item; + }); + expect(fieldContextSchema.safeParse(context).success).toBe(true); + f.admission.request.selections = structuredClone( + context.items.map((item) => item.binding), + ); + const projection = projectRetainedField(context, "retained-1", 1); + f.part.data.surface = projection.surface; + expect(fitsRetainedFieldBudget("ready", { state: "ready", ...context })).toBe( + true, + ); + expect(fitsRetainedFieldBudget("part", f.part)).toBe(true); + expect(fitsRetainedFieldBudget("text", projection.text)).toBe(true); + const bytes = new TextEncoder().encode( + JSON.stringify({ state: "ready", fieldContext: context, ...projection }), + ).byteLength; + expect(bytes).toBeGreaterThan(32 * 1024); + expect(consumeRetainedField(f.part, f.admission)).toEqual({ + state: "unavailable", + }); +}); + +it("measures complete ready-shaped objects at exact multibyte JSON boundaries", () => { + const object = { + state: "ready", + fieldContext: {}, + collection: {}, + surface: {}, + text: "", + descriptors: [], + }; + const overhead = new TextEncoder().encode(JSON.stringify(object)).byteLength; + const remaining = 32 * 1024 - overhead; + object.text = + "界".repeat(Math.floor(remaining / 3)) + "x".repeat(remaining % 3); + expect(new TextEncoder().encode(JSON.stringify(object)).byteLength).toBe( + 32 * 1024, + ); + expect(fitsRetainedFieldBudget("ready", object)).toBe(true); + expect( + fitsRetainedFieldBudget("ready", { ...object, text: object.text + "x" }), + ).toBe(false); + expect( + fitsRetainedFieldBudget("ready", { ...object, text: object.text + "界" }), + ).toBe(false); +}); diff --git a/lib/intelligent-ui/retained-field/consumeRetainedField.ts b/lib/intelligent-ui/retained-field/consumeRetainedField.ts new file mode 100644 index 000000000..f66a78eab --- /dev/null +++ b/lib/intelligent-ui/retained-field/consumeRetainedField.ts @@ -0,0 +1,117 @@ +import { z } from "zod"; +import { equalParsedProjection } from "./equalParsedProjection"; +import { surfaceSchema } from "../schema"; +import { identifierSchema, revisionSchema } from "../contractValues"; +import { fitsRetainedFieldBudget } from "./fitsRetainedFieldBudget"; +import { indexDescriptors } from "../descriptors/indexDescriptors"; +import { + fieldContextSchema, + retainedFieldRequestSchema, + type RetainedFieldRequest, +} from "./schemas"; +import { projectRetainedField } from "./projectRetainedField"; + +/** Separate negotiated envelope: never an extension accepted by schema-v1 history. */ +export const retainedFieldPartSchema = z + .object({ + type: z.literal("data-retained-field-snapshot"), + capability: z.literal("retained-field-companion/1"), + data: z + .object({ surface: surfaceSchema, fieldContext: fieldContextSchema }) + .strict(), + }) + .strict(); +const scopeSchema = z + .object({ + accountId: identifierSchema, + workspaceId: identifierSchema, + sessionId: identifierSchema, + chatId: identifierSchema, + messageId: identifierSchema, + generation: revisionSchema, + }) + .strict(); +type Scope = z.infer; +type Admission = { + capability: "retained-field-companion/1"; + /** Supplied by an owning disclosure adapter; this module cannot authorize reads. */ + disclosure: "available" | "unavailable" | "error"; + capturedScope: Scope; + currentScope: Scope; + surfaceId: string; + surfaceRevision: number; + request: RetainedFieldRequest; +}; +/** Offline consumer only. No default capability, network, cached fallback, or live registration. */ +export function consumeRetainedField(input: unknown, admission?: Admission) { + const unavailable = { state: "unavailable" as const }; + if ( + !admission || + admission.capability !== "retained-field-companion/1" || + admission.disclosure !== "available" + ) + return unavailable; + const { capturedScope: captured, currentScope: current } = admission; + if ( + !scopeSchema.safeParse(captured).success || + !scopeSchema.safeParse(current).success || + ![ + "accountId", + "workspaceId", + "sessionId", + "chatId", + "messageId", + "generation", + ].every( + (key) => captured[key as keyof Scope] === current[key as keyof Scope], + ) + ) + return unavailable; + try { + if (!fitsRetainedFieldBudget("part", input)) return unavailable; + const part = retainedFieldPartSchema.parse(input); + const request = retainedFieldRequestSchema.parse(admission.request); + const { surface, fieldContext } = part.data; + if ( + !fitsRetainedFieldBudget("ready", { state: "ready", ...fieldContext }) || + !fitsRetainedFieldBudget("text", surface.fallbackText) || + surface.id !== admission.surfaceId || + surface.revision !== admission.surfaceRevision || + current.workspaceId !== request.workspaceId || + JSON.stringify( + retainedFieldRequestSchema.parse({ + mode: "retained_field", + workspaceId: fieldContext.workspaceId, + catalogId: fieldContext.catalogId, + field: fieldContext.field, + method: fieldContext.method, + query: fieldContext.query, + selections: fieldContext.items.map((item) => item.binding), + }), + ) !== JSON.stringify(request) + ) + return unavailable; + const projection = projectRetainedField( + fieldContext, + surface.id, + surface.revision, + ); + if (!equalParsedProjection(surface, projection.surface)) return unavailable; + const ready = { + state: "ready" as const, + fieldContext, + ...projection, + descriptors: indexDescriptors(projection.collection.items), + }; + // JSON.stringify(Map) would hide the index contents. Count those too, along + // with every duplicated numeric/text projection, before releasing anything. + return fitsRetainedFieldBudget("ready", { + ...ready, + descriptors: [...ready.descriptors], + }) + ? ready + : unavailable; + } catch { + return unavailable; + } +} diff --git a/lib/intelligent-ui/retained-field/equalParsedProjection.ts b/lib/intelligent-ui/retained-field/equalParsedProjection.ts new file mode 100644 index 000000000..93ca3c350 --- /dev/null +++ b/lib/intelligent-ui/retained-field/equalParsedProjection.ts @@ -0,0 +1,30 @@ +/** Compare schema-parsed JSON: object order is irrelevant; array order is not. */ +export function equalParsedProjection(left: unknown, right: unknown): boolean { + if (left === right) return true; + if ( + left === null || + right === null || + typeof left !== "object" || + typeof right !== "object" + ) + return false; + if (Array.isArray(left) || Array.isArray(right)) { + return ( + Array.isArray(left) && + Array.isArray(right) && + left.length === right.length && + left.every((value, index) => equalParsedProjection(value, right[index])) + ); + } + const a = left as Record; + const b = right as Record; + const keys = Object.keys(a); + return ( + keys.length === Object.keys(b).length && + keys.every( + (key) => + Object.prototype.hasOwnProperty.call(b, key) && + equalParsedProjection(a[key], b[key]), + ) + ); +} diff --git a/lib/intelligent-ui/retained-field/fitsRetainedFieldBudget.ts b/lib/intelligent-ui/retained-field/fitsRetainedFieldBudget.ts new file mode 100644 index 000000000..48a94e101 --- /dev/null +++ b/lib/intelligent-ui/retained-field/fitsRetainedFieldBudget.ts @@ -0,0 +1,17 @@ +const limits = { part: 256 * 1024, ready: 32 * 1024, text: 24 * 1024 } as const; + +/** Count complete UTF-8 output; never truncate private context or projections. */ +export function fitsRetainedFieldBudget( + kind: keyof typeof limits, + value: unknown, +) { + try { + const serialized = kind === "text" ? value : JSON.stringify(value); + return ( + typeof serialized === "string" && + new TextEncoder().encode(serialized).byteLength <= limits[kind] + ); + } catch { + return false; + } +} diff --git a/lib/intelligent-ui/retained-field/projectRetainedField.ts b/lib/intelligent-ui/retained-field/projectRetainedField.ts new file mode 100644 index 000000000..27a659de9 --- /dev/null +++ b/lib/intelligent-ui/retained-field/projectRetainedField.ts @@ -0,0 +1,81 @@ +import { collectionResultSchema } from "../descriptors/collectionResult"; +import { toCollectionComponent } from "../descriptors/toCollectionComponent"; +import { getCollectionText } from "../representations/getCollectionText"; +import { surfaceSchema } from "../schema"; +import { fieldContextSchema, type FieldContext } from "./schemas"; + +/** Offline deterministic projection; a field context is not an authorization lease. */ +export function projectRetainedField( + input: FieldContext, + id: string, + revision: number, +) { + const context = fieldContextSchema.parse(input); + const result = collectionResultSchema.parse({ + workspaceId: context.workspaceId, + items: context.items.map((item) => ({ + ref: item.ref, + label: item.binding.subjectId, + field: { + value: item.value, + role: "observed", + metric: "current_streams", + unit: "streams", + currency: null, + periodStart: item.periods.current.start, + periodEnd: new Date( + Date.parse(`${item.periods.current.end_exclusive}T00:00:00Z`) - + 86400000, + ) + .toISOString() + .slice(0, 10), + territory: "worldwide", + basis: + "Computed sum of retained Luminate daily streams; retrieval time is not provider freshness.", + observedAt: item.source.retrievalRange.latest, + }, + })), + nextCursor: null, + hasMore: false, + knownTotal: null, + completeness: "partial", + aggregationScope: "page", + population: "Selected recordings; catalog total unknown", + selection: context.items.map((item) => item.ref), + }); + const component = { + ...toCollectionComponent(result), + id: "retained-field-recordings", + }; + const periods = context.items[0].periods; + const text = [ + `Historical retained values; evaluated as of ${context.asOf}. Not a currentness lease.`, + `Previous period [${periods.previous.start}, ${periods.previous.end_exclusive}); current period [${periods.current.start}, ${periods.current.end_exclusive}); ${periods.days} days, UTC.`, + "Retrieval timestamps describe retrieval, not provider freshness.", + ...context.items.map( + (item) => + `${item.binding.subjectId}: retrieved ${item.source.retrievalRange.earliest} to ${item.source.retrievalRange.latest}.`, + ), + getCollectionText(component), + ].join("\n"); + const surface = surfaceSchema.parse({ + schemaVersion: 1, + id, + revision, + title: "Historical retained streams", + description: + "Selected recordings only; catalog total unknown. Retrieval time is not provider freshness.", + context: { + workspaceId: context.workspaceId, + subject: { + kind: "catalog", + id: context.catalogId, + label: context.catalogId, + }, + }, + components: [component], + evidence: [], + fallbackText: text, + }); + return { collection: result, surface, text }; +} diff --git a/lib/intelligent-ui/retained-field/schemas.ts b/lib/intelligent-ui/retained-field/schemas.ts new file mode 100644 index 000000000..c20fb8718 --- /dev/null +++ b/lib/intelligent-ui/retained-field/schemas.ts @@ -0,0 +1,194 @@ +import { z } from "zod"; +import { objectRefSchema } from "../descriptors/schemas"; + +const uuid = z + .string() + .uuid() + .refine((value) => value === value.toLowerCase()); +const date = z + .string() + .date() + .refine((value) => { + const time = Date.parse(`${value}T00:00:00Z`); + return ( + Number.isFinite(time) && + new Date(time).toISOString().slice(0, 10) === value + ); + }); +const timestamp = z + .string() + .max(64) + .datetime({ offset: true }) + .refine((value) => Number.isFinite(Date.parse(value))); +const versions = z.array(uuid).length(1); +const method = z + .object({ + recipe: z.literal("catalog-retained-stream-fields/1"), + recipeHash: z.literal( + "65a06a785aa496e1232fe3a9f1606595f19c1a152b710ca30c4c06612f01864a", + ), + evaluatorSha256: z.literal( + "163563e15dd92d473aa51899c54c96300f20d27072b83e39ffb01c84f3adc64e", + ), + helperSha256: z.literal( + "91dcca66c8dec0851c1f6e110257a63b730e9b7ae33a60bceb0e9ffcf318dd81", + ), + }) + .strict(); +const query = z + .object({ + since: date, + days: z.number().int().min(1).max(366), + timezone: z.literal("UTC"), + }) + .strict(); +const binding = z + .object({ + ownerId: uuid, + requestId: uuid, + subjectId: uuid, + catalogId: uuid, + resultId: uuid, + revision: z.number().int().nonnegative().safe(), + topic: z.literal("catalog_retained_streams"), + sourceVersionIds: versions, + }) + .strict(); +const shared = { + workspaceId: uuid, + catalogId: uuid, + field: z.literal("current_streams"), + method, + query, +}; +export const retainedFieldRequestSchema = z + .object({ + mode: z.literal("retained_field"), + ...shared, + selections: z.array(binding).min(1).max(8), + }) + .strict() + .superRefine((value, ctx) => { + if ( + new Set(value.selections.map((row) => row.subjectId)).size !== + value.selections.length || + value.selections.some( + (row) => + row.ownerId !== value.workspaceId || + row.catalogId !== value.catalogId, + ) + ) + ctx.addIssue({ + code: "custom", + message: "Selection scope or identity mismatch", + }); + }); +const period = z.object({ start: date, end_exclusive: date }).strict(); +const count = z.number().int().min(0).max(732); +export const fieldContextSchema = z + .object({ + contract: z.literal("catalog-retained-field-projection/1"), + ...shared, + asOf: timestamp, + semantics: z.literal("historical_snapshot"), + items: z + .array( + z + .object({ + ref: objectRefSchema, + binding, + value: z.discriminatedUnion("state", [ + z + .object({ + state: z.literal("known"), + amount: z.number().int().nonnegative().safe(), + }) + .strict(), + z.object({ state: z.literal("unknown") }).strict(), + ]), + periods: z + .object({ + previous: period, + current: period, + days: z.number().int().min(1).max(366), + timezone: z.literal("UTC"), + }) + .strict(), + coverage: z + .object({ + comparisonState: z.enum(["comparable", "incomplete"]), + absentDateCount: count, + nullDateCount: count, + missingDateCount: count, + }) + .strict(), + source: z + .object({ + provider: z.literal("luminate"), + metric: z.literal("daily_streams"), + platform: z.literal("all_dsps"), + territory: z.literal("worldwide"), + timezone: z.literal("UTC"), + retrievalRange: z + .object({ earliest: timestamp, latest: timestamp }) + .strict(), + }) + .strict(), + }) + .strict(), + ) + .min(1) + .max(8), + }) + .strict() + .superRefine((value, ctx) => { + const fail = () => + ctx.addIssue({ code: "custom", message: "Field context mismatch" }); + // Zod may still run this refinement after a child string refinement fails. + if (!query.safeParse(value.query).success) return fail(); + const start = Date.parse(`${value.query.since}T00:00:00Z`); + const span = value.query.days * 86400000; + if (![start, start - span, start + span].every(Number.isFinite)) + return fail(); + const asOf = Date.parse(value.asOf); + if (!Number.isFinite(asOf) || start + span > asOf) return fail(); + const day = (time: number) => new Date(time).toISOString().slice(0, 10); + if ( + new Set(value.items.map((row) => row.binding.subjectId)).size !== + value.items.length + ) + fail(); + for (const item of value.items) { + const { ref, binding: row, periods, coverage, source } = item; + if ( + row.ownerId !== value.workspaceId || + row.catalogId !== value.catalogId || + ref.workspaceId !== row.ownerId || + ref.authority !== "context" || + ref.kind !== "recording" || + ref.id !== row.subjectId || + ref.sourceVersionIds.length !== 1 || + ref.sourceVersionIds[0] !== row.sourceVersionIds[0] || + periods.days !== value.query.days || + periods.current.start !== value.query.since || + periods.current.end_exclusive !== day(start + span) || + periods.previous.start !== day(start - span) || + periods.previous.end_exclusive !== value.query.since || + (item.value.state === "known") !== + (coverage.comparisonState === "comparable") || + coverage.absentDateCount > 2 * value.query.days || + coverage.nullDateCount > 2 * value.query.days || + coverage.missingDateCount > 2 * value.query.days || + coverage.missingDateCount !== + coverage.absentDateCount + coverage.nullDateCount || + (coverage.comparisonState === "comparable") !== + (coverage.missingDateCount === 0) || + Date.parse(source.retrievalRange.latest) > asOf || + Date.parse(source.retrievalRange.earliest) > + Date.parse(source.retrievalRange.latest) + ) + fail(); + } + }); +export type FieldContext = z.infer; +export type RetainedFieldRequest = z.infer;