/** Pure poll-journal accounting, not MAC/terminal authority. Full reservations * include unresolved work; compact history continues paying bytes and rows. * Bytes are logical charges, never a claim about PostgreSQL relation size. */ const ATTEMPT_BYTES = 8 * 1024 * 1024 const ADMISSION_BYTES = 32768 const ATTEMPT_ROWS = 4019 // anchor + 2008 intents + 2008 acks + receipt + quarantine const DAY_MS = 86400000 const DATE_MAX = 8640000000000000 export interface PollStoragePolicy { attemptBytes: number admissionBytes: number attemptRows: number retentionDays: number safetyWindowMs: number } export const SERVER_POLL_STORAGE_POLICY: Readonly = Object.freeze({ attemptBytes: ATTEMPT_BYTES, admissionBytes: ADMISSION_BYTES, attemptRows: ATTEMPT_ROWS, retentionDays: 14, safetyWindowMs: 60000, }) export class PollStorageRefused extends Error { readonly automaticReplay=false constructor() { super("Poll storage state unavailable"); this.name = "PollStorageRefused" } } function refuse(): never { throw new PollStorageRefused() } const integer = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && !Object.is(value,-0) const timestamp = (value: unknown): value is number => integer(value) && value <= DATE_MAX const record = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value) const days = (value: unknown): value is number => integer(value) && value >= 1 && value <= 365 const uuid = (value: unknown): value is string => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) const hash = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{64}$/.test(value) /** Trusted composition only. Per-poll charges cannot be changed by a * caller; only retention and its safety window are configurable. */ export function pollStoragePolicy(raw: unknown = SERVER_POLL_STORAGE_POLICY): Readonly { if (!record(raw) || Object.keys(raw).some(key => !Object.hasOwn(SERVER_POLL_STORAGE_POLICY, key))) refuse() for (const key of Object.keys(SERVER_POLL_STORAGE_POLICY) as (keyof PollStoragePolicy)[]) { if (key !== "retentionDays" && key !== "safetyWindowMs" && raw[key] !== SERVER_POLL_STORAGE_POLICY[key]) refuse() } if (!days(raw.retentionDays) || !integer(raw.safetyWindowMs) || raw.safetyWindowMs < 60000 || raw.safetyWindowMs > DAY_MS) refuse() return Object.freeze({ ...SERVER_POLL_STORAGE_POLICY, retentionDays: raw.retentionDays, safetyWindowMs: raw.safetyWindowMs }) } export interface PollStorageScope { receiptId: string kind: "rest" | "mcp" executionId: string ownerId: string bindingProof: string contextProof: string issuedAt: number expiresAt: number } /** Expired scope parsing is exclusively for retained metadata, never a claim. */ export function pollStorageScope(raw: unknown, options: { now: number; allowExpired?: boolean }): Readonly { if (!record(raw) || !timestamp(options.now) || options.allowExpired !== undefined && typeof options.allowExpired !== "boolean" || Object.keys(raw).some(key => !["receiptId", "kind", "executionId", "ownerId", "bindingProof", "contextProof", "issuedAt", "expiresAt"].includes(key)) || !uuid(raw.receiptId) || !uuid(raw.executionId) || raw.kind !== "rest" && raw.kind !== "mcp" || typeof raw.ownerId !== "string" || !raw.ownerId.length || raw.ownerId.length > 200 || raw.ownerId.trim() !== raw.ownerId || /[\x00-\x1f\x7f-\x9f]/.test(raw.ownerId) || !hash(raw.bindingProof) || !hash(raw.contextProof) || !timestamp(raw.issuedAt) || !timestamp(raw.expiresAt) || raw.expiresAt <= raw.issuedAt || raw.issuedAt > options.now || !options.allowExpired && options.now >= raw.expiresAt) refuse() return Object.freeze({ receiptId: raw.receiptId, kind: raw.kind, executionId: raw.executionId, ownerId: raw.ownerId, bindingProof: raw.bindingProof, contextProof: raw.contextProof, issuedAt: raw.issuedAt, expiresAt: raw.expiresAt }) } export interface PollStorageUsage { attempts: number; bytes: number; rows: number; compactedAttempts?: number; archiveBytes?: number } export function validatePollStorageUsage(raw: PollStorageUsage) { if (!record(raw)) refuse() const compact = Object.hasOwn(raw,"compactedAttempts"), archive = Object.hasOwn(raw,"archiveBytes") const keys = Object.keys(raw).sort().join(",") if (compact !== archive || keys !== (compact ? "archiveBytes,attempts,bytes,compactedAttempts,rows" : "attempts,bytes,rows")) refuse() const count = compact ? raw.compactedAttempts : 0, encoded = archive ? raw.archiveBytes : 0 if (!integer(raw.attempts) || !integer(raw.bytes) || !integer(raw.rows) || !integer(count) || !integer(encoded) || encoded < count * 40 || encoded > count * 131072) refuse() const expectedRows = raw.attempts * ATTEMPT_ROWS + count * 2 const expectedBytes = raw.attempts * (ATTEMPT_BYTES + ADMISSION_BYTES) + count * ADMISSION_BYTES + encoded if (!integer(expectedRows) || !integer(expectedBytes) || raw.rows !== expectedRows || raw.bytes !== expectedBytes) refuse() return { ...raw, compactedAttempts:count, archiveBytes:encoded } } export interface PollStorageGcCandidate { scope: PollStorageScope lastActivityAt: number gcNotBefore: number retentionDays: number safetyWindowMs: number /** Caller must verify the actual operation, never infer terminality from a receipt. */ mcpTerminal: boolean } /** No forced-delete branch: malformed/overflowed dates and live MCP operations * remain reserved. Increasing retention applies to already persisted attempts. */ export function pollStorageGcEligible(candidate: PollStorageGcCandidate, rawPolicy: PollStoragePolicy, now: number): boolean { try { const policy = pollStoragePolicy(rawPolicy) if (!record(candidate) || !timestamp(now)) return false const scope = pollStorageScope(candidate.scope, { now, allowExpired: true }) if (!timestamp(candidate.lastActivityAt) || candidate.lastActivityAt < scope.issuedAt || candidate.lastActivityAt > now || !timestamp(candidate.gcNotBefore) || !days(candidate.retentionDays) || !integer(candidate.safetyWindowMs) || candidate.safetyWindowMs < 60000 || candidate.safetyWindowMs > DAY_MS || typeof candidate.mcpTerminal !== "boolean" || scope.kind === "mcp" && !candidate.mcpTerminal) return false const retainedUntil = Math.max(scope.expiresAt, candidate.lastActivityAt) + Math.max(policy.retentionDays, candidate.retentionDays) * DAY_MS + Math.max(policy.safetyWindowMs, candidate.safetyWindowMs) return timestamp(retainedUntil) && now > Math.max(candidate.gcNotBefore, retainedUntil) } catch { return false } }