import { PROTOCOL_LIMIT_CEILINGS, ProtocolContractError, compareLogCursor, decodeCanonicalTimestamp, decodeLogCursor, decodeProtocolEnvelope, decodeUuid, ROLE_TEXT_MAX_BYTES, utf8ByteLength, type LogCursor, type ProtocolEnvelope, } from './contract.js'; import { decodeEnrichedStreamEntry } from './sse.js'; import type { AppendLogResponse, Decision, EnrichedStreamEntry, LogVisibility, RoutingEcho, } from './types.js'; import { isLabelLine, parseRoleSections } from '../role-section.js'; export interface ReadLogRequest { cursor: LogCursor | null; limit?: number; } export interface AppendLogResult extends Omit { entry: EnrichedStreamEntry; } export interface ReadLogResult { entries: EnrichedStreamEntry[]; cursor: LogCursor | null; behind_by: number; has_more: boolean; } export interface EntryQueryRequest { entry_id: string; } export interface EntryQueryResult { entry: EnrichedStreamEntry; } export interface AckStatusRequest { entry_id: string; } export interface AckStatusRecipient { drone_id: string; drone_label: string | null; drone_role: string | null; acknowledged_at: string | null; } export interface AckStatusClaim { drone_id: string; drone_label: string | null; drone_role: string | null; claimed_at: string; } export interface AckStatusResult { entry_id: string; visibility: LogVisibility; recipients: AckStatusRecipient[]; claims: AckStatusClaim[]; } export interface ReassignDroneRequest { role_id: string; } export interface ManagedDrone { id: string; cube_id: string; role_id: string; label: string; } export interface ReassignDroneResult { drone: ManagedDrone; } export type EvictDroneRequest = Record; export interface EvictDroneResult { drone_id: string; evicted: true; } export type DeleteRoleRequest = Record; export const ROLE_IN_USE_DELETE_MESSAGE = 'Reassign or evict every drone assigned to this role before deleting it.' as const; export interface DeleteRoleResult { role_id: string; deleted: true; } export interface RoleRationaleRequest { role: string; section: string; } export interface RoleRationaleResult { role_id: string; role_name: string; section: { heading: string; body: string; }; } /** Maximum UTF-8 payload for one returned role-description section. */ export const ROLE_RATIONALE_SECTION_BODY_MAX_BYTES = ROLE_TEXT_MAX_BYTES; function object(value: unknown): Record { if (typeof value !== 'object' || value === null || Array.isArray(value)) { throw new ProtocolContractError('Expected a coordination object.'); } return value as Record; } function exact( value: Record, allowed: readonly string[], required: readonly string[], ): void { for (const key of Object.keys(value)) { if (!allowed.includes(key)) throw new ProtocolContractError(`Unknown coordination field "${key}".`); } for (const key of required) { if (!Object.prototype.hasOwnProperty.call(value, key)) { throw new ProtocolContractError(`Missing coordination field "${key}".`); } } } function boundedString(value: unknown, name: string, maximum: number): string { if (typeof value !== 'string' || value.length === 0 || utf8ByteLength(value) > maximum) { throw new ProtocolContractError(`Invalid coordination field "${name}".`); } return value; } function nullableString(value: unknown, name: string, maximum: number): string | null { return value === null ? null : boundedString(value, name, maximum); } function nonNegativeInteger(value: unknown, name: string, maximum: number): number { if (!Number.isSafeInteger(value) || (value as number) < 0 || (value as number) > maximum) { throw new ProtocolContractError(`Invalid coordination field "${name}".`); } return value as number; } function positiveInteger(value: unknown, name: string, maximum: number): number { const decoded = nonNegativeInteger(value, name, maximum); if (decoded === 0) throw new ProtocolContractError(`Invalid coordination field "${name}".`); return decoded; } function decodeManagedDrone(value: unknown): ManagedDrone { const input = object(value); exact(input, ['id', 'cube_id', 'role_id', 'label'], ['id', 'cube_id', 'role_id', 'label']); return { id: decodeUuid(input.id, ['id']), cube_id: decodeUuid(input.cube_id, ['cube_id']), role_id: decodeUuid(input.role_id, ['role_id']), label: boundedString(input.label, 'label', 120), }; } export function decodeReassignDroneRequest(value: unknown): ReassignDroneRequest { const input = object(value); exact(input, ['role_id'], ['role_id']); return { role_id: decodeUuid(input.role_id, ['role_id']) }; } export function decodeReassignDroneRequestEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeReassignDroneRequest); } export function decodeReassignDroneResult(value: unknown): ReassignDroneResult { const input = object(value); exact(input, ['drone'], ['drone']); return { drone: decodeManagedDrone(input.drone) }; } export function decodeReassignDroneResultEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeReassignDroneResult); } export function decodeEvictDroneRequest(value: unknown): EvictDroneRequest { const input = object(value); exact(input, [], []); return {}; } export function decodeEvictDroneRequestEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeEvictDroneRequest); } export function decodeEvictDroneResult(value: unknown): EvictDroneResult { const input = object(value); exact(input, ['drone_id', 'evicted'], ['drone_id', 'evicted']); if (input.evicted !== true) throw new ProtocolContractError('Invalid drone eviction result.'); return { drone_id: decodeUuid(input.drone_id, ['drone_id']), evicted: true }; } export function decodeEvictDroneResultEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeEvictDroneResult); } export function decodeDeleteRoleRequest(value: unknown): DeleteRoleRequest { const input = object(value); exact(input, [], []); return {}; } export function decodeDeleteRoleRequestEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeDeleteRoleRequest); } export function decodeDeleteRoleResult(value: unknown): DeleteRoleResult { const input = object(value); exact(input, ['role_id', 'deleted'], ['role_id', 'deleted']); if (input.deleted !== true) throw new ProtocolContractError('Invalid role deletion result.'); return { role_id: decodeUuid(input.role_id, ['role_id']), deleted: true }; } export function decodeDeleteRoleResultEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeDeleteRoleResult); } function plainRoleSectionHeading(value: unknown): string { const heading = boundedString(value, 'section', 60); if ( heading !== heading.trim() || /[\u0000-\u001f\u007f-\u009f]/.test(heading) || !isLabelLine(`${heading}:`) ) { throw new ProtocolContractError('Invalid coordination field "section".'); } return heading; } export function decodeRoleRationaleRequest(value: unknown): RoleRationaleRequest { const input = object(value); exact(input, ['role', 'section'], ['role', 'section']); const role = boundedString(input.role, 'role', 120); if (role !== role.trim() || /[\u0000-\u001f\u007f-\u009f]/.test(role)) { throw new ProtocolContractError('Invalid coordination field "role".'); } return { role, section: plainRoleSectionHeading(input.section) }; } export function decodeRoleRationaleRequestEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeRoleRationaleRequest); } export function decodeRoleRationaleResult(value: unknown): RoleRationaleResult { const input = object(value); exact(input, ['role_id', 'role_name', 'section'], ['role_id', 'role_name', 'section']); const section = object(input.section); exact(section, ['heading', 'body'], ['heading', 'body']); const heading = plainRoleSectionHeading(section.heading); const body = boundedString( section.body, 'section.body', ROLE_RATIONALE_SECTION_BODY_MAX_BYTES, ); const parsed = parseRoleSections(body); if ( parsed.length !== 2 || parsed[0]?.kind !== 'preamble' || parsed[0].body !== '' || parsed[1]?.kind !== 'label' || parsed[1].heading !== heading || parsed[1].body !== body ) { throw new ProtocolContractError('Invalid coordination field "section.body".'); } return { role_id: decodeUuid(input.role_id, ['role_id']), role_name: boundedString(input.role_name, 'role_name', 120), section: { heading, body, }, }; } export function decodeRoleRationaleResultEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeRoleRationaleResult); } export function decodeReadLogRequest(value: unknown): ReadLogRequest { const input = object(value); exact(input, ['cursor', 'limit'], ['cursor']); const output: ReadLogRequest = { cursor: input.cursor === null ? null : decodeLogCursor(input.cursor, ['cursor']), }; if (input.limit !== undefined) output.limit = positiveInteger(input.limit, 'limit', 500); return output; } export function decodeReadLogRequestEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeReadLogRequest); } export function decodeEntryQueryRequest(value: unknown): EntryQueryRequest { const input = object(value); exact(input, ['entry_id'], ['entry_id']); const entryId = boundedString(input.entry_id, 'entry_id', 36); if (/^[0-9a-f]{8}$/i.test(entryId)) return { entry_id: entryId.toLowerCase() }; return { entry_id: decodeUuid(entryId, ['entry_id']) }; } export function decodeEntryQueryRequestEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeEntryQueryRequest); } export function decodeEntryQueryResult(value: unknown): EntryQueryResult { const input = object(value); exact(input, ['entry'], ['entry']); return { entry: decodeEnrichedStreamEntry(input.entry) }; } export function decodeEntryQueryResultEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeEntryQueryResult); } export function decodeAckStatusRequest(value: unknown): AckStatusRequest { const input = object(value); exact(input, ['entry_id'], ['entry_id']); return { entry_id: decodeUuid(input.entry_id, ['entry_id']) }; } export function decodeAckStatusRequestEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeAckStatusRequest); } function decodeAckStatusRecipient(value: unknown): AckStatusRecipient { const input = object(value); exact( input, ['drone_id', 'drone_label', 'drone_role', 'acknowledged_at'], ['drone_id', 'drone_label', 'drone_role', 'acknowledged_at'], ); return { drone_id: decodeUuid(input.drone_id, ['drone_id']), drone_label: nullableString(input.drone_label, 'drone_label', 120), drone_role: nullableString(input.drone_role, 'drone_role', 120), acknowledged_at: input.acknowledged_at === null ? null : decodeCanonicalTimestamp(input.acknowledged_at, ['acknowledged_at']), }; } function decodeAckStatusClaim(value: unknown): AckStatusClaim { const input = object(value); exact( input, ['drone_id', 'drone_label', 'drone_role', 'claimed_at'], ['drone_id', 'drone_label', 'drone_role', 'claimed_at'], ); return { drone_id: decodeUuid(input.drone_id, ['drone_id']), drone_label: nullableString(input.drone_label, 'drone_label', 120), drone_role: nullableString(input.drone_role, 'drone_role', 120), claimed_at: decodeCanonicalTimestamp(input.claimed_at, ['claimed_at']), }; } export function decodeAckStatusResult(value: unknown): AckStatusResult { const input = object(value); exact( input, ['entry_id', 'visibility', 'recipients', 'claims'], ['entry_id', 'visibility', 'recipients', 'claims'], ); if (input.visibility !== 'broadcast' && input.visibility !== 'direct') { throw new ProtocolContractError('Invalid acknowledgement-status visibility.'); } if (!Array.isArray(input.recipients) || input.recipients.length > 500) { throw new ProtocolContractError('Invalid acknowledgement-status recipients.'); } if (!Array.isArray(input.claims) || input.claims.length > 500) { throw new ProtocolContractError('Invalid acknowledgement-status claims.'); } return { entry_id: decodeUuid(input.entry_id, ['entry_id']), visibility: input.visibility, recipients: input.recipients.map(decodeAckStatusRecipient), claims: input.claims.map(decodeAckStatusClaim), }; } export function decodeAckStatusResultEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeAckStatusResult); } function decodeRoutingEcho(value: unknown): RoutingEcho { const input = object(value); exact( input, ['class', 'recipients'], ['class', 'recipients'], ); if (!Array.isArray(input.recipients) || input.recipients.length > 100) { throw new ProtocolContractError('Invalid routing recipient list.'); } return { class: nullableString(input.class, 'routing.class', 64), recipients: input.recipients.map((recipient) => boundedString(recipient, 'routing.recipients', 120) ), }; } function decodeUnreachableRecipient( value: unknown, ): NonNullable[number] { const input = object(value); exact(input, ['id', 'label'], ['id', 'label']); return { id: boundedString(input.id, 'unreachableRecipients.id', 120), label: boundedString(input.label, 'unreachableRecipients.label', 120), }; } export function decodeAppendLogResult(value: unknown): AppendLogResult { const input = object(value); exact(input, ['entry', 'deduplicated', 'routing', 'unreachableRecipients', 'advisory'], ['entry', 'deduplicated']); if (typeof input.deduplicated !== 'boolean') { throw new ProtocolContractError('Invalid append-log deduplicated flag.'); } const output: AppendLogResult = { entry: decodeEnrichedStreamEntry(input.entry), deduplicated: input.deduplicated, }; if (input.routing !== undefined) { output.routing = input.routing === null ? null : decodeRoutingEcho(input.routing); } if (input.unreachableRecipients !== undefined) { if (!Array.isArray(input.unreachableRecipients) || input.unreachableRecipients.length > 100) { throw new ProtocolContractError('Invalid unreachable-recipient list.'); } output.unreachableRecipients = input.unreachableRecipients.map(decodeUnreachableRecipient); } if (input.advisory !== undefined) { const advisory = object(input.advisory); exact(advisory, ['code', 'threshold_bytes'], ['code', 'threshold_bytes']); if (advisory.code !== 'STORE_AS_DOCUMENT') { throw new ProtocolContractError('Invalid append-log document advisory.'); } const threshold = positiveInteger( advisory.threshold_bytes, 'advisory.threshold_bytes', PROTOCOL_LIMIT_CEILINGS.max_log_message_bytes, ); output.advisory = { code: 'STORE_AS_DOCUMENT', threshold_bytes: threshold }; } return output; } export function decodeAppendLogResultEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeAppendLogResult); } export function decodeReadLogResult(value: unknown): ReadLogResult { const input = object(value); exact( input, ['entries', 'cursor', 'behind_by', 'has_more'], ['entries', 'cursor', 'behind_by', 'has_more'], ); if (!Array.isArray(input.entries) || input.entries.length > 500) { throw new ProtocolContractError('Invalid read-log entries.'); } if (typeof input.has_more !== 'boolean') throw new ProtocolContractError('Invalid has_more flag.'); const entries = input.entries.map(decodeEnrichedStreamEntry); const cursor = input.cursor === null ? null : decodeLogCursor(input.cursor, ['cursor']); for (let index = 1; index < entries.length; index++) { const previous = { id: entries[index - 1].id, created_at: entries[index - 1].created_at }; const current = { id: entries[index].id, created_at: entries[index].created_at }; if (compareLogCursor(previous, current) >= 0) { throw new ProtocolContractError('Read-log entries are not strictly cursor ordered.'); } } if (entries.length > 0) { const last = entries.at(-1)!; if (cursor === null || cursor.id !== last.id || cursor.created_at !== last.created_at) { throw new ProtocolContractError('Read-log cursor must equal the final entry tuple.'); } } return { entries, cursor, behind_by: nonNegativeInteger(input.behind_by, 'behind_by', Number.MAX_SAFE_INTEGER), has_more: input.has_more, }; } export function decodeReadLogResultEnvelope( value: unknown, ): ProtocolEnvelope { return decodeProtocolEnvelope(value, decodeReadLogResult); } export function decodeDecision(value: unknown): Decision { const input = object(value); exact( input, [ 'id', 'cube_id', 'topic', 'decision', 'rationale', 'ratified_by', 'status', 'supersedes', 'created_at', ], [ 'id', 'cube_id', 'topic', 'decision', 'rationale', 'ratified_by', 'status', 'supersedes', 'created_at', ], ); if (!['active', 'superseded', 'removed'].includes(String(input.status))) { throw new ProtocolContractError('Invalid decision status.'); } return { id: decodeUuid(input.id, ['id']), cube_id: decodeUuid(input.cube_id, ['cube_id']), topic: boundedString(input.topic, 'topic', 120), // Existing registry entries may exceed the write limit; only new writes are capped. decision: boundedString(input.decision, 'decision', Number.MAX_SAFE_INTEGER), rationale: nullableString(input.rationale, 'rationale', Number.MAX_SAFE_INTEGER), ratified_by: input.ratified_by === null ? null : decodeUuid(input.ratified_by, ['ratified_by']), status: input.status as 'active' | 'superseded' | 'removed', supersedes: input.supersedes === null ? null : decodeUuid(input.supersedes, ['supersedes']), created_at: decodeCanonicalTimestamp(input.created_at, ['created_at']), }; } export function decodeDecisionResultEnvelope( value: unknown, ): ProtocolEnvelope<{ decision: Decision }> { return decodeProtocolEnvelope(value, (payload) => { const input = object(payload); exact(input, ['decision'], ['decision']); return { decision: decodeDecision(input.decision) }; }); } export function decodeDecisionsResultEnvelope( value: unknown, ): ProtocolEnvelope<{ decisions: Decision[] }> { return decodeProtocolEnvelope(value, (payload) => { const input = object(payload); exact(input, ['decisions'], ['decisions']); if (!Array.isArray(input.decisions) || input.decisions.length > 500) { throw new ProtocolContractError('Invalid decisions list.'); } return { decisions: input.decisions.map(decodeDecision) }; }); }