import { ErrorCode, compareLogCursor, createProtocolEnvelope, decodeAssociateRepositoryCubeResponseEnvelope, decodeCreateCubeResponseEnvelope, decodeDeleteCubeResponseEnvelope, decodeAppendLogResultEnvelope, decodeAckStatusResultEnvelope, decodeEntryQueryResultEnvelope, decodeDecisionResultEnvelope, decodeDecisionsResultEnvelope, decodeEnrollmentExchangeResponseEnvelope, decodeInvitationArtifact, decodeAttachResponseEnvelope, decodeReconcileAttachmentResponseEnvelope, deriveAttachmentReceipt, type ReconcileAttachmentAction, type ReconcileAttachmentRequest, type AttachRequest, decodeEvictDroneResultEnvelope, decodeDeleteRoleResultEnvelope, decodeRoleRationaleResultEnvelope, decodeProtocolEnvelope, decodeProtocolErrorEnvelope, decodeProtocolTagPreflight, decodeReadLogResultEnvelope, decodeResolveRepositoryCubeResponseEnvelope, decodeReassignDroneResultEnvelope, decodeUpdateDroneRuntimeMetadataResponseEnvelope, decodeGetDocumentResultEnvelope, decodeListDocumentsResultEnvelope, decodePutDocumentResultEnvelope, decodeRemoveDocumentResultEnvelope, decodeSseFrames, PROTOCOL_LIMIT_CEILINGS, PROTOCOL_HTTP_CONTRACT, PROTOCOL_VERSION, ROLE_IN_USE_DELETE_MESSAGE, utf8ByteLength, type CreateCubeRepository, type CubeTemplate, type LogCursor, type StreamEvent, type CubeDocument, type EnrichedStreamEntry, } from '../protocol/index.js'; import { APPEND_LOG_IDEMPOTENCY_CONFORMANCE, CREATE_CUBE_ASSOCIATION_CONFORMANCE, CREATE_CUBE_RETRY_CONFORMANCE, INVITATION_ARTIFACT_CONFORMANCE, ENROLLMENT_RETRY_CONFORMANCE, DOCUMENT_CONFORMANCE, } from './index.js'; export interface ConformanceHttpResponse { status: number; body: unknown; } export interface ConformancePrincipal { readonly id: string; } export interface ConformanceCube { readonly id: string; } export interface ConformanceRole { readonly id: string; } export interface ConformanceDrone { readonly id: string; } export type ConformanceCubeAccess = 'read' | 'write' | 'manage'; export interface ConformanceRepositoryCubeFixture { cube_id: string; name: string; template: CubeTemplate; human_seat_role_id: string; default_worker_role_id: string; access: 'manage'; } export interface ConformanceReplayBarrier { /** Resolves after the replay snapshot is read but before live delivery is active. */ readonly reached: Promise; release(): void; } export interface ConformanceStreamResponse extends ConformanceHttpResponse { /** Present only for a successful streaming response. Chunks are raw SSE wire text. */ stream: AsyncIterable | null; } /** * Privileged test-only controls. Production request handlers must never expose * these operations; an adapter implements them through its test fixture layer. */ export interface ConformanceAdmin { reset(): Promise; createPrincipal(name: string): Promise; createCube(name: string): Promise; /** Grants the requested cube authority; omitted access defaults to manage. */ grantCube( principal: ConformancePrincipal, cube: ConformanceCube, access?: ConformanceCubeAccess, ): Promise; revokeCubeGrant(principal: ConformancePrincipal, cube: ConformanceCube): Promise; createRole(cube: ConformanceCube, input: { readonly roleClass: 'queen' | 'worker'; readonly isHumanSeat: boolean; readonly name?: string; readonly detailedDescription?: string; readonly isDefault?: boolean; readonly isMandatory?: boolean; }): Promise; /** * Seeds deterministic IDs required to exercise full, unique-prefix, and * ambiguous-prefix lookup. Protocol-assigned random IDs cannot portably * guarantee those prefix shapes, so this remains a semantic synthetic control. */ seedEntryQueryIds( cube: ConformanceCube, entries: readonly { current_id: string; query_id: string }[], ): Promise; createDrone( principal: ConformancePrincipal, cube: ConformanceCube, role: ConformanceRole, ): Promise; issueManagedDroneSession(drone: ConformanceDrone): Promise; revokeManagedDroneSession(drone: ConformanceDrone): Promise; grantCreateCubeCapability(principal: ConformancePrincipal): Promise; issueDroneSession(principal: ConformancePrincipal): Promise; issueSingleUseInvitation(principal: ConformancePrincipal, purpose: 'owner' | 'client'): Promise; prepareRepositoryCube( cube: ConformanceCube, input: { name: string; template: CubeTemplate; }, ): Promise; revokePrincipal(principal: ConformancePrincipal): Promise; expireCursor(cube: ConformanceCube, cursor: LogCursor): Promise; armReplayTransition(): ConformanceReplayBarrier; } /** Raw, authenticated adapter operations driven entirely by the shared runner. */ export interface ConformanceOperations { health(): Promise; protocol(credential: string | null): Promise; enroll(request: unknown): Promise; createCube(credential: string | null, request: unknown): Promise; deleteCube( credential: string, cube: ConformanceCube, request: unknown, ): Promise; putDocument(credential: string, cube: ConformanceCube, request: unknown): Promise; getDocument(credential: string, cube: ConformanceCube, request: unknown): Promise; listDocuments(credential: string, cube: ConformanceCube, request: unknown): Promise; removeDocument(credential: string, cube: ConformanceCube, request: unknown): Promise; resolveRepositoryCube(credential: string | null, request: unknown): Promise; associateRepositoryCube(credential: string | null, request: unknown): Promise; attach(credential: string, request: unknown): Promise; reconcileAttachment(credential: string, request: unknown): Promise; selfMetadataUpdate( credential: string, cube: ConformanceCube, request: unknown, ): Promise; append( credential: string, cube: ConformanceCube, request: unknown, ): Promise; /** Sends an exact UTF-8 JSON body through the adapter's size and parsing boundary. */ appendRaw( credential: string, cube: ConformanceCube, body: string, ): Promise; read( credential: string, cube: ConformanceCube, request: unknown, ): Promise; entryQuery( credential: string, cube: ConformanceCube, request: unknown, ): Promise; ack( credential: string, cube: ConformanceCube, request: unknown, ): Promise; ackStatus( credential: string, cube: ConformanceCube, request: unknown, ): Promise; updateCube( credential: string, cube: ConformanceCube, request: unknown, ): Promise; createRole( credential: string, cube: ConformanceCube, request: unknown, ): Promise; patchTaxonomy( credential: string, cube: ConformanceCube, request: unknown, ): Promise; recordDecision( credential: string, cube: ConformanceCube, request: unknown, ): Promise; listDecisions( credential: string, cube: ConformanceCube, request: unknown, ): Promise; listDrones( credential: string, cube: ConformanceCube, ): Promise; reassignDrone( credential: string, cube: ConformanceCube, drone: ConformanceDrone, request: unknown, ): Promise; evictDrone( credential: string, cube: ConformanceCube, drone: ConformanceDrone, request: unknown, ): Promise; deleteRole( credential: string, cube: ConformanceCube, role: ConformanceRole, request: unknown, ): Promise; roleRationale( credential: string, cube: ConformanceCube, request: unknown, ): Promise; openStream( credential: string, cube: ConformanceCube, cursor: LogCursor | null, ): Promise; } export interface ConformanceEnvironment { readonly admin: ConformanceAdmin; readonly operations: ConformanceOperations; } export const ADAPTER_CONFORMANCE_FIXTURES = [ { id: 'http.unauthenticated-liveness', area: 'http' }, { id: 'protocol.credential-free-preflight', area: 'protocol' }, { id: 'enrollment.invitation-artifact', area: 'enrollment' }, { id: 'enrollment.retry-authority', area: 'enrollment' }, { id: 'repository.explicit-association', area: 'repository' }, { id: 'documents.lifecycle', area: 'documents' }, { id: 'security.adapter-boundary-injection', area: 'security' }, { id: 'security.oversize-request', area: 'security' }, { id: 'security.cross-cube-isolation', area: 'security' }, { id: 'log.append-idempotency', area: 'log' }, { id: 'log.mandatory-addressing', area: 'log' }, { id: 'log.entry-query', area: 'log' }, { id: 'log.read-cursor-tuple', area: 'cursor' }, { id: 'sse.replay-live-transition', area: 'sse' }, { id: 'cursor.explicit-expiry', area: 'cursor' }, { id: 'acks.idempotent', area: 'acks' }, { id: 'acks.status-query', area: 'acks' }, { id: 'decisions.topic-supersession', area: 'decisions' }, { id: 'security.drone-management-authorization', area: 'security' }, { id: 'security.manage-access-matrix', area: 'security' }, { id: 'drones.reassign-invariants', area: 'drones' }, { id: 'security.cross-cube-drone-management', area: 'security' }, { id: 'drones.evict-terminal-signal', area: 'drones' }, { id: 'roles.delete-contract', area: 'roles' }, { id: 'roles.rationale-contract', area: 'roles' }, { id: 'metadata.attach-report', area: 'metadata' }, { id: 'metadata.self-heal-patch', area: 'metadata' }, { id: 'security.metadata-invalid-atomic', area: 'security' }, { id: 'security.metadata-own-seat', area: 'security' }, { id: 'security.metadata-cross-cube-isolation', area: 'security' }, { id: 'security.metadata-noninterference', area: 'security' }, { id: 'security.metadata-secret-non-echo', area: 'security' }, { id: 'security.active-stream-revocation', area: 'security' }, { id: 'cubes.delete-terminal-cascade', area: 'cubes' }, { id: 'attachment.reconciliation', area: 'attachment' }, ] as const; export type AdapterConformanceFixtureId = (typeof ADAPTER_CONFORMANCE_FIXTURES)[number]['id']; const FIXTURE_PREREQUISITES: Partial> = { 'repository.explicit-association': ['shared.enrolled-principals'], 'documents.lifecycle': ['shared.enrolled-principals'], 'security.adapter-boundary-injection': ['shared.enrolled-principals'], 'security.oversize-request': ['shared.enrolled-principals'], 'security.cross-cube-isolation': ['shared.enrolled-principals'], 'log.mandatory-addressing': ['shared.enrolled-principals'], 'log.entry-query': ['shared.enrolled-principals'], 'log.read-cursor-tuple': ['shared.enrolled-principals'], 'sse.replay-live-transition': ['shared.enrolled-principals'], 'cursor.explicit-expiry': ['shared.enrolled-principals'], 'acks.idempotent': ['shared.enrolled-principals'], 'acks.status-query': ['shared.enrolled-principals'], 'decisions.topic-supersession': ['shared.enrolled-principals'], 'security.manage-access-matrix': ['shared.enrolled-principals'], 'drones.reassign-invariants': ['shared.enrolled-principals'], 'security.cross-cube-drone-management': ['shared.enrolled-principals'], 'drones.evict-terminal-signal': ['shared.enrolled-principals'], 'metadata.attach-report': ['shared.enrolled-principals'], 'metadata.self-heal-patch': ['shared.enrolled-principals', 'shared.metadata-baseline'], 'security.metadata-invalid-atomic': ['shared.enrolled-principals', 'shared.metadata-baseline'], 'security.metadata-own-seat': ['shared.enrolled-principals', 'shared.metadata-baseline'], 'security.metadata-cross-cube-isolation': ['shared.enrolled-principals', 'shared.metadata-baseline'], 'security.metadata-noninterference': ['shared.enrolled-principals', 'shared.metadata-baseline'], 'security.metadata-secret-non-echo': ['shared.enrolled-principals', 'shared.metadata-baseline'], }; export interface AdapterConformanceResult { id: AdapterConformanceFixtureId; ok: boolean; /** True when the fixture was not exercised because a named prerequisite failed. */ skipped?: boolean; observations: Record; error?: string; } export interface AdapterConformanceReport { ok: boolean; results: AdapterConformanceResult[]; /** Stable, identifier-free observations suitable for cross-adapter comparison. */ normalizedTranscript: ReadonlyArray<{ id: AdapterConformanceFixtureId; observations: Record; }>; } export interface AdapterConformanceOptions { /** Maximum wait for a replay, live delivery, or revocation close. */ streamDeadlineMs?: number; /** Observation window used to prove an idle stream remains pending. */ pendingProbeMs?: number; } const DEFAULT_STREAM_DEADLINE_MS = 5_000; const DEFAULT_PENDING_PROBE_MS = 25; function invariant(condition: unknown, message: string): asserts condition { if (!condition) throw new Error(message); } function protocolError(response: ConformanceHttpResponse): ErrorCode | null { try { return decodeProtocolErrorEnvelope(response.body).error.code; } catch { return null; } } function protocolErrorMessage(response: ConformanceHttpResponse): string | null { try { return decodeProtocolErrorEnvelope(response.body).error.message; } catch { return null; } } function delay(milliseconds: number): Promise { const setTimeoutValue = (globalThis as unknown as { setTimeout?: (callback: () => void, delay: number) => unknown; }).setTimeout; if (!setTimeoutValue) throw new Error('Conformance runner requires a timer implementation.'); return new Promise((resolve) => setTimeoutValue(resolve, milliseconds)); } async function within( promise: Promise, description: string, deadlineMs: number, ): Promise { const timers = globalThis as unknown as { setTimeout?: (callback: () => void, delay: number) => unknown; clearTimeout?: (timer: unknown) => void; }; if (!timers.setTimeout || !timers.clearTimeout) { throw new Error('Conformance runner requires timer cancellation support.'); } return new Promise((resolve, reject) => { const timer = timers.setTimeout!(() => { reject(new Error(`${description} did not settle within ${deadlineMs}ms.`)); }, deadlineMs); promise.then( (value) => { timers.clearTimeout!(timer); resolve(value); }, (error) => { timers.clearTimeout!(timer); reject(error); }, ); }); } async function provePending( promise: Promise, description: string, probeMs: number, ): Promise { const settled = await Promise.race([ promise.then( () => true, () => true, ), delay(probeMs).then(() => false), ]); invariant(!settled, `${description} settled before new activity.`); } class SseEventReader { private readonly iterator: AsyncIterator; private buffer = ''; private ended = false; constructor(stream: AsyncIterable) { this.iterator = stream[Symbol.asyncIterator](); } async next(): Promise { while (true) { this.buffer = this.buffer .replace(/\r\n/g, '\n') .replace(this.ended ? /\r/g : /\r(?!$)/g, '\n'); const boundary = this.buffer.search(/\n\n+/); if (boundary >= 0) { const match = this.buffer.slice(boundary).match(/^\n\n+/); invariant(match, 'Internal SSE frame boundary error.'); const frame = this.buffer.slice(0, boundary); this.buffer = this.buffer.slice(boundary + match[0].length); if (frame.trim() === '') continue; const events = decodeSseFrames(`${frame}\n\n`); invariant(events.length === 1, 'Expected exactly one SSE event per frame.'); return events[0]; } if (this.ended) { if (this.buffer.trim() !== '') throw new Error('SSE stream ended with an incomplete frame.'); throw new Error('SSE stream ended while an event was expected.'); } const chunk = await this.iterator.next(); if (chunk.done) { this.ended = true; continue; } invariant(typeof chunk.value === 'string', 'SSE stream yielded a non-string chunk.'); this.buffer += chunk.value; } } async close(): Promise { if (this.iterator.return) await this.iterator.return(); } } function expectStatus(response: ConformanceHttpResponse, status: number, operation: string): void { invariant( response.status === status, `${operation} returned HTTP ${response.status}; expected ${status}.`, ); } function expectError( response: ConformanceHttpResponse, status: number, code: ErrorCode, operation: string, ): void { expectStatus(response, status, operation); invariant(protocolError(response) === code, `${operation} did not return ${code}.`); } function logEvent(event: StreamEvent, description: string): Extract { invariant(event.type === 'log', `${description} produced ${event.type}, not a log event.`); return event; } function same(left: unknown, right: unknown): boolean { return JSON.stringify(left) === JSON.stringify(right); } function listedDroneIds(response: ConformanceHttpResponse): string[] { return decodeProtocolEnvelope(response.body, (payload) => { invariant(typeof payload === 'object' && payload !== null, 'Roster payload is not an object.'); const drones = (payload as { drones?: unknown }).drones; invariant(Array.isArray(drones), 'Roster payload omitted drones.'); return drones.map((drone) => { invariant(typeof drone === 'object' && drone !== null, 'Roster contains an invalid drone.'); const id = (drone as { id?: unknown }).id; invariant(typeof id === 'string', 'Roster drone omitted its id.'); return id; }); }).payload; } function listedDrone(response: ConformanceHttpResponse, droneId: string): Record | null { return decodeProtocolEnvelope(response.body, (payload) => { invariant(typeof payload === 'object' && payload !== null, 'Roster payload is not an object.'); const drones = (payload as { drones?: unknown }).drones; invariant(Array.isArray(drones), 'Roster payload omitted drones.'); const drone = drones.find((candidate) => typeof candidate === 'object' && candidate !== null && (candidate as { id?: unknown }).id === droneId ); return drone ? { ...drone as Record } : null; }).payload; } function withoutRuntimeMetadata(drone: Record): Record { const { agent_kind: _agentKind, reported_model: _reportedModel, working_repo_name: _workingRepoName, working_repo_origin: _workingRepoOrigin, runtime_metadata_reported: _runtimeMetadataReported, ...rest } = drone; return rest; } function assertEnrollmentErrorIsSecretFree( response: ConformanceHttpResponse, requests: readonly { invitation: string; retry_key: string; client_credential: string }[], description: string, ): void { const diagnostic = JSON.stringify(response.body); const secrets = new Set(requests.flatMap((request) => [ request.invitation, request.retry_key, request.client_credential, ])); for (const secret of secrets) { invariant(!diagnostic.includes(secret), `${description} exposed enrollment retry material.`); } } function expectSecretFreeError( response: ConformanceHttpResponse, status: number, code: ErrorCode, operation: string, secrets: readonly string[], ): void { expectError(response, status, code, operation); const diagnostic = JSON.stringify(response.body); for (const secret of new Set(secrets)) { invariant(!diagnostic.includes(secret), `${operation} exposed sensitive material.`); } } export async function runAdapterConformance( environment: ConformanceEnvironment, options: AdapterConformanceOptions = {}, ): Promise { const streamDeadlineMs = options.streamDeadlineMs ?? DEFAULT_STREAM_DEADLINE_MS; const pendingProbeMs = options.pendingProbeMs ?? DEFAULT_PENDING_PROBE_MS; invariant(streamDeadlineMs > 0, 'streamDeadlineMs must be positive.'); invariant(pendingProbeMs > 0, 'pendingProbeMs must be positive.'); const results: AdapterConformanceResult[] = []; const prerequisiteFailures = new Map(); const record = async ( id: AdapterConformanceFixtureId, execute: () => Promise>, prerequisites: readonly string[] = [], ): Promise => { const required = [...(FIXTURE_PREREQUISITES[id] ?? []), ...prerequisites]; const failedPrerequisite = required.find((name) => prerequisiteFailures.has(name)); if (failedPrerequisite) { results.push({ id, ok: false, skipped: true, observations: {}, error: `Skipped because prerequisite ${failedPrerequisite} failed: ${prerequisiteFailures.get(failedPrerequisite)}`, }); return; } try { results.push({ id, ok: true, observations: await execute() }); } catch (error) { const message = error instanceof Error ? error.message : String(error); results.push({ id, ok: false, observations: {}, error: message, }); } }; await environment.admin.reset(); let principalA!: ConformancePrincipal; let principalB!: ConformancePrincipal; let cubeA!: ConformanceCube; let cubeB!: ConformanceCube; let credentialA = ''; let credentialB = ''; await record('http.unauthenticated-liveness', async () => { const response = await environment.operations.health(); expectStatus(response, 204, 'Unauthenticated liveness'); invariant(response.body === '' || response.body === undefined, 'Unauthenticated liveness exposed a response body.'); return { status: 204, bodyless: true }; }); await record('protocol.credential-free-preflight', async () => { // The tag preflight is credential-free: a client verifies pinned TLS and the // exact tag before it creates or sends any credential. const response = await environment.operations.protocol(null); expectStatus(response, 200, 'Credential-free protocol-tag preflight'); const preflight = decodeProtocolTagPreflight(response.body); invariant( Object.keys(preflight).length === 1 && preflight.protocol_version === PROTOCOL_VERSION, 'Protocol-tag preflight exposed more than the exact tag.', ); return { authenticated: false, protocol_version: preflight.protocol_version }; }); await record('enrollment.invitation-artifact', async () => { const errors: string[] = []; for (const vector of INVITATION_ARTIFACT_CONFORMANCE) { if (vector.expected === null) { let rejected = false; try { decodeInvitationArtifact(vector.input); } catch { rejected = true; } if (!rejected) errors.push(`${vector.name}: permissive decoder accepted the invalid artifact.`); continue; } try { const decoded = decodeInvitationArtifact(vector.input); invariant(same(decoded, vector.expected), `${vector.name} decoded a different artifact.`); } catch (error) { errors.push(`${vector.name}: ${error instanceof Error ? error.message : String(error)}`); } } invariant(errors.length === 0, errors.join(' | ')); return { vectors: INVITATION_ARTIFACT_CONFORMANCE.length }; }); await record('enrollment.retry-authority', async () => { const retryVectorErrors: string[] = []; for (const [index, vector] of ENROLLMENT_RETRY_CONFORMANCE.entries()) { for (const purpose of ['client', 'owner'] as const) { await environment.admin.reset(); try { const principal = await environment.admin.createPrincipal(`${purpose}-retry-vector-${index}`); const invitation = await environment.admin.issueSingleUseInvitation(principal, purpose); const initialPayload = { ...vector.initial, invitation }; const retryPayload = { ...vector.retry, invitation }; const initialResponse = await environment.operations.enroll( createProtocolEnvelope(`retry-${index}-initial`, initialPayload), ); expectStatus(initialResponse, 201, `${vector.name} initial request`); const initial = decodeEnrollmentExchangeResponseEnvelope(initialResponse.body).payload; invariant(initial.purpose === purpose, `${purpose} ${vector.name} returned the wrong purpose.`); invariant( same(initial.server_capabilities, purpose === 'owner' ? ['create_cube'] : []), `${purpose} ${vector.name} returned incorrect server authority.`, ); const retryResponse = await environment.operations.enroll( createProtocolEnvelope(`retry-${index}-retry`, retryPayload), ); if (vector.expected.outcome === 'stable_non_secret_identity') { expectStatus(retryResponse, 201, `${purpose} ${vector.name}`); const retry = decodeEnrollmentExchangeResponseEnvelope(retryResponse.body).payload; invariant(same(initial, retry), `${purpose} ${vector.name} returned different identities.`); for (const field of vector.expected.forbidden_response_fields) { invariant(!(field in retry), `${purpose} ${vector.name} returned forbidden field ${field}.`); } } else { expectError(retryResponse, vector.expected.status, ErrorCode.AUTH_INVALID, `${purpose} ${vector.name}`); assertEnrollmentErrorIsSecretFree( retryResponse, [initialPayload, retryPayload], `${purpose} ${vector.name}`, ); } const credentialProbeCube = await environment.admin.createCube(`${purpose}-credential-probe-${index}`); await environment.admin.grantCube(principal, credentialProbeCube, 'read'); expectStatus( await environment.operations.read( initialPayload.client_credential, credentialProbeCube, createProtocolEnvelope(`retry-${index}-credential-probe`, { cursor: null, limit: 1 }), ), 200, `${purpose} ${vector.name} original credential probe`, ); const capabilityProbe = await environment.operations.createCube( initialPayload.client_credential, createProtocolEnvelope(`retry-${index}-${purpose}-capability-probe`, { retry_key: `10000000-0000-4000-8000-${String(index + (purpose === 'owner' ? 700 : 600)).padStart(12, '0')}`, name: `${purpose} capability probe ${index}`, working_repo_name: `${purpose}-capability-probe-${index}`, repository: { kind: 'local', value: `20000000-0000-4000-8000-${String(index + (purpose === 'owner' ? 700 : 600)).padStart(12, '0')}`, }, template: 'software-dev', }), ); if (purpose === 'owner') { expectStatus(capabilityProbe, 201, `${purpose} ${vector.name} capability probe`); } else { expectError( capabilityProbe, 403, ErrorCode.ACCESS_DENIED, `${purpose} ${vector.name} capability probe`, ); } } catch (error) { retryVectorErrors.push( `${purpose} ${vector.name}: ${error instanceof Error ? error.message : String(error)}`, ); } } } invariant(retryVectorErrors.length === 0, retryVectorErrors.join(' | ')); await environment.admin.reset(); const ownerPrincipal = await environment.admin.createPrincipal('owner'); const ordinaryPrincipal = await environment.admin.createPrincipal('ordinary'); const ownerInvitation = await environment.admin.issueSingleUseInvitation(ownerPrincipal, 'owner'); const ordinaryInvitation = await environment.admin.issueSingleUseInvitation(ordinaryPrincipal, 'client'); const ownerCredential = `${'Q'.repeat(42)}U`; const ordinaryCredential = `${'Y'.repeat(42)}U`; const ownerResponse = await environment.operations.enroll(createProtocolEnvelope('owner-enroll', { invitation: ownerInvitation, retry_key: '00000000-0000-4000-8000-000000000211', client_credential: ownerCredential, client_name: 'owner-client', })); const ordinaryResponse = await environment.operations.enroll(createProtocolEnvelope('ordinary-enroll', { invitation: ordinaryInvitation, retry_key: '00000000-0000-4000-8000-000000000212', client_credential: ordinaryCredential, client_name: 'ordinary-client', })); expectStatus(ownerResponse, 201, 'Owner enrollment'); expectStatus(ordinaryResponse, 201, 'Ordinary enrollment'); const owner = decodeEnrollmentExchangeResponseEnvelope(ownerResponse.body).payload; const ordinary = decodeEnrollmentExchangeResponseEnvelope(ordinaryResponse.body).payload; invariant(owner.purpose === 'owner' && same(owner.server_capabilities, ['create_cube']), 'Owner enrollment lacked exact create-cube authority.'); invariant(ordinary.purpose === 'client' && ordinary.server_capabilities.length === 0, 'Ordinary enrollment gained authority.'); const cubeRequest = { retry_key: '00000000-0000-4000-8000-000000000213', name: 'Repository One', working_repo_name: 'repository-one', repository: { kind: 'origin' as const, value: 'https://github.com/Byte-Ventures/repository-one', }, template: 'software-dev', }; const droneCredential = await environment.admin.issueDroneSession(ownerPrincipal); expectSecretFreeError( await environment.operations.createCube(null, createProtocolEnvelope('cube-missing-auth', cubeRequest)), 401, ErrorCode.AUTH_MISSING, 'Missing-auth cube create', [cubeRequest.retry_key], ); expectSecretFreeError( await environment.operations.createCube('invalid-credential', createProtocolEnvelope('cube-invalid-auth', cubeRequest)), 401, ErrorCode.AUTH_INVALID, 'Invalid-auth cube create', [cubeRequest.retry_key], ); expectSecretFreeError( await environment.operations.createCube(ordinaryCredential, createProtocolEnvelope('cube-denied', cubeRequest)), 403, ErrorCode.ACCESS_DENIED, 'Ordinary cube create', [cubeRequest.retry_key], ); expectSecretFreeError( await environment.operations.createCube(droneCredential, createProtocolEnvelope('cube-drone-denied', cubeRequest)), 403, ErrorCode.ACCESS_DENIED, 'Drone-session cube create', [cubeRequest.retry_key], ); const createdResponse = await environment.operations.createCube(ownerCredential, createProtocolEnvelope('cube-create', cubeRequest)); expectStatus(createdResponse, 201, 'Owner cube create'); const created = decodeCreateCubeResponseEnvelope(createdResponse.body).payload; expectError( await environment.operations.createCube(ownerCredential, createProtocolEnvelope('cube-case-variant-duplicate', { ...cubeRequest, retry_key: '00000000-0000-4000-8000-000000000214', name: 'repository one', repository: { kind: 'origin' as const, value: 'https://github.com/Byte-Ventures/repository-one-case-variant', }, })), 409, ErrorCode.INVALID_INPUT, 'Same-owner case-variant cube name', ); const createdRoleProbes = new Map(); for (const [kind, roleId, roleClass, isHumanSeat, marker] of [ ['human-seat', created.human_seat_role_id, 'queen', true, 'H'], ['default-worker', created.default_worker_role_id, 'worker', false, 'D'], ] as const) { const sessionCredential = marker.repeat(43); const attached = await environment.operations.attach( ownerCredential, createProtocolEnvelope(`cube-create-${kind}-probe`, { cube_id: created.cube_id, role_id: roleId, session_credential: sessionCredential, }), ); expectStatus(attached, 200, `Created ${kind} role probe`); const attachedPayload = decodeAttachResponseEnvelope(attached.body).payload; const attachedRole = attachedPayload.role; invariant( attachedRole.id === roleId && attachedRole.role_class === roleClass && attachedRole.is_human_seat === isHumanSeat, `Created ${kind} role identity did not match its protocol role.`, ); createdRoleProbes.set(kind, { role: attachedRole, droneId: attachedPayload.drone.id, sessionCredential, }); } const retriedCreateResponse = await environment.operations.createCube(ownerCredential, createProtocolEnvelope('cube-retry', cubeRequest)); expectStatus(retriedCreateResponse, 201, 'Exact cube-create retry'); const retriedCreate = decodeCreateCubeResponseEnvelope(retriedCreateResponse.body).payload; invariant(retriedCreate.result === 'resolved', 'Exact cube-create retry did not report resolved readback.'); invariant( same({ ...retriedCreate, result: 'created' }, created), 'Exact cube-create retry returned different authoritative fields.', ); const displayRetryVector = CREATE_CUBE_RETRY_CONFORMANCE.find( (vector) => vector.expected.outcome === 'resolved_response' && vector.retry.working_repo_name !== vector.initial.working_repo_name, ); invariant(displayRetryVector !== undefined, 'Missing repository display readback vector.'); const displayRetryResponse = await environment.operations.createCube( ownerCredential, createProtocolEnvelope('cube-display-retry', { ...displayRetryVector.retry, retry_key: cubeRequest.retry_key, }), ); expectStatus(displayRetryResponse, 201, 'Changed repository display retry'); invariant( same(decodeCreateCubeResponseEnvelope(displayRetryResponse.body).payload, retriedCreate), 'Changed repository display retry did not return stored authoritative display.', ); for (const [index, vector] of CREATE_CUBE_RETRY_CONFORMANCE.entries()) { if (vector.expected.outcome !== 'retry_tuple_mismatch') continue; const mismatch = { ...vector.retry, retry_key: cubeRequest.retry_key }; expectSecretFreeError( await environment.operations.createCube( ownerCredential, createProtocolEnvelope(`cube-mismatch-${index}`, mismatch), ), 409, ErrorCode.INVALID_INPUT, `Cube-create ${vector.name}`, [cubeRequest.retry_key], ); } for (const [kind, roleId] of [ ['human-seat', created.human_seat_role_id], ['default-worker', created.default_worker_role_id], ] as const) { const initialProbe = createdRoleProbes.get(kind); invariant(initialProbe !== undefined, `Missing initial ${kind} role probe.`); const attached = await environment.operations.attach( ownerCredential, createProtocolEnvelope(`cube-create-${kind}-post-refusal-probe`, { cube_id: created.cube_id, role_id: roleId, session_credential: initialProbe.sessionCredential, prior_drone_id: initialProbe.droneId, }), ); expectStatus(attached, 200, `Post-refusal ${kind} role probe`); invariant( same(decodeAttachResponseEnvelope(attached.body).payload.role, initialProbe.role), `Cube-create retry refusal changed the full ${kind} role shape.`, ); } const sameAssociationVector = CREATE_CUBE_ASSOCIATION_CONFORMANCE.find( (vector) => vector.expected.outcome === 'resolved', ); invariant(sameAssociationVector !== undefined, 'Missing same-repository association vector.'); const associationResolveResponse = await environment.operations.createCube( ownerCredential, createProtocolEnvelope('cube-association-resolve', { ...sameAssociationVector.request, repository: cubeRequest.repository, }), ); expectStatus(associationResolveResponse, 201, 'Fresh retry for associated repository'); const associationResolved = decodeCreateCubeResponseEnvelope(associationResolveResponse.body).payload; invariant(associationResolved.result === 'resolved', 'Associated repository did not resolve.'); invariant( same({ ...associationResolved, result: 'created' }, created), 'Associated repository did not return stored authoritative fields.', ); await environment.admin.grantCreateCubeCapability(ordinaryPrincipal); const crossClientRequest = { ...cubeRequest, working_repo_name: 'ordinary-repository', repository: { kind: 'local' as const, value: '00000000-0000-4000-8000-000000000216', }, }; const crossClientResponse = await environment.operations.createCube( ordinaryCredential, createProtocolEnvelope('cube-cross-client', crossClientRequest), ); expectStatus(crossClientResponse, 201, 'Cross-client cube create with reused retry key'); const crossClientCreated = decodeCreateCubeResponseEnvelope(crossClientResponse.body).payload; invariant(crossClientCreated.cube_id !== created.cube_id, 'Cross-client retry key reused another client\'s cube.'); for (const [kind, roleId, originalRoleId, marker] of [ ['human-seat', crossClientCreated.human_seat_role_id, created.human_seat_role_id, 'V'], ['default-worker', crossClientCreated.default_worker_role_id, created.default_worker_role_id, 'W'], ] as const) { const originalProbe = createdRoleProbes.get(kind); invariant(originalProbe !== undefined, `Missing original ${kind} role probe.`); const attached = await environment.operations.attach( ordinaryCredential, createProtocolEnvelope(`cube-cross-client-${kind}-probe`, { cube_id: crossClientCreated.cube_id, role_id: roleId, session_credential: marker.repeat(43), }), ); expectStatus(attached, 200, `Cross-client ${kind} role probe`); const attachedRole = decodeAttachResponseEnvelope(attached.body).payload.role; invariant( same({ ...attachedRole, id: originalRoleId }, originalProbe.role), `Cross-client ${kind} role did not match the full template role shape.`, ); } const crossClientRetry = await environment.operations.createCube( ordinaryCredential, createProtocolEnvelope('cube-cross-client-retry', crossClientRequest), ); expectStatus(crossClientRetry, 201, 'Exact cross-client cube-create retry'); const crossClientResolved = decodeCreateCubeResponseEnvelope(crossClientRetry.body).payload; invariant( crossClientResolved.result === 'resolved', 'Exact cross-client cube-create retry did not report resolved readback.', ); invariant( same( { ...crossClientResolved, result: 'created' }, crossClientCreated, ), 'Exact cross-client cube-create retry returned different authoritative fields.', ); const differentAssociationVector = CREATE_CUBE_ASSOCIATION_CONFORMANCE.find( (vector) => vector.expected.outcome === 'created', ); invariant(differentAssociationVector !== undefined, 'Missing different-repository association vector.'); const secondCreatedResponse = await environment.operations.createCube( ownerCredential, createProtocolEnvelope('cube-create-second', differentAssociationVector.request), ); expectStatus(secondCreatedResponse, 201, 'Second cube create'); const secondCreated = decodeCreateCubeResponseEnvelope(secondCreatedResponse.body).payload; invariant(secondCreated.cube_id !== created.cube_id, 'Fresh cube-create retry key reused an existing cube.'); await environment.admin.revokePrincipal(ownerPrincipal); expectSecretFreeError( await environment.operations.createCube(ownerCredential, createProtocolEnvelope('cube-revoked', { ...cubeRequest, retry_key: '00000000-0000-4000-8000-000000000215', })), 401, ErrorCode.SESSION_REVOKED, 'Revoked owner cube create', ['00000000-0000-4000-8000-000000000215'], ); return { enrollment_status: 201, exact_retry_status: 201, mismatched_retry: ErrorCode.AUTH_INVALID, response_secret_free: true, }; }); try { await environment.admin.reset(); principalA = await environment.admin.createPrincipal('principal-a'); principalB = await environment.admin.createPrincipal('principal-b'); cubeA = await environment.admin.createCube('cube-a'); cubeB = await environment.admin.createCube('cube-b'); await environment.admin.grantCube(principalA, cubeA); await environment.admin.grantCube(principalB, cubeB); const invitationA = await environment.admin.issueSingleUseInvitation(principalA, 'client'); const invitationB = await environment.admin.issueSingleUseInvitation(principalB, 'client'); credentialA = 'A'.repeat(43); credentialB = 'E'.repeat(43); const enrolledAResponse = await environment.operations.enroll(createProtocolEnvelope('enroll-a1', { invitation: invitationA, retry_key: '00000000-0000-4000-8000-000000000201', client_credential: credentialA, client_name: 'conformance-a', })); const enrolledBResponse = await environment.operations.enroll(createProtocolEnvelope('enroll-b1', { invitation: invitationB, retry_key: '00000000-0000-4000-8000-000000000202', client_credential: credentialB, client_name: 'conformance-b', })); expectStatus(enrolledAResponse, 201, 'Shared principal A enrollment'); expectStatus(enrolledBResponse, 201, 'Shared principal B enrollment'); } catch (error) { prerequisiteFailures.set('shared.enrolled-principals', error instanceof Error ? error.message : String(error)); } await record('repository.explicit-association', async () => { const repository = { kind: 'origin' as const, value: 'https://github.com/Byte-Ventures/legacy-repository', }; const prepared = await environment.admin.prepareRepositoryCube(cubeA, { name: 'Legacy Repository Cube', template: 'software-dev', }); const resolveRequest = { working_repo_name: 'legacy-repository', repository, }; const alternateResolveRequest = { working_repo_name: 'other-repository', repository: { kind: 'origin' as const, value: 'https://github.com/Byte-Ventures/other-repository', }, }; const resolve = async (requestId: string, request: typeof resolveRequest) => { const response = await environment.operations.resolveRepositoryCube( credentialA, createProtocolEnvelope(requestId, request), ); expectStatus(response, 200, requestId); return decodeResolveRepositoryCubeResponseEnvelope(response.body).payload; }; const noneResponse = await environment.operations.resolveRepositoryCube( credentialA, createProtocolEnvelope('repository-resolve-none', resolveRequest), ); expectStatus(noneResponse, 200, 'Unassociated repository resolution'); invariant( same(decodeResolveRepositoryCubeResponseEnvelope(noneResponse.body).payload, { result: 'none' }), 'Unassociated repository did not return explicit none.', ); invariant( same(await resolve('repository-resolve-none-readback', resolveRequest), { result: 'none' }), 'Read-only repository resolution created an association.', ); const associationRequest = { cube_id: cubeA.id, ...resolveRequest }; expectSecretFreeError( await environment.operations.associateRepositoryCube( credentialB, createProtocolEnvelope('repository-associate-denied', associationRequest), ), 403, ErrorCode.ACCESS_DENIED, 'Inaccessible repository cube association', [associationRequest.cube_id, repository.value], ); const associatedResponse = await environment.operations.associateRepositoryCube( credentialA, createProtocolEnvelope('repository-associate', associationRequest), ); expectStatus(associatedResponse, 200, 'Explicit repository cube association'); const associated = decodeAssociateRepositoryCubeResponseEnvelope(associatedResponse.body).payload; const authoritative = { result: 'resolved' as const, cube_id: prepared.cube_id, name: prepared.name, working_repo_name: resolveRequest.working_repo_name, repository, template: prepared.template, human_seat_role_id: prepared.human_seat_role_id, default_worker_role_id: prepared.default_worker_role_id, access: prepared.access, }; invariant(same(associated, authoritative), 'Repository association did not return authoritative stored fields.'); const resolvedResponse = await environment.operations.resolveRepositoryCube( credentialA, createProtocolEnvelope('repository-resolve', { ...resolveRequest, working_repo_name: 'ignored-new-display', }), ); expectStatus(resolvedResponse, 200, 'Associated repository resolution'); invariant( same(decodeResolveRepositoryCubeResponseEnvelope(resolvedResponse.body).payload, authoritative), 'Associated repository did not return stored authoritative display.', ); const retryResponse = await environment.operations.associateRepositoryCube( credentialA, createProtocolEnvelope('repository-associate-retry', associationRequest), ); expectStatus(retryResponse, 200, 'Exact repository association retry'); invariant( same(decodeAssociateRepositoryCubeResponseEnvelope(retryResponse.body).payload, authoritative), 'Exact repository association retry changed authoritative fields.', ); const cubeC = await environment.admin.createCube('cube-c'); await environment.admin.grantCube(principalA, cubeC); await environment.admin.prepareRepositoryCube(cubeC, { name: 'Other Legacy Cube', template: 'starter', }); expectSecretFreeError( await environment.operations.associateRepositoryCube( credentialA, createProtocolEnvelope('repository-associate-repository-conflict', { ...associationRequest, cube_id: cubeC.id, }), ), 409, ErrorCode.REPOSITORY_ALREADY_ASSOCIATED, 'Repository-to-other-cube conflict', [cubeA.id, cubeC.id, repository.value], ); invariant( same(await resolve('repository-resolve-after-repository-conflict', resolveRequest), authoritative), 'Repository conflict changed the authoritative original binding.', ); invariant( same(await resolve('repository-resolve-alternate-after-repository-conflict', alternateResolveRequest), { result: 'none' }), 'Repository conflict created an alternate binding.', ); const alternateAssociationResponse = await environment.operations.associateRepositoryCube( credentialA, createProtocolEnvelope('repository-associate-second-repository', { cube_id: cubeA.id, ...alternateResolveRequest, }), ); expectStatus(alternateAssociationResponse, 200, 'Second repository association'); const alternateAuthoritative = decodeAssociateRepositoryCubeResponseEnvelope( alternateAssociationResponse.body, ).payload; invariant( same(await resolve('repository-resolve-after-second-association', resolveRequest), authoritative), 'Second repository association changed the authoritative original binding.', ); invariant( same( await resolve('repository-resolve-alternate-after-second-association', alternateResolveRequest), alternateAuthoritative, ), 'Second repository association was not observable.', ); const preparedB = await environment.admin.prepareRepositoryCube(cubeB, { name: 'Other Client Legacy Cube', template: 'starter', }); const crossClientResolve = await environment.operations.resolveRepositoryCube( credentialB, createProtocolEnvelope('repository-resolve-cross-client', resolveRequest), ); expectStatus(crossClientResolve, 200, 'Cross-client repository resolution'); invariant( same(decodeResolveRepositoryCubeResponseEnvelope(crossClientResolve.body).payload, { result: 'none' }), 'Another client repository binding was exposed by resolution.', ); const crossClientAssociation = await environment.operations.associateRepositoryCube( credentialB, createProtocolEnvelope('repository-associate-cross-client', { ...associationRequest, cube_id: cubeB.id, }), ); expectStatus(crossClientAssociation, 200, 'Cross-client repository association'); const crossClientAssociated = decodeAssociateRepositoryCubeResponseEnvelope( crossClientAssociation.body, ).payload; invariant( crossClientAssociated.cube_id === preparedB.cube_id && crossClientAssociated.repository.value === repository.value, 'Another client binding changed cross-client association identity.', ); await environment.admin.revokeCubeGrant(principalA, cubeA); const hiddenResolve = await environment.operations.resolveRepositoryCube( credentialA, createProtocolEnvelope('repository-resolve-inaccessible-binding', resolveRequest), ); expectStatus(hiddenResolve, 200, 'Inaccessible repository binding resolution'); invariant( same(decodeResolveRepositoryCubeResponseEnvelope(hiddenResolve.body).payload, { result: 'none' }), 'Inaccessible repository binding was exposed by read-only resolution.', ); expectSecretFreeError( await environment.operations.associateRepositoryCube( credentialA, createProtocolEnvelope('repository-associate-inaccessible-binding', { ...associationRequest, cube_id: cubeC.id, }), ), 403, ErrorCode.ACCESS_DENIED, 'Inaccessible existing repository binding', [cubeA.id, cubeC.id, repository.value], ); const hiddenAfterRefusal = await resolve('repository-resolve-after-inaccessible-refusal', resolveRequest); const alternateAfterRefusal = await resolve( 'repository-resolve-alternate-after-inaccessible-refusal', alternateResolveRequest, ); await environment.admin.grantCube(principalA, cubeA); invariant( same(hiddenAfterRefusal, { result: 'none' }), 'Inaccessible-binding refusal changed the hidden authoritative binding.', ); invariant( same(alternateAfterRefusal, { result: 'none' }), 'Inaccessible-binding refusal created an alternate binding.', ); invariant( same(await resolve('repository-resolve-restored-after-inaccessible-refusal', resolveRequest), authoritative), 'Inaccessible-binding refusal did not preserve the original binding.', ); return { none: true, resolved: true, idempotent: true, repository_conflict: ErrorCode.REPOSITORY_ALREADY_ASSOCIATED, multiple_repositories_per_cube: true, inaccessible: ErrorCode.ACCESS_DENIED, inaccessible_binding_hidden: true, cross_client_binding_hidden: true, }; }); await record('documents.lifecycle', async () => { const outcomes = new Map(); const documentPrincipal = await environment.admin.createPrincipal('document-lifecycle'); const documentCube = await environment.admin.createCube('document-lifecycle'); await environment.admin.grantCube(documentPrincipal, documentCube, 'write'); const documentCredential = await environment.admin.issueDroneSession(documentPrincipal); const reader = await environment.admin.createPrincipal('document-reader'); const peer = await environment.admin.createPrincipal('document-peer'); const manager = await environment.admin.createPrincipal('document-manager'); await environment.admin.grantCube(reader, documentCube, 'read'); await environment.admin.grantCube(peer, documentCube, 'write'); await environment.admin.grantCube(manager, documentCube, 'manage'); const readerCredential = await environment.admin.issueDroneSession(reader); const peerCredential = await environment.admin.issueDroneSession(peer); const managerCredential = await environment.admin.issueDroneSession(manager); const foreignPrincipal = await environment.admin.createPrincipal('document-foreign'); const foreignCube = await environment.admin.createCube('document-foreign'); await environment.admin.grantCube(foreignPrincipal, foreignCube, 'write'); const foreignCredential = await environment.admin.issueDroneSession(foreignPrincipal); const foreignPut = await environment.operations.putDocument( foreignCredential, foreignCube, createProtocolEnvelope('document-foreign-put', { title: 'Foreign evidence', content_type: 'text/plain', content: 'Foreign immutable content.', }), ); expectStatus(foreignPut, 201, 'Foreign document put'); const foreignDocument = decodePutDocumentResultEnvelope(foreignPut.body).payload.document; expectError(await environment.operations.putDocument( readerCredential, documentCube, createProtocolEnvelope('document-read-only-put', { title: 'Denied', content_type: 'text/plain', content: 'denied' }), ), 403, ErrorCode.ACCESS_DENIED, 'Read-only document put'); expectError(await environment.operations.putDocument( documentCredential, documentCube, createProtocolEnvelope('document-bad-type', { title: 'Binary', content_type: 'application/octet-stream', content: 'x' }), ), 400, ErrorCode.DOCUMENT_CONTENT_TYPE_UNSUPPORTED, 'Unsupported document type'); outcomes.set('unsupported-content-type', ErrorCode.DOCUMENT_CONTENT_TYPE_UNSUPPORTED); expectError(await environment.operations.putDocument( documentCredential, documentCube, createProtocolEnvelope('document-bad-title', { title: 'x'.repeat(121), content_type: 'text/plain', content: 'x' }), ), 400, ErrorCode.INVALID_INPUT, 'Oversized document title'); outcomes.set('oversize-title', ErrorCode.INVALID_INPUT); expectError(await environment.operations.putDocument( documentCredential, documentCube, createProtocolEnvelope('document-oversize', { title: 'Too large', content_type: 'text/plain', content: 'x'.repeat(65_537) }), ), 413, ErrorCode.DOCUMENT_BUDGET_EXCEEDED, 'Oversized document'); const budgetCube = await environment.admin.createCube('document-budget'); await environment.admin.grantCube(documentPrincipal, budgetCube, 'write'); let budgetPredecessor: CubeDocument | undefined; for (let index = 0; index < 8; index++) { const response = await environment.operations.putDocument( documentCredential, budgetCube, createProtocolEnvelope(`document-budget-${index}`, { title: `Budget ${index}`, content_type: 'text/plain', content: 'x'.repeat(65_536), }), ); expectStatus(response, 201, `Document budget fill ${index}`); if (index === 0) budgetPredecessor = decodePutDocumentResultEnvelope(response.body).payload.document; } invariant(budgetPredecessor !== undefined, 'Budget predecessor was not created.'); expectError(await environment.operations.putDocument( documentCredential, budgetCube, createProtocolEnvelope('document-budget-overflow', { title: 'Overflow', content_type: 'text/plain', content: 'x', supersedes: budgetPredecessor.id, }), ), 413, ErrorCode.DOCUMENT_BUDGET_EXCEEDED, 'Active document budget'); const budgetList = decodeListDocumentsResultEnvelope((await environment.operations.listDocuments( documentCredential, budgetCube, createProtocolEnvelope('document-budget-list', {}), )).body).payload.documents; invariant(budgetList.length === 8, 'Budget refusal partially mutated the document set.'); const budgetRetained = decodeGetDocumentResultEnvelope((await environment.operations.getDocument( documentCredential, budgetCube, createProtocolEnvelope('document-budget-get-predecessor', { id: budgetPredecessor.id }), )).body).payload.document; invariant( budgetRetained.state === 'active' && budgetRetained.superseded_by === null && budgetRetained.content === budgetPredecessor.content, 'Budget refusal partially mutated its predecessor.', ); expectError(await environment.operations.putDocument( documentCredential, documentCube, createProtocolEnvelope('document-unknown-supersedes', { title: 'Unknown', content_type: 'text/plain', content: 'x', supersedes: 'unknown_full_id' }), ), 409, ErrorCode.DOCUMENT_SUPERSESSION_INVALID, 'Unknown document supersession'); outcomes.set('foreign-supersedes', ErrorCode.DOCUMENT_SUPERSESSION_INVALID); const put = await environment.operations.putDocument( documentCredential, documentCube, createProtocolEnvelope('document-put', { title: 'Review evidence', content_type: 'text/markdown', content: '# Evidence\n\nPortable UTF-8: €\n', }), ); expectStatus(put, 201, 'Document put'); const created = decodePutDocumentResultEnvelope(put.body).payload.document; outcomes.set('markdown', 'created'); invariant(created.size_bytes === utf8ByteLength(created.content), 'Document size is not its UTF-8 byte size.'); expectSecretFreeError(await environment.operations.getDocument( documentCredential, documentCube, createProtocolEnvelope('document-foreign-get', { id: foreignDocument.id }), ), 404, ErrorCode.DOCUMENT_NOT_FOUND, 'Foreign document get', [foreignDocument.title, foreignDocument.content]); expectSecretFreeError(await environment.operations.listDocuments( documentCredential, foreignCube, createProtocolEnvelope('document-foreign-list', {}), ), 404, ErrorCode.NOT_FOUND, 'Foreign document list', [foreignDocument.title, foreignDocument.content]); expectSecretFreeError(await environment.operations.removeDocument( documentCredential, documentCube, createProtocolEnvelope('document-foreign-remove', { id: foreignDocument.id }), ), 404, ErrorCode.DOCUMENT_NOT_FOUND, 'Foreign document remove', [foreignDocument.title, foreignDocument.content]); const entriesBeforeForeignCitation = decodeReadLogResultEnvelope((await environment.operations.read( documentCredential, documentCube, createProtocolEnvelope('document-read-before-foreign-cite', { cursor: null, limit: 100 }), )).body).payload.entries.length; expectSecretFreeError(await environment.operations.append( documentCredential, documentCube, createProtocolEnvelope('document-foreign-citation', { post_id: '00000000-0000-4000-8000-00000000031f', to: 'broadcast', message: 'Foreign evidence must remain hidden.', documents: [foreignDocument.id], }), ), 404, ErrorCode.DOCUMENT_NOT_FOUND, 'Foreign document citation', [foreignDocument.title, foreignDocument.content]); const entriesAfterForeignCitation = decodeReadLogResultEnvelope((await environment.operations.read( documentCredential, documentCube, createProtocolEnvelope('document-read-after-foreign-cite', { cursor: null, limit: 100 }), )).body).payload.entries.length; invariant(entriesAfterForeignCitation === entriesBeforeForeignCitation, 'Denied foreign citation mutated the log.'); const successorResponse = await environment.operations.putDocument( documentCredential, documentCube, createProtocolEnvelope('document-put-successor', { title: 'Review evidence revision 2', content_type: 'text/markdown', content: '# Revised evidence\n', supersedes: created.id, }), ); expectStatus(successorResponse, 201, 'Document successor put'); const successor = decodePutDocumentResultEnvelope(successorResponse.body).payload.document; invariant(successor.supersedes === created.id, 'Document successor did not bind the full prior id.'); expectError(await environment.operations.putDocument( documentCredential, documentCube, createProtocolEnvelope('document-branch', { title: 'Branch', content_type: 'text/plain', content: 'x', supersedes: created.id }), ), 409, ErrorCode.DOCUMENT_SUPERSESSION_INVALID, 'Branched document supersession'); outcomes.set('branched-supersedes', ErrorCode.DOCUMENT_SUPERSESSION_INVALID); expectError(await environment.operations.putDocument( credentialA, cubeA, createProtocolEnvelope('document-cross-cube', { title: 'Cross cube', content_type: 'text/plain', content: 'x', supersedes: created.id }), ), 409, ErrorCode.DOCUMENT_SUPERSESSION_INVALID, 'Cross-cube document supersession'); const citationResponse = await environment.operations.append( documentCredential, documentCube, createProtocolEnvelope('document-citation', { post_id: '00000000-0000-4000-8000-000000000320', to: 'broadcast', message: 'See the document evidence.', documents: [created.id, successor.id], }), ); expectStatus(citationResponse, 201, 'Document citation append'); const cited = decodeAppendLogResultEnvelope(citationResponse.body).payload.entry.documents; invariant(cited?.length === 2 && cited[0].state === 'superseded', 'Log citations did not render document metadata and state.'); expectError(await environment.operations.append( documentCredential, documentCube, createProtocolEnvelope('document-citation-conflict', { post_id: '00000000-0000-4000-8000-000000000320', to: 'broadcast', message: 'See the document evidence.', documents: [successor.id], }), ), 409, ErrorCode.POST_ID_CONFLICT, 'Document citation post-id conflict'); const listed = await environment.operations.listDocuments( readerCredential, documentCube, createProtocolEnvelope('document-list', {}), ); expectStatus(listed, 200, 'Document list'); const list = decodeListDocumentsResultEnvelope(listed.body).payload.documents; invariant( list.length === 2 && list.some(({ id, state, superseded_by }) => id === created.id && state === 'superseded' && superseded_by === successor.id), 'Linear document supersession was not listed by full ids.', ); invariant(!('content' in list[0]), 'Document list exposed immutable content.'); invariant(!list.some(({ id }) => id === foreignDocument.id), 'Document list leaked a foreign document.'); expectStatus(await environment.operations.getDocument( readerCredential, documentCube, createProtocolEnvelope('document-reader-get', { id: created.id }), ), 200, 'Read-only document get'); expectError(await environment.operations.removeDocument( readerCredential, documentCube, createProtocolEnvelope('document-reader-remove', { id: created.id }), ), 403, ErrorCode.DOCUMENT_REMOVE_DENIED, 'Read-only document remove'); expectError(await environment.operations.removeDocument( peerCredential, documentCube, createProtocolEnvelope('document-peer-remove', { id: created.id }), ), 403, ErrorCode.DOCUMENT_REMOVE_DENIED, 'Peer document remove'); outcomes.set('peer-remove', ErrorCode.DOCUMENT_REMOVE_DENIED); const authorDocumentResponse = await environment.operations.putDocument( documentCredential, documentCube, createProtocolEnvelope('document-author-put', { title: 'Author removable', content_type: 'text/plain', content: 'Author content.', }), ); expectStatus(authorDocumentResponse, 201, 'Author document put'); outcomes.set('plain', 'created'); const authorDocument = decodePutDocumentResultEnvelope(authorDocumentResponse.body).payload.document; expectStatus(await environment.operations.removeDocument( documentCredential, documentCube, createProtocolEnvelope('document-author-remove', { id: authorDocument.id }), ), 200, 'Author document remove'); const got = await environment.operations.getDocument( documentCredential, documentCube, createProtocolEnvelope('document-get', { id: created.id }), ); expectStatus(got, 200, 'Document get'); invariant( decodeGetDocumentResultEnvelope(got.body).payload.document.content === created.content, 'Document get did not preserve immutable content and metadata.', ); const removed = await environment.operations.removeDocument( managerCredential, documentCube, createProtocolEnvelope('document-remove', { id: created.id }), ); expectStatus(removed, 200, 'Document remove'); invariant( decodeRemoveDocumentResultEnvelope(removed.body).payload.document.state === 'removed', 'Document removal did not produce audit-retained removed state.', ); const afterResponse = await environment.operations.listDocuments( readerCredential, documentCube, createProtocolEnvelope('document-list-after', {}), ); expectStatus(afterResponse, 200, 'Read-only document list after removal'); const after = decodeListDocumentsResultEnvelope(afterResponse.body).payload.documents; invariant(after.length === 1 && after[0].id === successor.id, 'Removed document remained in active listing.'); const retainedResponse = await environment.operations.getDocument( readerCredential, documentCube, createProtocolEnvelope('document-get-removed', { id: created.id }), ); expectStatus(retainedResponse, 200, 'Read-only audit-retained document get'); const retained = decodeGetDocumentResultEnvelope(retainedResponse.body).payload.document; invariant(retained.state === 'removed' && retained.content === created.content, 'Removed content was not forensically resolvable.'); const foreignRetained = decodeGetDocumentResultEnvelope((await environment.operations.getDocument( foreignCredential, foreignCube, createProtocolEnvelope('document-foreign-retained', { id: foreignDocument.id }), )).body).payload.document; invariant( foreignRetained.state === 'active' && foreignRetained.content === foreignDocument.content, 'Denied foreign operations leaked mutation into the foreign document.', ); outcomes.set('removed', 'audit-resolvable'); const entriesBeforeUnknownCitation = (await environment.operations.read( documentCredential, documentCube, createProtocolEnvelope('document-read-before-unknown-cite', { cursor: null, limit: 100 }), )); const beforeCount = decodeReadLogResultEnvelope(entriesBeforeUnknownCitation.body).payload.entries.length; expectError(await environment.operations.append( documentCredential, documentCube, createProtocolEnvelope('document-unknown-citation', { post_id: '00000000-0000-4000-8000-000000000321', message: 'Unknown.', to: 'broadcast', documents: ['unknown_full_id'], }), ), 404, ErrorCode.DOCUMENT_NOT_FOUND, 'Unknown document citation'); const longAccepted = await environment.operations.append( documentCredential, documentCube, createProtocolEnvelope('document-advisory', { post_id: '00000000-0000-4000-8000-000000000322', message: 'x'.repeat(1025), to: 'broadcast', }), ); expectStatus(longAccepted, 201, 'Advisory log append'); invariant(decodeAppendLogResultEnvelope(longAccepted.body).payload.advisory?.threshold_bytes === 1024, 'Configured advisory was not returned.'); expectError(await environment.operations.append( documentCredential, documentCube, createProtocolEnvelope('document-hard-cap', { post_id: '00000000-0000-4000-8000-000000000323', message: 'x'.repeat(4097), to: 'broadcast', }), ), 413, ErrorCode.CONTENT_TOO_LARGE, 'Hard-cap log append'); const citedRead = decodeReadLogResultEnvelope((await environment.operations.read( documentCredential, documentCube, createProtocolEnvelope('document-citation-read', { cursor: null, limit: 10 }), )).body).payload.entries[0].documents; invariant(citedRead?.[0].state === 'removed', 'Log citation did not resolve the audit-retained removed state.'); const finalCount = decodeReadLogResultEnvelope((await environment.operations.read( documentCredential, documentCube, createProtocolEnvelope('document-final-read', { cursor: null, limit: 100 }), )).body).payload.entries.length; invariant(finalCount === beforeCount + 1, 'Rejected document or log operations partially mutated state.'); for (const vector of DOCUMENT_CONFORMANCE) { invariant( outcomes.get(vector.fixture) === vector.expected, `${vector.name} produced ${outcomes.get(vector.fixture) ?? 'no outcome'}; expected ${vector.expected}.`, ); } return { refusals: true, put: 201, cited: true, active_listed: true, removed_hidden: true, audit_resolvable: true }; }); await record('security.adapter-boundary-injection', async () => { const injectedMessage = "'); DROP TABLE log_entries; --\r\ndata: forged-sse-frame"; const injectedBody = JSON.stringify( createProtocolEnvelope('inject-b1', { post_id: '00000000-0000-4000-8000-000000000301', to: 'broadcast', message: injectedMessage, }), ); invariant( utf8ByteLength(injectedBody) <= PROTOCOL_LIMIT_CEILINGS.max_request_bytes && utf8ByteLength(injectedMessage) <= PROTOCOL_LIMIT_CEILINGS.max_log_message_bytes, 'Injection fixture exceeded the shared request-limit ceiling.', ); const injected = await environment.operations.appendRaw( credentialB, cubeB, injectedBody, ); expectStatus(injected, 201, 'Adapter-boundary injection append'); const injectedEntry = decodeAppendLogResultEnvelope(injected.body).payload.entry; invariant(injectedEntry.message === injectedMessage, 'Adapter altered or interpreted injection-shaped log data.'); const sentinel = await environment.operations.append( credentialB, cubeB, createProtocolEnvelope('inject-b2', { post_id: '00000000-0000-4000-8000-000000000302', to: 'broadcast', message: 'post-injection-sentinel', }), ); expectStatus(sentinel, 201, 'Post-injection sentinel append'); const read = await environment.operations.read( credentialB, cubeB, createProtocolEnvelope('inject-read', { cursor: null, limit: 10 }), ); expectStatus(read, 200, 'Post-injection read'); const messages = decodeReadLogResultEnvelope(read.body).payload.entries.map((entry) => entry.message); invariant( same(messages, [injectedMessage, 'post-injection-sentinel']), 'Injection-shaped input was not persisted inertly and exactly.', ); const opened = await environment.operations.openStream(credentialB, cubeB, null); expectStatus(opened, 200, 'Post-injection stream open'); invariant(opened.stream, 'Post-injection stream omitted its AsyncIterable.'); const reader = new SseEventReader(opened.stream); try { const first = logEvent( await within(reader.next(), 'Injected SSE event', streamDeadlineMs), 'Injected SSE event', ); const second = logEvent( await within(reader.next(), 'Post-injection sentinel SSE event', streamDeadlineMs), 'Post-injection sentinel SSE event', ); invariant( first.entry.message === injectedMessage && second.entry.message === 'post-injection-sentinel', 'Injection-shaped input escaped or split its SSE frame.', ); const bookmark = await within(reader.next(), 'Post-injection bookmark', streamDeadlineMs); invariant(bookmark.type === 'bookmark', 'Post-injection stream produced an extra forged event.'); } finally { await reader.close(); } return { status: 201, preserved_exactly: true, subsequent_write_succeeded: true, ordered_messages: 2, sse_events: 2, }; }); await record('security.oversize-request', async () => { const baseBody = JSON.stringify( createProtocolEnvelope('oversize-a1', { post_id: '00000000-0000-4000-8000-000000000303', to: 'broadcast', message: 'must-not-persist', }), ); const oversizedBody = baseBody + ' '.repeat( Math.max(0, PROTOCOL_LIMIT_CEILINGS.max_request_bytes - utf8ByteLength(baseBody) + 1), ); invariant( utf8ByteLength(oversizedBody) > PROTOCOL_LIMIT_CEILINGS.max_request_bytes, 'Oversize fixture did not exceed max_request_bytes.', ); const response = await environment.operations.appendRaw(credentialA, cubeA, oversizedBody); expectError(response, 413, ErrorCode.CONTENT_TOO_LARGE, 'Oversized append request'); const read = await environment.operations.read( credentialA, cubeA, createProtocolEnvelope('oversize-read', { cursor: null, limit: 10 }), ); expectStatus(read, 200, 'Post-oversize read'); invariant( decodeReadLogResultEnvelope(read.body).payload.entries.length === 0, 'Oversized request was persisted before rejection.', ); return { status: 413, code: ErrorCode.CONTENT_TOO_LARGE, persisted_entries: 0 }; }); await record('security.cross-cube-isolation', async () => { const secretAppend = await environment.operations.append( credentialB, cubeB, createProtocolEnvelope('append-b1', { post_id: '00000000-0000-4000-8000-000000000304', message: 'principal-b-secret', to: 'broadcast', }), ); expectStatus(secretAppend, 201, 'Principal B append'); const denied = await environment.operations.read( credentialA, cubeB, createProtocolEnvelope('read-cross', { cursor: null, limit: 10 }), ); expectError(denied, 404, ErrorCode.NOT_FOUND, 'Cross-cube read'); return { status: 404, code: ErrorCode.NOT_FOUND }; }); await record('log.append-idempotency', async () => { const principal = await environment.admin.createPrincipal('append-idempotency'); const otherPrincipal = await environment.admin.createPrincipal('append-idempotency-other'); const cube = await environment.admin.createCube('append-idempotency'); await environment.admin.grantCube(principal, cube); await environment.admin.grantCube(otherPrincipal, cube); const credential = await environment.admin.issueDroneSession(principal); const otherCredential = await environment.admin.issueDroneSession(otherPrincipal); const role = await environment.admin.createRole(cube, { roleClass: 'worker', isHumanSeat: false, }); const firstRecipient = await environment.admin.createDrone(principal, cube, role); const secondRecipient = await environment.admin.createDrone(principal, cube, role); const postId = '00000000-0000-4000-8000-000000000313'; const initialPayload = { post_id: postId, message: 'once', to: [firstRecipient.id], class: 'review', }; const first = await environment.operations.append( credential, cube, createProtocolEnvelope('append-idempotency-first', initialPayload), ); expectStatus(first, 201, 'Initial idempotent append'); const firstResult = decodeAppendLogResultEnvelope(first.body).payload; invariant(!firstResult.deduplicated, 'Initial append was reported as deduplicated.'); for (const [index, vector] of APPEND_LOG_IDEMPOTENCY_CONFORMANCE.entries()) { const payload = { ...initialPayload, ...(vector.mutation === 'message' ? { message: 'changed' } : {}), ...(vector.mutation === 'audience' ? { to: 'broadcast' as const } : {}), ...(vector.mutation === 'recipient_set' ? { to: [secondRecipient.id] } : {}), ...(vector.mutation === 'classification' ? { class: 'security' } : {}), }; const response = await environment.operations.append( vector.actor === 'same' ? credential : otherCredential, cube, createProtocolEnvelope(`append-idempotency-${index}`, payload), ); if (vector.expected === 'POST_ID_CONFLICT') { expectError(response, 409, ErrorCode.POST_ID_CONFLICT, vector.name); continue; } expectStatus(response, 201, vector.name); const result = decodeAppendLogResultEnvelope(response.body).payload; invariant(result.deduplicated === (vector.expected === 'deduplicated'), `${vector.name} returned the wrong deduplicated flag.`); invariant( vector.expected === 'deduplicated' ? result.entry.id === firstResult.entry.id : result.entry.id !== firstResult.entry.id, `${vector.name} returned the wrong entry identity.`, ); } const read = await environment.operations.read( credential, cube, createProtocolEnvelope('append-idempotency-read', { cursor: null, limit: 10 }), ); expectStatus(read, 200, 'Idempotent append read'); invariant( decodeReadLogResultEnvelope(read.body).payload.entries.length === 2, 'Append collision controls persisted the wrong number of entries.', ); return { persisted_entries: 2, stable_entry: true, deduplicated: true, conflicts: 3, cross_author_created: true }; }); await record('log.mandatory-addressing', async () => { const cube = await environment.admin.createCube('mandatory-addressing-cube'); await environment.admin.grantCube(principalA, cube); const role = await environment.admin.createRole(cube, { roleClass: 'worker', isHumanSeat: false, name: 'Structured Recipient', }); const recipient = await environment.admin.createDrone(principalA, cube, role); const message = 'START NOW exact slice'; expectError( await environment.operations.append( credentialA, cube, createProtocolEnvelope('mandatory-addressing-omitted', { post_id: '30000000-0000-4000-8000-000000000001', message, }), ), 400, ErrorCode.INVALID_INPUT, 'Omitted mandatory addressing', ); const broadcast = await environment.operations.append( credentialA, cube, createProtocolEnvelope('mandatory-addressing-broadcast', { post_id: '30000000-0000-4000-8000-000000000002', message, to: 'broadcast', }), ); expectStatus(broadcast, 201, 'Explicit broadcast addressing'); const broadcastResult = decodeAppendLogResultEnvelope(broadcast.body).payload; invariant(broadcastResult.entry.visibility === 'broadcast', 'Scalar broadcast did not produce broadcast visibility.'); invariant( (broadcastResult.entry.recipient_drone_ids?.length ?? 0) === 0, 'Scalar broadcast unexpectedly resolved direct recipients.', ); const directed = await environment.operations.append( credentialA, cube, createProtocolEnvelope('mandatory-addressing-directed', { post_id: '30000000-0000-4000-8000-000000000003', message, to: [recipient.id], class: 'cube-wide', }), ); expectStatus(directed, 201, 'Recipient-selector union branch'); const directedResult = decodeAppendLogResultEnvelope(directed.body).payload; invariant(directedResult.entry.visibility === 'direct', 'Explicit recipient selectors did not produce direct visibility.'); invariant( directedResult.entry.recipient_drone_ids?.includes(recipient.id) === true, 'Explicit recipient selectors did not resolve the named recipient.', ); invariant( directedResult.entry.recipient_drone_ids?.length === 1, 'Classification changed or fell open the explicit recipient set.', ); const readback = await environment.operations.read( credentialA, cube, createProtocolEnvelope('mandatory-addressing-readback', { cursor: null, limit: 10 }), ); expectStatus(readback, 200, 'Mandatory-addressing persistence readback'); const persistedIds = decodeReadLogResultEnvelope(readback.body).payload.entries.map((entry) => entry.id); invariant( same(persistedIds, [broadcastResult.entry.id, directedResult.entry.id]), 'Rejected mandatory-addressing append was persisted.', ); return { refused_status: 400, code: ErrorCode.INVALID_INPUT, persisted: false, broadcast: true, union: true, no_fall_open: true }; }); await record('log.entry-query', async () => { const cube = await environment.admin.createCube('entry-query-cube'); await environment.admin.grantCube(principalA, cube); const role = await environment.admin.createRole(cube, { roleClass: 'worker', isHumanSeat: false, name: 'Entry Query Worker', }); const acknowledgedRecipient = await environment.admin.createDrone(principalA, cube, role); const claimingRecipient = await environment.admin.createDrone(principalA, cube, role); const acknowledgedCredential = await environment.admin.issueManagedDroneSession(acknowledgedRecipient); const claimingCredential = await environment.admin.issueManagedDroneSession(claimingRecipient); const ids = [ '11111111-0000-4000-8000-000000000001', '22222222-0000-4000-8000-000000000001', '22222222-0000-4000-8000-000000000002', ]; const entries: EnrichedStreamEntry[] = []; const idSeeds: Array<{ current_id: string; query_id: string }> = []; for (const [index, id] of ids.entries()) { const response = await environment.operations.append( credentialA, cube, createProtocolEnvelope(`entry-query-append-${index}`, { post_id: `40000000-0000-4000-8000-00000000000${index}`, to: [acknowledgedRecipient.id, claimingRecipient.id], message: `entry-query-${index}`, }), ); expectStatus(response, 201, `Entry-query fixture append ${index}`); const entry = decodeAppendLogResultEnvelope(response.body).payload.entry; idSeeds.push({ current_id: entry.id, query_id: id }); entries.push({ ...entry, id }); } await environment.admin.seedEntryQueryIds(cube, idSeeds); expectStatus( await environment.operations.ack( acknowledgedCredential, cube, createProtocolEnvelope('entry-query-seed-ack', { entry_id: ids[0], kind: 'ack' }), ), 204, 'Entry-query acknowledgement seed', ); expectStatus( await environment.operations.ack( claimingCredential, cube, createProtocolEnvelope('entry-query-seed-claim', { entry_id: ids[1], kind: 'claim' }), ), 204, 'Entry-query claim seed', ); for (const [requestId, selector, expectedId] of [ ['entry-query-full', ids[1], ids[1]], ['entry-query-prefix', '11111111', ids[0]], ] as const) { const response = await environment.operations.entryQuery( credentialA, cube, createProtocolEnvelope(requestId, { entry_id: selector }), ); expectStatus(response, 200, requestId); const result = decodeEntryQueryResultEnvelope(response.body).payload; invariant(result.entry.id === expectedId, `${requestId} returned the wrong entry.`); } expectError( await environment.operations.entryQuery( credentialA, cube, createProtocolEnvelope('entry-query-unknown', { entry_id: 'ffffffff' }), ), 404, ErrorCode.NOT_FOUND, 'Unknown entry query', ); expectError( await environment.operations.entryQuery( credentialA, cube, createProtocolEnvelope('entry-query-ambiguous', { entry_id: '22222222' }), ), 409, ErrorCode.LOG_ENTRY_PREFIX_AMBIGUOUS, 'Ambiguous entry query', ); const acknowledgementStatus = decodeAckStatusResultEnvelope((await environment.operations.ackStatus( credentialA, cube, createProtocolEnvelope('entry-query-ack-status', { entry_id: ids[0] }), )).body).payload; const claimStatus = decodeAckStatusResultEnvelope((await environment.operations.ackStatus( credentialA, cube, createProtocolEnvelope('entry-query-claim-status', { entry_id: ids[1] }), )).body).payload; const acknowledgedRecipients = acknowledgementStatus.recipients.filter( (recipient) => recipient.acknowledged_at !== null, ); invariant( acknowledgedRecipients.length === 1 && acknowledgedRecipients[0].drone_id === acknowledgedRecipient.id && acknowledgementStatus.recipients.find( (recipient) => recipient.drone_id === claimingRecipient.id, )?.acknowledged_at === null, 'Entry query changed the seeded acknowledgement set.', ); invariant( claimStatus.claims.length === 1 && claimStatus.claims[0].drone_id === claimingRecipient.id && claimStatus.recipients.every((recipient) => recipient.acknowledged_at === null), 'Entry query changed the seeded claim or acknowledgement set.', ); const unreadResponse = await environment.operations.read( credentialA, cube, createProtocolEnvelope('entry-query-unread', { cursor: null, limit: 10 }), ); expectStatus(unreadResponse, 200, 'Entry-query unread read'); const unread = decodeReadLogResultEnvelope(unreadResponse.body).payload; invariant( same(unread.entries, entries), 'Entry query mutated, consumed, or advanced unread activity.', ); return { full_uuid: true, unique_prefix: true, ambiguous_code: ErrorCode.LOG_ENTRY_PREFIX_AMBIGUOUS, unknown_code: ErrorCode.NOT_FOUND, unread_entry_available: true, acknowledgement_preserved: true, claim_preserved: true, mutation: 'none', }; }); await record('log.read-cursor-tuple', async () => { const entries: Array<{ id: string; created_at: string; message: string }> = []; for (const [index, message] of ['alpha', 'beta', 'gamma'].entries()) { const response = await environment.operations.append( credentialA, cubeA, createProtocolEnvelope(`append-a${index + 1}`, { post_id: `00000000-0000-4000-8000-${String(305 + index).padStart(12, '0')}`, to: 'broadcast', message, }), ); expectStatus(response, 201, `Append ${message}`); const entry = decodeAppendLogResultEnvelope(response.body).payload.entry; entries.push({ id: entry.id, created_at: entry.created_at, message: entry.message }); } const response = await environment.operations.read( credentialA, cubeA, createProtocolEnvelope('read-page1', { cursor: null, limit: 2 }), ); expectStatus(response, 200, 'First paged read'); const page = decodeReadLogResultEnvelope(response.body).payload; invariant(same(page.entries.map((entry) => entry.message), ['alpha', 'beta']), 'Read did not honor limit and tuple ordering.'); invariant(page.has_more && page.behind_by === 1, 'Read pagination metadata is incorrect.'); invariant(page.cursor !== null, 'Read did not return a cursor.'); invariant( page.cursor.id === entries[1].id && page.cursor.created_at === entries[1].created_at, 'Read cursor does not equal the final delivered entry tuple.', ); return { messages: ['alpha', 'beta'], has_more: true, behind_by: 1, cursor_matches_last_entry: true }; }); await record('sse.replay-live-transition', async () => { const principal = await environment.admin.createPrincipal('stream-transition'); const cube = await environment.admin.createCube('stream-transition'); await environment.admin.grantCube(principal, cube); const credential = await environment.admin.issueDroneSession(principal); let readCursor!: LogCursor; for (const [index, message] of ['alpha', 'beta', 'gamma'].entries()) { const response = await environment.operations.append( credential, cube, createProtocolEnvelope(`stream-transition-${message}`, { post_id: `00000000-0000-4000-8000-${String(316 + index).padStart(12, '0')}`, to: 'broadcast', message, }), ); expectStatus(response, 201, `Stream transition append ${message}`); if (message === 'beta') { const entry = decodeAppendLogResultEnvelope(response.body).payload.entry; readCursor = { id: entry.id, created_at: entry.created_at }; } } const barrier = environment.admin.armReplayTransition(); const openPromise = environment.operations.openStream(credential, cube, readCursor); await within(barrier.reached, 'Replay transition boundary', streamDeadlineMs); try { const appendDelta = environment.operations.append( credential, cube, createProtocolEnvelope('stream-transition-delta', { post_id: '00000000-0000-4000-8000-000000000319', to: 'broadcast', message: 'delta', }), ); expectStatus(await appendDelta, 201, 'Transition append'); } finally { barrier.release(); } const opened = await within(openPromise, 'Cursor stream open', streamDeadlineMs); expectStatus(opened, 200, 'Cursor stream open'); invariant(opened.stream, 'Successful stream response omitted its AsyncIterable.'); const reader = new SseEventReader(opened.stream); try { const replay = logEvent(await within(reader.next(), 'Replay event', streamDeadlineMs), 'Replay'); invariant(replay.entry.message === 'gamma', 'Stream ignored its cursor or replayed the wrong entry.'); invariant(compareLogCursor(readCursor, replay.cursor) < 0, 'Replay cursor did not advance.'); const delta = logEvent(await within(reader.next(), 'Transition delta event', streamDeadlineMs), 'Replay transition'); invariant(delta.entry.message === 'delta', 'Entry appended at the replay/live boundary was lost.'); invariant(compareLogCursor(replay.cursor, delta.cursor) < 0, 'Transition cursor did not advance.'); const bookmark = await within(reader.next(), 'Replay-complete bookmark', streamDeadlineMs); invariant(bookmark.type === 'bookmark' && bookmark.replay_complete, 'Stream omitted its replay-complete bookmark.'); const noDuplicate = reader.next(); await provePending(noDuplicate, 'Live stream after delta', pendingProbeMs); const epsilonResponse = await environment.operations.append( credential, cube, createProtocolEnvelope('stream-transition-epsilon', { post_id: '00000000-0000-4000-8000-000000000320', to: 'broadcast', message: 'epsilon', }), ); expectStatus(epsilonResponse, 201, 'Live append'); const epsilon = logEvent(await within(noDuplicate, 'Live epsilon event', streamDeadlineMs), 'Live append'); invariant(epsilon.entry.message === 'epsilon', 'Live stream duplicated or reordered an event.'); invariant(compareLogCursor(delta.cursor, epsilon.cursor) < 0, 'Live stream cursors are not ordered.'); invariant(new Set([replay.entry.id, delta.entry.id, epsilon.entry.id]).size === 3, 'Stream delivered a duplicate entry.'); return { replay: ['gamma'], transition: 'bookmark', live: ['delta', 'epsilon'], duplicates: 0 }; } finally { await reader.close(); } }); await record('cursor.explicit-expiry', async () => { const cube = await environment.admin.createCube('cursor-expiry'); await environment.admin.grantCube(principalA, cube); const appended = await environment.operations.append( credentialA, cube, createProtocolEnvelope('cursor-expiry-entry', { post_id: '00000000-0000-4000-8000-000000000321', to: 'broadcast', message: 'expire this cursor', }), ); expectStatus(appended, 201, 'Cursor expiry fixture append'); const entry = decodeAppendLogResultEnvelope(appended.body).payload.entry; const cursor = { id: entry.id, created_at: entry.created_at }; await environment.admin.expireCursor(cube, cursor); const response = await environment.operations.read( credentialA, cube, createProtocolEnvelope('read-expired', { cursor, limit: 10 }), ); expectError(response, 410, ErrorCode.CURSOR_EXPIRED, 'Expired cursor read'); const stream = await environment.operations.openStream(credentialA, cube, cursor); expectError(stream, 410, ErrorCode.CURSOR_EXPIRED, 'Expired cursor stream'); invariant(stream.stream === null, 'Expired cursor stream exposed a body stream.'); return { read_status: 410, stream_status: 410, code: ErrorCode.CURSOR_EXPIRED }; }); await record('acks.idempotent', async () => { const cube = await environment.admin.createCube('ack-idempotency'); await environment.admin.grantCube(principalA, cube); const appended = await environment.operations.append( credentialA, cube, createProtocolEnvelope('ack-idempotency-entry', { post_id: '00000000-0000-4000-8000-000000000322', to: 'broadcast', message: 'acknowledge this entry', }), ); expectStatus(appended, 201, 'Acknowledgement fixture append'); const entry = decodeAppendLogResultEnvelope(appended.body).payload.entry; const request = createProtocolEnvelope('ack-entry1', { entry_id: entry.id, kind: 'ack' }); const first = await environment.operations.ack(credentialA, cube, request); const second = await environment.operations.ack(credentialA, cube, request); expectStatus(first, 204, 'First acknowledgement'); expectStatus(second, 204, 'Repeated acknowledgement'); invariant((first.body === '' || first.body === undefined) && (second.body === '' || second.body === undefined), 'Acknowledgement responses must be bodyless.'); return { first_status: 204, repeated_status: 204, bodyless: true }; }); await record('acks.status-query', async () => { const cube = await environment.admin.createCube('ack-status-cube'); await environment.admin.grantCube(principalA, cube); const role = await environment.admin.createRole(cube, { roleClass: 'worker', isHumanSeat: false, name: 'Ack Status Worker', }); const acknowledgedRecipient = await environment.admin.createDrone(principalA, cube, role); const claimingRecipient = await environment.admin.createDrone(principalA, cube, role); const acknowledgedCredential = await environment.admin.issueManagedDroneSession(acknowledgedRecipient); const claimingCredential = await environment.admin.issueManagedDroneSession(claimingRecipient); const append = await environment.operations.append( credentialA, cube, createProtocolEnvelope('ack-status-append', { post_id: '00000000-0000-4000-8000-000000000310', to: [acknowledgedRecipient.id, claimingRecipient.id], message: 'START NOW acknowledgement status fixture', }), ); expectStatus(append, 201, 'Acknowledgement-status fixture append'); const entry = decodeAppendLogResultEnvelope(append.body).payload.entry; const missingResponse = await environment.operations.ackStatus( credentialA, cube, createProtocolEnvelope('ack-status-missing', { entry_id: entry.id }), ); expectStatus(missingResponse, 200, 'Missing acknowledgement status'); const missing = decodeAckStatusResultEnvelope(missingResponse.body).payload; invariant( missing.visibility === 'direct' && missing.recipients.length === 2 && missing.recipients.every((recipient) => recipient.acknowledged_at === null) && missing.claims.length === 0, 'Missing acknowledgement was not represented as nullable per-recipient state.', ); expectStatus( await environment.operations.ack( acknowledgedCredential, cube, createProtocolEnvelope('ack-status-ack', { entry_id: entry.id, kind: 'ack' }), ), 204, 'Acknowledgement-status acknowledgement', ); expectStatus( await environment.operations.ack( claimingCredential, cube, createProtocolEnvelope('ack-status-claim', { entry_id: entry.id, kind: 'claim' }), ), 204, 'Acknowledgement-status claim', ); const distinctResponse = await environment.operations.ackStatus( credentialA, cube, createProtocolEnvelope('ack-status-distinct', { entry_id: entry.id }), ); expectStatus(distinctResponse, 200, 'Distinct acknowledgement and claim status'); const distinct = decodeAckStatusResultEnvelope(distinctResponse.body).payload; const acknowledged = distinct.recipients.filter((recipient) => recipient.acknowledged_at !== null); invariant( acknowledged.length === 1 && acknowledged[0].drone_id === acknowledgedRecipient.id && distinct.claims.length === 1 && distinct.claims[0].drone_id === claimingRecipient.id && distinct.recipients.find((recipient) => recipient.drone_id === claimingRecipient.id)?.acknowledged_at === null, 'Acknowledgement status conflated acknowledgement and claim records.', ); expectError( await environment.operations.ackStatus( credentialA, cube, createProtocolEnvelope('ack-status-unknown', { entry_id: '00000000-0000-4000-8000-000000000311', }), ), 404, ErrorCode.NOT_FOUND, 'Unknown acknowledgement-status entry', ); const unreadResponse = await environment.operations.read( credentialA, cube, createProtocolEnvelope('ack-status-unread', { cursor: null, limit: 10 }), ); expectStatus(unreadResponse, 200, 'Post-query unread read'); const unread = decodeReadLogResultEnvelope(unreadResponse.body).payload; invariant( same(unread.entries, [entry]), 'Acknowledgement-status query mutated or advanced unread delivery state.', ); return { missing_acknowledgement: null, acknowledgements: 1, claims: 1, distinct: true, unread_entry_available: true, unknown_entry_code: ErrorCode.NOT_FOUND, }; }); await record('decisions.topic-supersession', async () => { const firstResponse = await environment.operations.recordDecision( credentialA, cubeA, createProtocolEnvelope('decision1', { topic: 'runtime', decision: 'first' }), ); expectStatus(firstResponse, 201, 'First decision'); const first = decodeDecisionResultEnvelope(firstResponse.body).payload.decision; const secondResponse = await environment.operations.recordDecision( credentialA, cubeA, createProtocolEnvelope('decision2', { topic: 'runtime', decision: 'second', rationale: 'new evidence' }), ); expectStatus(secondResponse, 201, 'Superseding decision'); const second = decodeDecisionResultEnvelope(secondResponse.body).payload.decision; const listResponse = await environment.operations.listDecisions( credentialA, cubeA, createProtocolEnvelope('decisions', {}), ); expectStatus(listResponse, 200, 'Decision list'); const active = decodeDecisionsResultEnvelope(listResponse.body).payload.decisions; invariant(active.length === 1 && active[0].decision === 'second', 'Decision list did not contain only the active superseding decision.'); invariant(second.supersedes === first.id, 'Superseding decision did not reference its predecessor.'); return { active_count: 1, active_decision: 'second', supersedes_first: true }; }); let workerRoleA!: ConformanceRole; let workerRoleB!: ConformanceRole; let managedWorker!: ConformanceDrone; let readCredential = ''; let writeCredential = ''; let workerSession = ''; let metadataDroneA!: ConformanceDrone; let metadataDroneB!: ConformanceDrone; let metadataSessionA = ''; await record('security.drone-management-authorization', async () => { const observationCredential = await environment.admin.issueDroneSession(principalA); workerRoleA = await environment.admin.createRole(cubeA, { roleClass: 'worker', isHumanSeat: false, }); managedWorker = await environment.admin.createDrone(principalA, cubeA, workerRoleA); const deniedCredentials: Array<{ access: 'read' | 'write'; credential: string }> = []; for (const [index, access] of ['read', 'write'].entries()) { const principalName = access === 'read' ? 'Coordinator' : 'write-principal'; const principal = await environment.admin.createPrincipal(principalName); await environment.admin.grantCube(principal, cubeA, access as 'read' | 'write'); const invitation = await environment.admin.issueSingleUseInvitation(principal, 'client'); const credential = `${(access === 'read' ? 'R' : 'W').repeat(42)}Q`; if (access === 'read') readCredential = credential; else writeCredential = credential; const enrollment = await environment.operations.enroll(createProtocolEnvelope( `${access}-principal-enroll`, { invitation, retry_key: `00000000-0000-4000-8000-${String(301 + index).padStart(12, '0')}`, client_credential: credential, client_name: principalName, }, )); expectStatus(enrollment, 201, `${access} principal enrollment`); deniedCredentials.push({ access: access as 'read' | 'write', credential }); } for (const { access, credential } of deniedCredentials) { const rosterBefore = await environment.operations.listDrones(observationCredential, cubeA); expectStatus(rosterBefore, 200, `${access} principal pre-denial roster`); const workerBefore = listedDrone(rosterBefore, managedWorker.id); invariant(workerBefore, `${access} principal pre-denial roster omitted the managed worker.`); expectError( await environment.operations.reassignDrone( credential, cubeA, managedWorker, createProtocolEnvelope(`${access}-reassign-denied`, { role_id: workerRoleA.id }), ), 403, ErrorCode.ACCESS_DENIED, `${access} principal reassignment`, ); expectError( await environment.operations.evictDrone( credential, cubeA, managedWorker, createProtocolEnvelope(`${access}-evict-denied`, {}), ), 403, ErrorCode.ACCESS_DENIED, `${access} principal eviction`, ); const rosterAfter = await environment.operations.listDrones(observationCredential, cubeA); expectStatus(rosterAfter, 200, `${access} principal post-denial roster`); invariant( same(listedDrone(rosterAfter, managedWorker.id), workerBefore), `${access} principal management denial mutated the managed worker.`, ); } return { read_status: 403, write_status: 403, manage_required: true }; }); await record('security.manage-access-matrix', async () => { const noGrantPrincipal = await environment.admin.createPrincipal('Coordinator role without cube grant'); const noGrantInvitation = await environment.admin.issueSingleUseInvitation(noGrantPrincipal, 'client'); const noGrantCredential = `${'N'.repeat(42)}Q`; expectStatus(await environment.operations.enroll(createProtocolEnvelope( 'no-grant-principal-enroll', { invitation: noGrantInvitation, retry_key: '00000000-0000-4000-8000-000000000303', client_credential: noGrantCredential, client_name: 'Coordinator', }, )), 201, 'No-grant principal enrollment'); const droneCredential = await environment.admin.issueManagedDroneSession(managedWorker); const matrixTargetRole = await environment.admin.createRole(cubeA, { roleClass: 'worker', isHumanSeat: false, }); const evictionTarget = await environment.admin.createDrone(principalA, cubeA, workerRoleA); const evictionTargetCredential = await environment.admin.issueManagedDroneSession(evictionTarget); const unknownCube = { id: '00000000-0000-4000-8000-000000000399' }; const operations: ReadonlyArray<{ name: string; successStatus: number; invoke: (credential: string, cube: ConformanceCube) => Promise; }> = [ { name: 'cube-update', successStatus: 200, invoke: (credential, cube) => environment.operations.updateCube( credential, cube, createProtocolEnvelope('matrix-cube-update', { cube_directive: 'matrix-directive' }), ), }, { name: 'role-create', successStatus: 201, invoke: (credential, cube) => environment.operations.createRole( credential, cube, createProtocolEnvelope('matrix-role-create', { name: 'Matrix Role' }), ), }, { name: 'taxonomy-patch', successStatus: 200, invoke: (credential, cube) => environment.operations.patchTaxonomy( credential, cube, createProtocolEnvelope('matrix-taxonomy-patch', { marker: 'matrix-taxonomy' }), ), }, { name: 'decision-record', successStatus: 201, invoke: (credential, cube) => environment.operations.recordDecision( credential, cube, createProtocolEnvelope('matrix-decision-record', { topic: 'matrix-authority', decision: 'manage only', }), ), }, { name: 'drone-reassign', successStatus: 200, invoke: (credential, cube) => environment.operations.reassignDrone( credential, cube, managedWorker, createProtocolEnvelope('matrix-drone-reassign', { role_id: matrixTargetRole.id }), ), }, { name: 'drone-evict', successStatus: 200, invoke: (credential, cube) => environment.operations.evictDrone( credential, cube, evictionTarget, createProtocolEnvelope('matrix-drone-evict', {}), ), }, ]; const observableState = async (operationName: string): Promise => { if (operationName === 'decision-record') { const response = await environment.operations.listDecisions( credentialA, cubeA, createProtocolEnvelope('matrix-observe-decisions', {}), ); expectStatus(response, 200, 'Matrix decision observation'); return decodeDecisionsResultEnvelope(response.body).payload; } if (operationName === 'drone-reassign' || operationName === 'drone-evict') { const response = await environment.operations.listDrones(credentialA, cubeA); expectStatus(response, 200, 'Matrix drone observation'); return listedDrone( response, operationName === 'drone-reassign' ? managedWorker.id : evictionTarget.id, ); } return null; }; const assertObservableDenial = async (operationName: string, before: unknown | null): Promise => { if (operationName === 'role-create') { expectError( await environment.operations.roleRationale( credentialA, cubeA, createProtocolEnvelope('matrix-observe-role', { role: 'Matrix Role', section: 'Workflow rationale', }), ), 404, ErrorCode.ROLE_NOT_FOUND, 'Denied matrix role observation', ); } else if (before !== null) { invariant( same(await observableState(operationName), before), `${operationName} changed protocol-visible state after denial.`, ); } }; for (const operation of operations) { for (const [kind, credential] of [ ['read', readCredential], ['write', writeCredential], ['drone-session', droneCredential], ] as const) { const before = await observableState(operation.name); expectError( await operation.invoke(credential, cubeA), 403, ErrorCode.ACCESS_DENIED, `${operation.name} by ${kind} principal`, ); await assertObservableDenial(operation.name, before); if (operation.name === 'drone-evict') { expectStatus( await environment.operations.read( evictionTargetCredential, cubeA, createProtocolEnvelope(`matrix-${kind}-eviction-target-probe`, { cursor: null, limit: 1 }), ), 200, `${kind} denied eviction target probe`, ); } } for (const [kind, credential, cube] of [ ['no-grant', noGrantCredential, cubeA], ['foreign-principal', credentialB, cubeA], ['foreign-cube', credentialA, cubeB], ['unknown-cube', credentialA, unknownCube], ] as const) { const before = await observableState(operation.name); expectError( await operation.invoke(credential, cube), 404, ErrorCode.NOT_FOUND, `${operation.name} against ${kind}`, ); await assertObservableDenial(operation.name, before); if (operation.name === 'drone-evict') { expectStatus( await environment.operations.read( evictionTargetCredential, cubeA, createProtocolEnvelope(`matrix-${kind}-eviction-target-probe`, { cursor: null, limit: 1 }), ), 200, `${kind} denied eviction target probe`, ); } } const success = await operation.invoke(credentialA, cubeA); expectStatus(success, operation.successStatus, `${operation.name} by managing principal`); } return { operation_count: operations.length, manage_success: true, read_write_status: 403, drone_session_status: 403, hidden_status: 404, observable_non_mutation_operations: 4, write_only_operations: 2, role_labels_authoritative: false, }; }); await record('drones.reassign-invariants', async () => { workerRoleB = await environment.admin.createRole(cubeA, { roleClass: 'worker', isHumanSeat: false, }); const humanSourceRole = await environment.admin.createRole(cubeA, { roleClass: 'worker', isHumanSeat: true, }); const queenRole = await environment.admin.createRole(cubeA, { roleClass: 'queen', isHumanSeat: false, }); const occupiedHumanRole = await environment.admin.createRole(cubeA, { roleClass: 'worker', isHumanSeat: true, }); const humanSource = await environment.admin.createDrone(principalA, cubeA, humanSourceRole); await environment.admin.createDrone(principalA, cubeA, occupiedHumanRole); const contender = await environment.admin.createDrone(principalA, cubeA, workerRoleA); workerSession = await environment.admin.issueManagedDroneSession(managedWorker); const reassigned = await environment.operations.reassignDrone( credentialA, cubeA, managedWorker, createProtocolEnvelope('reassign-worker', { role_id: workerRoleB.id }), ); expectStatus(reassigned, 200, 'Worker reassignment'); const reassignedDrone = decodeReassignDroneResultEnvelope(reassigned.body).payload.drone; invariant( reassignedDrone.id === managedWorker.id && reassignedDrone.role_id === workerRoleB.id, 'Reassignment response did not identify the persisted target role.', ); expectError( await environment.operations.reassignDrone( workerSession, cubeA, managedWorker, createProtocolEnvelope('reassign-drone-session-denied', { role_id: workerRoleA.id }), ), 403, ErrorCode.ACCESS_DENIED, 'Drone-session reassignment', ); expectError( await environment.operations.reassignDrone( credentialA, cubeA, managedWorker, createProtocolEnvelope('reassign-queen-denied', { role_id: queenRole.id }), ), 403, ErrorCode.ACCESS_DENIED, 'Worker-to-queen reassignment', ); const promoted = await environment.operations.reassignDrone( credentialA, cubeA, humanSource, createProtocolEnvelope('reassign-queen-allowed', { role_id: queenRole.id }), ); expectStatus(promoted, 200, 'Human-seat-to-queen reassignment'); invariant( decodeReassignDroneResultEnvelope(promoted.body).payload.drone.role_id === queenRole.id, 'Human-seat-to-queen reassignment did not persist.', ); expectError( await environment.operations.reassignDrone( credentialA, cubeA, contender, createProtocolEnvelope('reassign-occupied-denied', { role_id: occupiedHumanRole.id }), ), 409, ErrorCode.ROLE_IN_USE, 'Occupied human-seat reassignment', ); return { worker_reassigned: true, drone_session_denied: true, queen_requires_human_seat: true, occupied_human_seat_denied: true, }; }); await record('security.cross-cube-drone-management', async () => { const foreignRole = await environment.admin.createRole(cubeB, { roleClass: 'worker', isHumanSeat: false, }); const foreignDrone = await environment.admin.createDrone(principalB, cubeB, foreignRole); const foreignRosterBefore = await environment.operations.listDrones(credentialB, cubeB); const localRosterBefore = await environment.operations.listDrones(credentialA, cubeA); expectStatus(foreignRosterBefore, 200, 'Pre-denial foreign roster'); expectStatus(localRosterBefore, 200, 'Pre-denial local roster'); const foreignDroneBefore = listedDrone(foreignRosterBefore, foreignDrone.id); const managedWorkerBefore = listedDrone(localRosterBefore, managedWorker.id); invariant(foreignDroneBefore && managedWorkerBefore, 'Pre-denial roster omitted a drone-management target.'); expectError( await environment.operations.reassignDrone( credentialA, cubeB, foreignDrone, createProtocolEnvelope('cross-cube-reassign', { role_id: foreignRole.id }), ), 404, ErrorCode.NOT_FOUND, 'Cross-cube reassignment', ); expectError( await environment.operations.evictDrone( credentialA, cubeB, foreignDrone, createProtocolEnvelope('cross-cube-evict', {}), ), 404, ErrorCode.NOT_FOUND, 'Cross-cube eviction', ); expectError( await environment.operations.reassignDrone( credentialA, cubeA, foreignDrone, createProtocolEnvelope('foreign-drone-local-route', { role_id: workerRoleA.id }), ), 404, ErrorCode.NOT_FOUND, 'Foreign drone reassignment through authorized cube route', ); expectError( await environment.operations.evictDrone( credentialA, cubeA, foreignDrone, createProtocolEnvelope('foreign-drone-local-evict', {}), ), 404, ErrorCode.NOT_FOUND, 'Foreign drone eviction through authorized cube route', ); expectError( await environment.operations.reassignDrone( credentialA, cubeA, managedWorker, createProtocolEnvelope('foreign-role-local-drone', { role_id: foreignRole.id }), ), 404, ErrorCode.NOT_FOUND, 'Foreign role reassignment through authorized cube route', ); await environment.admin.grantCube(principalA, cubeB, 'read'); expectError( await environment.operations.reassignDrone( workerSession, cubeB, foreignDrone, createProtocolEnvelope('bound-drone-cross-cube-reassign', { role_id: foreignRole.id }), ), 404, ErrorCode.NOT_FOUND, 'Bound drone cross-cube reassignment', ); expectError( await environment.operations.evictDrone( workerSession, cubeB, foreignDrone, createProtocolEnvelope('bound-drone-cross-cube-evict', {}), ), 404, ErrorCode.NOT_FOUND, 'Bound drone cross-cube eviction', ); const foreignRosterAfter = await environment.operations.listDrones(credentialB, cubeB); const localRosterAfter = await environment.operations.listDrones(credentialA, cubeA); expectStatus(foreignRosterAfter, 200, 'Post-denial foreign roster'); expectStatus(localRosterAfter, 200, 'Post-denial local roster'); invariant( same(listedDrone(foreignRosterAfter, foreignDrone.id), foreignDroneBefore), 'Denied cross-cube management mutated the foreign drone.', ); invariant( same(listedDrone(localRosterAfter, managedWorker.id), managedWorkerBefore), 'Denied foreign-role management mutated the local drone.', ); return { unauthorized_cube_status: 404, foreign_drone_status: 404, foreign_role_status: 404, bound_drone_cross_cube_status: 404, targets_unchanged: true, code: ErrorCode.NOT_FOUND, }; }); await record('drones.evict-terminal-signal', async () => { const evictedDrone = await environment.admin.createDrone(principalA, cubeA, workerRoleA); const evictedCredential = await environment.admin.issueManagedDroneSession(evictedDrone); expectStatus( await environment.operations.read( evictedCredential, cubeA, createProtocolEnvelope('evict-probe-before', { cursor: null, limit: 1 }), ), 200, 'Pre-eviction seat probe', ); const before = await environment.operations.listDrones(credentialA, cubeA); expectStatus(before, 200, 'Pre-eviction roster'); invariant(listedDroneIds(before).includes(evictedDrone.id), 'Active drone was absent from roster.'); const evicted = await environment.operations.evictDrone( credentialA, cubeA, evictedDrone, createProtocolEnvelope('evict-managed-drone', {}), ); expectStatus(evicted, 200, 'Drone eviction'); invariant( same(decodeEvictDroneResultEnvelope(evicted.body).payload, { drone_id: evictedDrone.id, evicted: true, }), 'Eviction response did not identify the terminal seat.', ); const after = await environment.operations.listDrones(credentialA, cubeA); expectStatus(after, 200, 'Post-eviction roster'); invariant(!listedDroneIds(after).includes(evictedDrone.id), 'Evicted drone remained in roster.'); expectError( await environment.operations.append( credentialA, cubeA, createProtocolEnvelope('evict-direct-target', { message: 'must-not-fan-out', post_id: '00000000-0000-4000-8000-000000000310', to: [evictedDrone.id], }), ), 404, ErrorCode.NOT_FOUND, 'Evicted direct recipient', ); expectError( await environment.operations.read( evictedCredential, cubeA, createProtocolEnvelope('evict-probe-after', { cursor: null, limit: 1 }), ), PROTOCOL_HTTP_CONTRACT.drone_evicted_status, ErrorCode.DRONE_EVICTED, 'Evicted seat probe', ); return { eviction_status: 200, roster_visible: false, fanout_reachable: false, old_bearer_status: 410, old_bearer_code: ErrorCode.DRONE_EVICTED, }; }); let roleContractCube!: ConformanceCube; let roleContractPrincipal!: ConformancePrincipal; let roleContractCredential = ''; let roleContractReadCredential = ''; await record('roles.delete-contract', async () => { roleContractPrincipal = await environment.admin.createPrincipal('role-contract-manager'); const roleContractReader = await environment.admin.createPrincipal('role-contract-reader'); roleContractCube = await environment.admin.createCube('role-contract-cube'); await environment.admin.grantCube(roleContractPrincipal, roleContractCube, 'manage'); await environment.admin.grantCube(roleContractReader, roleContractCube, 'read'); const managerInvitation = await environment.admin.issueSingleUseInvitation( roleContractPrincipal, 'client', ); const readerInvitation = await environment.admin.issueSingleUseInvitation( roleContractReader, 'client', ); roleContractCredential = `${'D'.repeat(42)}Q`; roleContractReadCredential = `${'L'.repeat(42)}Q`; expectStatus(await environment.operations.enroll(createProtocolEnvelope( 'role-contract-manager-enroll', { invitation: managerInvitation, retry_key: '00000000-0000-4000-8000-000000000351', client_credential: roleContractCredential, }, )), 201, 'Role-contract manager enrollment'); expectStatus(await environment.operations.enroll(createProtocolEnvelope( 'role-contract-reader-enroll', { invitation: readerInvitation, retry_key: '00000000-0000-4000-8000-000000000352', client_credential: roleContractReadCredential, }, )), 201, 'Role-contract reader enrollment'); const refusalRationale = 'Workflow rationale:\nRefusal role remains.'; const defaultRole = await environment.admin.createRole(roleContractCube, { roleClass: 'worker', isHumanSeat: false, name: 'Default Worker', detailedDescription: refusalRationale, isDefault: true, }); const mandatoryRole = await environment.admin.createRole(roleContractCube, { roleClass: 'worker', isHumanSeat: false, name: 'Mandatory Worker', detailedDescription: refusalRationale, isMandatory: true, }); const humanRole = await environment.admin.createRole(roleContractCube, { roleClass: 'queen', isHumanSeat: true, name: 'Human Seat', detailedDescription: refusalRationale, }); const activeRole = await environment.admin.createRole(roleContractCube, { roleClass: 'worker', isHumanSeat: false, name: 'Active Worker', detailedDescription: refusalRationale, }); const activeDrone = await environment.admin.createDrone(roleContractPrincipal, roleContractCube, activeRole); const activeRosterBefore = await environment.operations.listDrones(roleContractCredential, roleContractCube); expectStatus(activeRosterBefore, 200, 'Pre-refusal active-role roster'); const activeDroneBefore = listedDrone(activeRosterBefore, activeDrone.id); invariant(activeDroneBefore, 'Pre-refusal roster omitted the active-role drone.'); const refusals = [ [defaultRole, ErrorCode.DEFAULT_ROLE_REQUIRED, 'default role', 'Default Worker', 'worker', false], [mandatoryRole, ErrorCode.ROLE_REQUIRED, 'mandatory role', 'Mandatory Worker', 'worker', false], [humanRole, ErrorCode.ROLE_REQUIRED, 'human-seat role', 'Human Seat', 'queen', true], [activeRole, ErrorCode.ROLE_IN_USE, 'active-drone role', 'Active Worker', 'worker', false], ] as const; for (const [index, [role, code, label, roleName, roleClass, isHumanSeat]] of refusals.entries()) { const response = await environment.operations.deleteRole( roleContractCredential, roleContractCube, role, createProtocolEnvelope(`delete-refusal-${index}`, {}), ); expectError(response, 409, code, `Delete ${label}`); if (code === ErrorCode.ROLE_IN_USE) { const message = protocolErrorMessage(response) ?? ''; invariant( message === ROLE_IN_USE_DELETE_MESSAGE, 'ROLE_IN_USE did not direct the caller to reassign or evict the drones first.', ); const roster = await environment.operations.listDrones(roleContractCredential, roleContractCube); expectStatus(roster, 200, 'Active-role refusal roster readback'); invariant( same(listedDrone(roster, activeDrone.id), activeDroneBefore), 'Active-role deletion refusal changed the active drone.', ); } const retained = await environment.operations.roleRationale( roleContractReadCredential, roleContractCube, createProtocolEnvelope(`delete-refusal-${index}-readback`, { role: role.id, section: 'Workflow rationale', }), ); expectStatus(retained, 200, `Retained ${label} rationale lookup`); const retainedPayload = decodeRoleRationaleResultEnvelope(retained.body).payload; invariant( retainedPayload.role_id === role.id && retainedPayload.role_name === roleName && same(retainedPayload.section, { heading: 'Workflow rationale', body: refusalRationale, }), `Retained ${label} rationale lookup returned a different role or section.`, ); const shapeSession = `${String(index).repeat(42)}S`; const shapeProbe = await environment.operations.attach( roleContractCredential, createProtocolEnvelope(`delete-refusal-${index}-shape-probe`, { cube_id: roleContractCube.id, role_id: role.id, session_credential: shapeSession, }), ); expectStatus(shapeProbe, 200, `Retained ${label} shape probe`); const shapePayload = decodeAttachResponseEnvelope(shapeProbe.body).payload; invariant( shapePayload.role.id === role.id && shapePayload.role.role_class === roleClass && shapePayload.role.is_human_seat === isHumanSeat, `Retained ${label} shape probe returned changed role semantics.`, ); expectStatus( await environment.operations.evictDrone( roleContractCredential, roleContractCube, { id: shapePayload.drone.id }, createProtocolEnvelope(`delete-refusal-${index}-shape-cleanup`, {}), ), 200, `Retained ${label} shape cleanup`, ); } const unknownRole = { id: '00000000-0000-4000-8000-000000000398' }; expectError( await environment.operations.deleteRole( roleContractCredential, roleContractCube, unknownRole, createProtocolEnvelope('delete-unknown-role', {}), ), 404, ErrorCode.NOT_FOUND, 'Delete unknown role', ); const deletableRole = await environment.admin.createRole(roleContractCube, { roleClass: 'worker', isHumanSeat: false, name: 'Disposable Worker', detailedDescription: refusalRationale, }); expectError( await environment.operations.deleteRole( roleContractReadCredential, roleContractCube, deletableRole, createProtocolEnvelope('delete-role-read-denied', {}), ), 403, ErrorCode.ACCESS_DENIED, 'Delete role with read authority', ); const retainedDeletable = await environment.operations.roleRationale( roleContractReadCredential, roleContractCube, createProtocolEnvelope('delete-role-read-denied-readback', { role: deletableRole.id, section: 'Workflow rationale', }), ); expectStatus(retainedDeletable, 200, 'Read-denied retained role rationale lookup'); const retainedDeletablePayload = decodeRoleRationaleResultEnvelope(retainedDeletable.body).payload; invariant( retainedDeletablePayload.role_id === deletableRole.id && retainedDeletablePayload.role_name === 'Disposable Worker' && same(retainedDeletablePayload.section, { heading: 'Workflow rationale', body: refusalRationale, }), 'Read-authority deletion denial changed the target role.', ); const shapeProbe = await environment.operations.attach( roleContractCredential, createProtocolEnvelope('delete-role-read-denied-shape-probe', { cube_id: roleContractCube.id, role_id: deletableRole.id, session_credential: 'S'.repeat(43), }), ); expectStatus(shapeProbe, 200, 'Read-denied retained role shape probe'); const shapePayload = decodeAttachResponseEnvelope(shapeProbe.body).payload; invariant( shapePayload.role.id === deletableRole.id && shapePayload.role.role_class === 'worker' && shapePayload.role.is_human_seat === false, 'Read-authority deletion denial changed the target role shape.', ); expectStatus( await environment.operations.evictDrone( roleContractCredential, roleContractCube, { id: shapePayload.drone.id }, createProtocolEnvelope('delete-role-read-denied-shape-cleanup', {}), ), 200, 'Read-denied retained role shape cleanup', ); const deleted = await environment.operations.deleteRole( roleContractCredential, roleContractCube, deletableRole, createProtocolEnvelope('delete-empty-role', {}), ); expectStatus(deleted, 200, 'Delete unassigned role'); invariant( same(decodeDeleteRoleResultEnvelope(deleted.body).payload, { role_id: deletableRole.id, deleted: true, }), 'Role deletion response did not identify the deleted role.', ); const evictedRole = await environment.admin.createRole(roleContractCube, { roleClass: 'worker', isHumanSeat: false, name: 'Former Worker', }); const evictedDrone = await environment.admin.createDrone( roleContractPrincipal, roleContractCube, evictedRole, ); const evictedSession = await environment.admin.issueManagedDroneSession(evictedDrone); const attributed = await environment.operations.append( evictedSession, roleContractCube, createProtocolEnvelope('role-delete-attribution', { post_id: '00000000-0000-4000-8000-000000000311', to: 'broadcast', message: 'attribution survives', }), ); expectStatus(attributed, 201, 'Pre-delete attributed log'); const attributedEntry = decodeAppendLogResultEnvelope(attributed.body).payload.entry; expectStatus(await environment.operations.evictDrone( roleContractCredential, roleContractCube, evictedDrone, createProtocolEnvelope('role-delete-evict', {}), ), 200, 'Pre-delete drone eviction'); expectStatus(await environment.operations.deleteRole( roleContractCredential, roleContractCube, evictedRole, createProtocolEnvelope('delete-evicted-role', {}), ), 200, 'Delete role held only by an evicted drone'); const read = await environment.operations.read( roleContractCredential, roleContractCube, createProtocolEnvelope('read-role-delete-attribution', { cursor: null, limit: 500 }), ); expectStatus(read, 200, 'Post-delete attributed log read'); invariant( decodeReadLogResultEnvelope(read.body).payload.entries.some( (entry) => entry.id === attributedEntry.id && entry.drone_id === evictedDrone.id, ), 'Deleting the evicted drone role lost the drone attribution of an existing log entry.', ); return { success_status: 200, hidden_status: 404, refusal_codes: [ ErrorCode.ROLE_IN_USE, ErrorCode.DEFAULT_ROLE_REQUIRED, ErrorCode.ROLE_REQUIRED, ], in_use_message_actionable: true, refusals_non_mutating: true, activity_log_attribution_preserved: true, }; }); await record('roles.rationale-contract', async () => { const detailedDescription = [ 'Implements assigned work.', '', 'Workflow rationale:', 'This exact stored section body is returned.', '', 'Boundaries:', 'Do not expand scope.', ].join('\n'); const role = await environment.admin.createRole(roleContractCube, { roleClass: 'worker', isHumanSeat: false, name: 'Rationale Builder', detailedDescription, }); const expectedSection = { heading: 'Workflow rationale', body: 'Workflow rationale:\nThis exact stored section body is returned.\n\n', }; for (const [index, [selector, section]] of [ [role.id, 'Workflow rationale'], ['rAtIoNaLe BuIlDeR', 'wOrKfLoW rAtIoNaLe'], ].entries()) { const response = await environment.operations.roleRationale( roleContractReadCredential, roleContractCube, createProtocolEnvelope(`rationale-lookup-${index}`, { role: selector, section }), ); expectStatus(response, 200, 'Role rationale lookup'); const result = decodeRoleRationaleResultEnvelope(response.body).payload; invariant( result.role_id === role.id && result.role_name === 'Rationale Builder' && same(result.section, expectedSection), 'Role rationale lookup did not return the canonical heading and exact stored section body.', ); } expectError( await environment.operations.roleRationale( roleContractReadCredential, roleContractCube, createProtocolEnvelope('rationale-unknown-role', { role: 'Unknown Role', section: 'Workflow rationale', }), ), 404, ErrorCode.ROLE_NOT_FOUND, 'Unknown role rationale lookup', ); const inaccessibleRole = await environment.admin.createRole(cubeB, { roleClass: 'worker', isHumanSeat: false, name: 'Foreign Rationale Role', detailedDescription, }); expectError( await environment.operations.roleRationale( roleContractReadCredential, roleContractCube, createProtocolEnvelope('rationale-inaccessible-role', { role: inaccessibleRole.id, section: 'Workflow rationale', }), ), 404, ErrorCode.ROLE_NOT_FOUND, 'Inaccessible role rationale lookup', ); expectError( await environment.operations.roleRationale( roleContractReadCredential, roleContractCube, createProtocolEnvelope('rationale-unknown-section', { role: role.id, section: 'Missing rationale', }), ), 404, ErrorCode.ROLE_SECTION_NOT_FOUND, 'Unknown role section lookup', ); await environment.admin.createRole(roleContractCube, { roleClass: 'worker', isHumanSeat: false, name: 'Ambiguous Role', detailedDescription, }); expectError( await environment.operations.createRole( roleContractCredential, roleContractCube, createProtocolEnvelope('role-case-variant-duplicate', { name: 'AMBIGUOUS ROLE' }), ), 409, ErrorCode.INVALID_INPUT, 'Case-variant duplicate role name', ); expectError( await environment.operations.createRole( roleContractCredential, roleContractCube, createProtocolEnvelope('role-invalid-character', { name: 'Invalid/Role' }), ), 400, ErrorCode.INVALID_INPUT, 'Invalid role name character', ); expectError( await environment.operations.roleRationale( roleContractReadCredential, roleContractCube, createProtocolEnvelope('rationale-invalid-selector', { role: ' Rationale Builder', section: 'Workflow rationale', }), ), 400, ErrorCode.INVALID_INPUT, 'Invalid role rationale selector', ); return { uuid_lookup: true, case_insensitive_name_lookup: true, canonical_heading: true, exact_body: true, unknown_role_code: ErrorCode.ROLE_NOT_FOUND, inaccessible_role_code: ErrorCode.ROLE_NOT_FOUND, unknown_section_code: ErrorCode.ROLE_SECTION_NOT_FOUND, case_variant_duplicate_status: 409, invalid_name_code: ErrorCode.INVALID_INPUT, invalid_selector_code: ErrorCode.INVALID_INPUT, }; }); const knownMetadata = { agent_kind: 'opencode' as const, reported_model: 'openai/gpt-5.6-sol', working_repo_name: 'Byte-Ventures/borg-mcp', working_repo_origin: 'https://github.com/Byte-Ventures/borg-mcp', }; try { metadataDroneA = await environment.admin.createDrone(principalA, cubeA, workerRoleA); metadataSessionA = await environment.admin.issueManagedDroneSession(metadataDroneA); } catch (error) { prerequisiteFailures.set('shared.metadata-baseline', error instanceof Error ? error.message : String(error)); } await record('metadata.attach-report', async () => { const attachSession = 'M'.repeat(43); const created = await environment.operations.attach( credentialA, createProtocolEnvelope('metadata-attach-created', { cube_id: cubeA.id, role_id: workerRoleA.id, session_credential: attachSession, runtime_metadata: { ...knownMetadata, working_repo_origin: 'git@github.com:Byte-Ventures/borg-mcp.git', }, }), ); expectStatus(created, 200, 'Metadata attach create'); const createdPayload = decodeAttachResponseEnvelope(created.body).payload; invariant(createdPayload.result === 'created', 'First metadata attach did not create a seat.'); invariant(same(createdPayload.drone.runtime_metadata, knownMetadata), 'Attach did not echo canonical metadata.'); invariant(createdPayload.drone.runtime_metadata_reported, 'Present attach report was not marked reported.'); const attachedDrone = { id: createdPayload.drone.id }; const unavailableSession = 'N'.repeat(43); const unavailable = await environment.operations.attach( credentialA, createProtocolEnvelope('metadata-attach-unavailable', { cube_id: cubeA.id, role_id: workerRoleA.id, session_credential: unavailableSession, }), ); expectStatus(unavailable, 200, 'Unavailable metadata attach'); const unavailableDrone = decodeAttachResponseEnvelope(unavailable.body).payload.drone; invariant( same(unavailableDrone.runtime_metadata, { agent_kind: null, reported_model: null, working_repo_name: null, working_repo_origin: null, }), 'Omitted attach report synthesized metadata.', ); invariant(!unavailableDrone.runtime_metadata_reported, 'Omitted attach report was marked reported.'); const explicitUnknown = await environment.operations.attach( credentialA, createProtocolEnvelope('metadata-attach-explicit-unknown', { cube_id: cubeA.id, role_id: workerRoleA.id, session_credential: 'U'.repeat(43), runtime_metadata: { agent_kind: null, reported_model: null, working_repo_name: null, working_repo_origin: null, }, }), ); expectStatus(explicitUnknown, 200, 'Explicit unknown metadata attach'); const explicitUnknownDrone = decodeAttachResponseEnvelope(explicitUnknown.body).payload.drone; invariant(explicitUnknownDrone.runtime_metadata_reported, 'All-null attach report was not marked reported.'); const reused = await environment.operations.attach( credentialA, createProtocolEnvelope('metadata-attach-reused', { cube_id: cubeA.id, role_id: workerRoleA.id, prior_drone_id: attachedDrone.id, session_credential: attachSession, runtime_metadata: knownMetadata, }), ); expectStatus(reused, 200, 'Metadata attach reuse'); invariant(decodeAttachResponseEnvelope(reused.body).payload.result === 'reused', 'Prior seat was not reused.'); const cleared = await environment.operations.selfMetadataUpdate( attachSession, cubeA, createProtocolEnvelope('metadata-clear-all', { agent_kind: null, reported_model: null, working_repo_name: null, working_repo_origin: null, }), ); expectStatus(cleared, 200, 'Clear-all metadata patch'); const clearedPayload = decodeUpdateDroneRuntimeMetadataResponseEnvelope(cleared.body).payload; invariant(clearedPayload.runtime_metadata_reported, 'Clear-all patch lost reported state.'); invariant( same(clearedPayload.runtime_metadata, explicitUnknownDrone.runtime_metadata), 'Clear-all patch did not produce explicit unknown metadata.', ); expectStatus( await environment.operations.selfMetadataUpdate( attachSession, cubeA, createProtocolEnvelope('metadata-restore-known', knownMetadata), ), 200, 'Restore known metadata', ); return { created: true, reused: true, report_states: [ unavailableDrone.runtime_metadata_reported, explicitUnknownDrone.runtime_metadata_reported, clearedPayload.runtime_metadata_reported, ], canonical_response: true, }; }); await record('metadata.self-heal-patch', async () => { const updates = [ { request_id: 'metadata-known-new', patch: { reported_model: 'openai/gpt-5.6-terra' } }, { request_id: 'metadata-null-clear', patch: { reported_model: null } }, { request_id: 'metadata-null-repeat', patch: { reported_model: null } }, { request_id: 'metadata-same-value', patch: { agent_kind: 'opencode' as const } }, ]; let state; for (const update of updates) { const response = await environment.operations.selfMetadataUpdate( metadataSessionA, cubeA, createProtocolEnvelope(update.request_id, update.patch), ); expectStatus(response, 200, update.request_id); state = decodeUpdateDroneRuntimeMetadataResponseEnvelope(response.body).payload; } invariant(state?.runtime_metadata.reported_model === null, 'Explicit null did not clear model metadata.'); invariant(state.runtime_metadata.agent_kind === 'opencode', 'Omitted field was not preserved.'); return { known_replace: true, omitted_unchanged: true, null_clear: true, repeat_safe: true }; }); await record('security.metadata-invalid-atomic', async () => { const baselineResponse = await environment.operations.selfMetadataUpdate( metadataSessionA, cubeA, createProtocolEnvelope('metadata-invalid-baseline', { agent_kind: 'opencode', reported_model: null, working_repo_name: 'Byte-Ventures/borg-mcp-shared', working_repo_origin: 'https://github.com/Byte-Ventures/borg-mcp-shared', }), ); expectStatus(baselineResponse, 200, 'Invalid metadata baseline'); decodeUpdateDroneRuntimeMetadataResponseEnvelope(baselineResponse.body); const baselineRoster = await environment.operations.listDrones(credentialA, cubeA); expectStatus(baselineRoster, 200, 'Invalid metadata baseline roster'); const baselineDrone = listedDrone(baselineRoster, metadataDroneA.id); invariant(baselineDrone, 'Invalid metadata baseline roster omitted the metadata seat.'); const invalidPatches: unknown[] = [ {}, { agent_kind: 'OpenCode' }, { reported_model: '' }, { reported_model: 'a'.repeat(161) }, { reported_model: 'safe\u001b[2J' }, { reported_model: 'safe\u061cnext' }, { working_repo_name: 'owner/repo' }, { working_repo_name: 'owner/repo', working_repo_origin: 'https://user:secret@github.com/owner/repo' }, { working_repo_name: 'owner/repo', working_repo_origin: ['file:/', '', 'Users', 'secret', 'repo'].join('/'), }, { role_id: workerRoleA.id }, { last_seen: '2026-07-14T10:00:00.000Z' }, ]; for (const [index, patch] of invalidPatches.entries()) { const response = await environment.operations.selfMetadataUpdate( metadataSessionA, cubeA, createProtocolEnvelope(`metadata-invalid-${index}`, patch), ); expectError(response, 400, ErrorCode.INVALID_INPUT, `Invalid metadata patch ${index}`); const readbackResponse = await environment.operations.listDrones(credentialA, cubeA); expectStatus(readbackResponse, 200, `Invalid metadata readback ${index}`); invariant( same(listedDrone(readbackResponse, metadataDroneA.id), baselineDrone), `Invalid metadata patch ${index} partially mutated state.`, ); } return { cases: invalidPatches.length, atomic: true, prior_safe_state_retained: true }; }); await record('security.metadata-own-seat', async () => { const peer = await environment.admin.createDrone(principalA, cubeA, workerRoleA); const rosterBefore = await environment.operations.listDrones(credentialA, cubeA); expectStatus(rosterBefore, 200, 'Pre-update metadata roster'); const peerBefore = listedDrone(rosterBefore, peer.id); const managedBefore = listedDrone(rosterBefore, managedWorker.id); const ownBefore = listedDrone(rosterBefore, metadataDroneA.id); invariant(peerBefore && managedBefore && ownBefore, 'Pre-update metadata roster omitted a fixture drone.'); const response = await environment.operations.selfMetadataUpdate( metadataSessionA, cubeA, createProtocolEnvelope('metadata-own-seat', { agent_kind: 'claude' }), ); expectStatus(response, 200, 'Own-seat metadata update'); const rosterAfter = await environment.operations.listDrones(credentialA, cubeA); expectStatus(rosterAfter, 200, 'Post-update metadata roster'); invariant( same(listedDrone(rosterAfter, peer.id), peerBefore), 'Own-seat update mutated a peer seat.', ); invariant( same(listedDrone(rosterAfter, managedWorker.id), managedBefore), 'Own-seat update mutated another existing seat.', ); invariant( listedDrone(rosterAfter, metadataDroneA.id)?.role_id === ownBefore.role_id, 'Metadata update changed the current seat role.', ); expectError( await environment.operations.selfMetadataUpdate( credentialA, cubeA, createProtocolEnvelope('metadata-manager-denied', { agent_kind: 'codex' }), ), 403, ErrorCode.ACCESS_DENIED, 'Manager metadata update', ); expectError( await environment.operations.selfMetadataUpdate( 'Z'.repeat(43), cubeA, createProtocolEnvelope('metadata-invalid-session', { agent_kind: null }), ), 401, ErrorCode.AUTH_INVALID, 'Unknown metadata session', ); const rejectedStates: Array<[string, ConformanceDrone, string, number, ErrorCode]> = []; const revoked = await environment.admin.createDrone(principalA, cubeA, workerRoleA); const revokedSession = await environment.admin.issueManagedDroneSession(revoked); await environment.admin.revokeManagedDroneSession(revoked); rejectedStates.push(['revoked', revoked, revokedSession, 401, ErrorCode.SESSION_REVOKED]); const evicted = await environment.admin.createDrone(principalA, cubeA, workerRoleA); const evictedSession = await environment.admin.issueManagedDroneSession(evicted); expectStatus( await environment.operations.evictDrone( credentialA, cubeA, evicted, createProtocolEnvelope('metadata-evict-seat', {}), ), 200, 'Metadata seat eviction', ); rejectedStates.push(['evicted', evicted, evictedSession, 410, ErrorCode.DRONE_EVICTED]); for (const [label, drone, session, status, code] of rejectedStates) { const rosterBefore = label === 'revoked' ? await environment.operations.listDrones(credentialA, cubeA) : null; if (rosterBefore) expectStatus(rosterBefore, 200, 'Pre-denial revoked metadata roster'); const droneBefore = rosterBefore ? listedDrone(rosterBefore, drone.id) : null; if (rosterBefore) invariant(droneBefore, 'Pre-denial roster omitted the revoked metadata seat.'); expectError( await environment.operations.selfMetadataUpdate( session, cubeA, createProtocolEnvelope(`metadata-${label}-denied`, { agent_kind: null }), ), status, code, `${label} metadata session`, ); if (droneBefore) { const rosterAfter = await environment.operations.listDrones(credentialA, cubeA); expectStatus(rosterAfter, 200, 'Post-denial revoked metadata roster'); invariant( same(listedDrone(rosterAfter, drone.id), droneBefore), 'Revoked metadata denial mutated the protocol-visible seat.', ); } } return { own_seat_only: true, manager_denied: true, unknown_session_denied: true, revoked_evicted_denied: true, }; }); await record('security.metadata-cross-cube-isolation', async () => { const sessionB = 'P'.repeat(43); const metadataRoleB = await environment.admin.createRole(cubeB, { roleClass: 'worker', isHumanSeat: false, }); const attachedB = await environment.operations.attach( credentialB, createProtocolEnvelope('metadata-attach-b', { cube_id: cubeB.id, role_id: metadataRoleB.id, session_credential: sessionB, runtime_metadata: { agent_kind: 'codex', reported_model: null, working_repo_name: 'Byte-Ventures/borg-mcp-server', working_repo_origin: 'https://github.com/Byte-Ventures/borg-mcp-server', }, }), ); expectStatus(attachedB, 200, 'Cube B metadata attach'); metadataDroneB = { id: decodeAttachResponseEnvelope(attachedB.body).payload.drone.id }; const rosterBefore = await environment.operations.listDrones(credentialB, cubeB); expectStatus(rosterBefore, 200, 'Pre-probe cube B roster'); const beforeB = listedDrone(rosterBefore, metadataDroneB.id); invariant(beforeB, 'Pre-probe cube B roster omitted its metadata seat.'); const foreign = await environment.operations.selfMetadataUpdate( metadataSessionA, cubeB, createProtocolEnvelope('metadata-cross-cube', { reported_model: 'foreign/probe' }), ); expectError(foreign, 404, ErrorCode.NOT_FOUND, 'Cross-cube metadata update'); const unknown = await environment.operations.selfMetadataUpdate( metadataSessionA, { id: '90000000-0000-4000-8000-000000000001' }, createProtocolEnvelope('metadata-unknown-cube', { reported_model: 'foreign/probe' }), ); expectError(unknown, 404, ErrorCode.NOT_FOUND, 'Unknown-cube metadata update'); invariant(same(foreign.body, unknown.body), 'Foreign and unknown metadata probes were distinguishable.'); const rosterAfter = await environment.operations.listDrones(credentialB, cubeB); expectStatus(rosterAfter, 200, 'Post-probe cube B roster'); invariant(same(listedDrone(rosterAfter, metadataDroneB.id), beforeB), 'Cross-cube metadata update mutated the foreign seat.'); const listedA = await environment.operations.listDrones(credentialA, cubeA); invariant(!listedDroneIds(listedA).includes(metadataDroneB.id), 'Cube A roster disclosed cube B metadata seat.'); return { update_status: 404, foreign_unknown_indistinguishable: true, foreign_unchanged: true, roster_isolated: true }; }); await record('security.metadata-noninterference', async () => { const rosterBefore = await environment.operations.listDrones(credentialA, cubeA); expectStatus(rosterBefore, 200, 'Pre-update noninterference roster'); const before = listedDrone(rosterBefore, metadataDroneA.id); invariant(before, 'Pre-update noninterference roster omitted the metadata seat.'); for (const [requestId, patch] of [ ['metadata-noninterference-known', { reported_model: 'openai/gpt-5.6-sol' }], ['metadata-noninterference-repeat', { reported_model: 'openai/gpt-5.6-sol' }], ['metadata-noninterference-null', { reported_model: null }], ] as const) { expectStatus( await environment.operations.selfMetadataUpdate( metadataSessionA, cubeA, createProtocolEnvelope(requestId, patch), ), 200, requestId, ); } expectError( await environment.operations.selfMetadataUpdate( metadataSessionA, cubeA, createProtocolEnvelope('metadata-noninterference-reject', { authority: 'manage' }), ), 400, ErrorCode.INVALID_INPUT, 'Rejected metadata non-interference update', ); const reattached = await environment.operations.attach( credentialA, createProtocolEnvelope('metadata-noninterference-reattach', { cube_id: cubeA.id, role_id: workerRoleA.id, prior_drone_id: metadataDroneA.id, session_credential: metadataSessionA, }), ); expectStatus(reattached, 200, 'Metadata non-interference reattach'); const rosterAfter = await environment.operations.listDrones(credentialA, cubeA); expectStatus(rosterAfter, 200, 'Post-update noninterference roster'); const after = listedDrone(rosterAfter, metadataDroneA.id); invariant(after, 'Post-update noninterference roster omitted the metadata seat.'); invariant( same(withoutRuntimeMetadata(before), withoutRuntimeMetadata(after)), 'Metadata update changed non-metadata roster state.', ); return { non_metadata_roster_state_unchanged: true }; }); await record('security.metadata-secret-non-echo', async () => { const marker = 'SECRET-METADATA-MARKER'; const rosterBefore = await environment.operations.listDrones(credentialA, cubeA); expectStatus(rosterBefore, 200, 'Pre-secret metadata roster'); const before = listedDrone(rosterBefore, metadataDroneA.id); invariant(before, 'Pre-secret metadata roster omitted the metadata seat.'); const response = await environment.operations.selfMetadataUpdate( metadataSessionA, cubeA, createProtocolEnvelope('metadata-secret', { working_repo_name: 'owner/repo', working_repo_origin: `https://user:${marker}@github.com/owner/repo?token=${marker}`, }), ); expectError(response, 400, ErrorCode.INVALID_INPUT, 'Secret-bearing metadata update'); invariant(!JSON.stringify(response.body).includes(marker), 'Metadata error echoed hostile secret input.'); const rosterAfter = await environment.operations.listDrones(credentialA, cubeA); expectStatus(rosterAfter, 200, 'Post-secret metadata roster'); invariant(same(listedDrone(rosterAfter, metadataDroneA.id), before), 'Secret-bearing metadata input was persisted.'); const hostileKeys = [ 'SECRET-METADATA-KEY-MARKER', `control\u001b[2J`, `bidi\u061cmarker`, `token_${'a'.repeat(48)}`, ]; for (const [index, key] of hostileKeys.entries()) { const rejected = await environment.operations.selfMetadataUpdate( metadataSessionA, cubeA, createProtocolEnvelope(`metadata-secret-key-${index}`, { [key]: 'x' }), ); expectError(rejected, 400, ErrorCode.INVALID_INPUT, `Hostile metadata key ${index}`); invariant(!JSON.stringify(rejected.body).includes(key), `Metadata error echoed hostile key ${index}.`); } const logs = await environment.operations.read( credentialA, cubeA, createProtocolEnvelope('metadata-secret-log-read', { cursor: null, limit: 500 }), ); expectStatus(logs, 200, 'Metadata secret log read'); for (const hostile of [marker, ...hostileKeys]) { invariant(!JSON.stringify(logs.body).includes(hostile), 'Metadata input leaked into activity logs.'); } return { rejected_pre_persistence: true, response_secret_free: true, state_secret_free: true, log_secret_free: true, unknown_key_secret_free: true, }; }); await record('security.active-stream-revocation', async () => { const principal = await environment.admin.createPrincipal('stream-revocation'); const cube = await environment.admin.createCube('stream-revocation'); await environment.admin.grantCube(principal, cube); const credential = await environment.admin.issueDroneSession(principal); const appended = await environment.operations.append( credential, cube, createProtocolEnvelope('stream-revocation-entry', { post_id: '00000000-0000-4000-8000-000000000315', to: 'broadcast', message: 'revocation cursor baseline', }), ); expectStatus(appended, 201, 'Revocation fixture append'); const entry = decodeAppendLogResultEnvelope(appended.body).payload.entry; const cursor = { id: entry.id, created_at: entry.created_at }; const opened = await environment.operations.openStream(credential, cube, cursor); expectStatus(opened, 200, 'Revocation stream open'); invariant(opened.stream, 'Successful revocation stream omitted its AsyncIterable.'); const reader = new SseEventReader(opened.stream); try { const bookmark = await within(reader.next(), 'Initial replay-complete bookmark', streamDeadlineMs); invariant(bookmark.type === 'bookmark' && bookmark.replay_complete, 'Fresh live stream did not complete replay.'); const pending = reader.next(); await provePending(pending, 'Idle live stream', pendingProbeMs); await environment.admin.revokePrincipal(principal); let terminated = false; try { await within(pending, 'Revoked stream termination', streamDeadlineMs); } catch (error) { if (error instanceof Error && error.message.includes('did not settle')) throw error; terminated = true; } invariant(terminated, 'Revoked stream yielded data instead of terminating.'); } finally { await reader.close(); } const rejected = await environment.operations.read( credential, cube, createProtocolEnvelope('read-revoked', { cursor, limit: 10 }), ); expectError(rejected, 401, ErrorCode.SESSION_REVOKED, 'Post-revocation request'); return { stream_terminated: true, subsequent_status: 401, subsequent_code: ErrorCode.SESSION_REVOKED }; }); await record('cubes.delete-terminal-cascade', async () => { const enrollParent = async ( name: string, marker: string, retrySuffix: string, ): Promise<{ principal: ConformancePrincipal; credential: string }> => { const principal = await environment.admin.createPrincipal(name); const invitation = await environment.admin.issueSingleUseInvitation(principal, 'client'); const credential = `${marker.repeat(41)}AQ`; expectStatus(await environment.operations.enroll(createProtocolEnvelope( `delete-${name}-enroll`, { invitation, retry_key: `00000000-0000-4000-8000-${retrySuffix.padStart(12, '0')}`, client_credential: credential, client_name: name, }, )), 201, `${name} enrollment`); return { principal, credential }; }; const creator = await enrollParent('delete-creator', 'C', '701'); const manager = await enrollParent('delete-manager', 'M', '702'); const reader = await enrollParent('delete-reader', 'R', '703'); const writer = await enrollParent('delete-writer', 'W', '704'); const outsider = await enrollParent('delete-outsider', 'O', '705'); await environment.admin.grantCreateCubeCapability(creator.principal); const deleteCubeRequest = { retry_key: '00000000-0000-4000-8000-000000000706', name: 'Disposable Cube', working_repo_name: 'disposable-cube', repository: { kind: 'local' as const, value: '00000000-0000-4000-8000-000000000707' }, template: 'software-dev' as const, }; const createResponse = await environment.operations.createCube( creator.credential, createProtocolEnvelope('delete-cube-create', deleteCubeRequest), ); expectStatus(createResponse, 201, 'Disposable cube creation'); const created = decodeCreateCubeResponseEnvelope(createResponse.body).payload; const cube = { id: created.cube_id }; const role = { id: created.default_worker_role_id }; await environment.admin.grantCube(manager.principal, cube, 'manage'); await environment.admin.grantCube(reader.principal, cube, 'read'); await environment.admin.grantCube(writer.principal, cube, 'write'); const drone = await environment.admin.createDrone(creator.principal, cube, role); const droneCredential = await environment.admin.issueManagedDroneSession(drone); const roleProbeSession = 'T'.repeat(43); const initialRoleProbe = await environment.operations.attach( manager.credential, createProtocolEnvelope('delete-role-shape-baseline', { cube_id: cube.id, role_id: role.id, session_credential: roleProbeSession, }), ); expectStatus(initialRoleProbe, 200, 'Deletion default-role shape baseline'); const roleProbeDrone = decodeAttachResponseEnvelope(initialRoleProbe.body).payload.drone; const append = await environment.operations.append( creator.credential, cube, createProtocolEnvelope('delete-log', { post_id: '00000000-0000-4000-8000-000000000312', to: 'broadcast', message: 'deleted with cube', }), ); expectStatus(append, 201, 'Deletion fixture log'); const entry = decodeAppendLogResultEnvelope(append.body).payload.entry; expectStatus(await environment.operations.ack( creator.credential, cube, createProtocolEnvelope('delete-claim', { entry_id: entry.id, kind: 'claim' }), ), 204, 'Deletion fixture claim'); expectStatus(await environment.operations.recordDecision( manager.credential, cube, createProtocolEnvelope('delete-decision', { topic: 'cleanup', decision: 'delete' }), ), 201, 'Deletion fixture decision'); const readDenialState = async (label: string): Promise => { const decisions = await environment.operations.listDecisions( manager.credential, cube, createProtocolEnvelope(`delete-${label}-decision-readback`, {}), ); expectStatus(decisions, 200, `${label} deletion decision readback`); const active = decodeDecisionsResultEnvelope(decisions.body).payload.decisions; const log = await environment.operations.read( manager.credential, cube, createProtocolEnvelope(`delete-${label}-log-readback`, { cursor: null, limit: 500 }), ); expectStatus(log, 200, `${label} deletion log readback`); const logPayload = decodeReadLogResultEnvelope(log.body).payload; const claimStatus = await environment.operations.ackStatus( manager.credential, cube, createProtocolEnvelope(`delete-${label}-claim-readback`, { entry_id: entry.id }), ); expectStatus(claimStatus, 200, `${label} deletion claim readback`); const roster = await environment.operations.listDrones(manager.credential, cube); expectStatus(roster, 200, `${label} deletion roster readback`); const roleReadback = await environment.operations.attach( manager.credential, createProtocolEnvelope(`delete-${label}-role-readback`, { cube_id: cube.id, role_id: role.id, prior_drone_id: roleProbeDrone.id, session_credential: roleProbeSession, }), ); expectStatus(roleReadback, 200, `${label} deletion role readback`); const rolePayload = decodeAttachResponseEnvelope(roleReadback.body).payload.role; return { decisions: active, entries: logPayload.entries, claims: decodeAckStatusResultEnvelope(claimStatus.body).payload.claims, drone: listedDrone(roster, drone.id), role: rolePayload, }; }; const denialBaseline = await readDenialState('baseline'); const assertDenialState = async (label: string): Promise => { invariant( same(await readDenialState(label), denialBaseline), `${label} cube deletion denial mutated protocol-visible cube state.`, ); }; for (const [kind, credential] of [ ['read', reader.credential], ['write', writer.credential], ['drone-session', droneCredential], ] as const) { expectError( await environment.operations.deleteCube( credential, cube, createProtocolEnvelope(`delete-${kind}-denied`, {}), ), 403, ErrorCode.ACCESS_DENIED, `${kind} cube deletion`, ); await assertDenialState(kind); } expectError( await environment.operations.deleteCube( outsider.credential, cube, createProtocolEnvelope('delete-outsider-denied', {}), ), 404, ErrorCode.NOT_FOUND, 'Never-authorized cube deletion', ); await assertDenialState('outsider'); const parentStream = await environment.operations.openStream(manager.credential, cube, null); const droneStream = await environment.operations.openStream(droneCredential, cube, null); expectStatus(parentStream, 200, 'Deletion parent stream'); expectStatus(droneStream, 200, 'Deletion drone stream'); invariant(parentStream.stream && droneStream.stream, 'Deletion fixture streams did not open.'); const parentEvents = new SseEventReader(parentStream.stream); const droneEvents = new SseEventReader(droneStream.stream); for (const streamReader of [parentEvents, droneEvents]) { invariant((await streamReader.next()).type === 'log', 'Deletion stream omitted replay log.'); const bookmark = await streamReader.next(); invariant(bookmark.type === 'bookmark' && bookmark.replay_complete, 'Deletion stream omitted bookmark.'); } const parentTerminal = parentEvents.next(); const droneTerminal = droneEvents.next(); await provePending(parentTerminal, 'Parent deletion terminal event', pendingProbeMs); await provePending(droneTerminal, 'Drone deletion terminal event', pendingProbeMs); const deleted = await environment.operations.deleteCube( manager.credential, cube, createProtocolEnvelope('delete-managed-cube', {}), ); expectStatus(deleted, 200, 'Managed cube deletion'); invariant( same(decodeDeleteCubeResponseEnvelope(deleted.body).payload, { cube_id: cube.id, deleted: true, }), 'Cube deletion response did not identify the terminal cube.', ); for (const [kind, event] of [ ['parent', await within(parentTerminal, 'Parent deletion terminal event', streamDeadlineMs)], ['drone', await within(droneTerminal, 'Drone deletion terminal event', streamDeadlineMs)], ] as const) { invariant( event.type === 'error' && event.error.error.code === ErrorCode.CUBE_DELETED, `${kind} stream did not receive CUBE_DELETED.`, ); } for (const streamReader of [parentEvents, droneEvents]) { let closed = false; try { await within(streamReader.next(), 'Deleted cube stream close', streamDeadlineMs); } catch (error) { if (error instanceof Error && error.message.includes('did not settle')) throw error; closed = true; } invariant(closed, 'Deleted cube stream yielded after its terminal error.'); await streamReader.close(); } for (const [kind, credential] of [ ['creator', creator.credential], ['manager', manager.credential], ['reader', reader.credential], ['writer', writer.credential], ['drone', droneCredential], ] as const) { expectError( await environment.operations.read( credential, cube, createProtocolEnvelope(`delete-${kind}-terminal`, { cursor: null, limit: 1 }), ), PROTOCOL_HTTP_CONTRACT.cube_deleted_status, ErrorCode.CUBE_DELETED, `${kind} post-delete request`, ); expectError( await environment.operations.deleteCube( credential, cube, createProtocolEnvelope(`delete-${kind}-repeat-terminal`, {}), ), PROTOCOL_HTTP_CONTRACT.cube_deleted_status, ErrorCode.CUBE_DELETED, `${kind} post-delete DELETE`, ); } expectError( await environment.operations.deleteCube( outsider.credential, cube, createProtocolEnvelope('delete-outsider-hidden-repeat', {}), ), 404, ErrorCode.NOT_FOUND, 'Never-authorized post-delete DELETE', ); expectError( await environment.operations.read( outsider.credential, cube, createProtocolEnvelope('delete-outsider-hidden', { cursor: null, limit: 1 }), ), 404, ErrorCode.NOT_FOUND, 'Never-authorized post-delete request', ); const recreatedResponse = await environment.operations.createCube( creator.credential, createProtocolEnvelope('delete-cube-recreate', deleteCubeRequest), ); expectStatus(recreatedResponse, 201, 'Post-delete cube recreation'); const recreated = decodeCreateCubeResponseEnvelope(recreatedResponse.body).payload; invariant( recreated.result === 'created' && recreated.cube_id !== cube.id, 'Post-delete recreation resolved retained cube-owned creation state.', ); return { deletion_status: 200, terminal_stream_error: ErrorCode.CUBE_DELETED, terminal_http_status: 410, unknown_hidden_status: 404, non_member_manager: true, recreation_created_new_cube: true, }; }); await record('attachment.reconciliation', async () => { await environment.admin.reset(); const enroll = async (name: string, token: string, retry: string) => { const principal = await environment.admin.createPrincipal(name); const invitation = await environment.admin.issueSingleUseInvitation(principal, 'client'); expectStatus(await environment.operations.enroll(createProtocolEnvelope(`attachment-enroll-${name}`, { invitation, retry_key: retry, client_credential: token, })), 201, 'Attachment parent enrollment'); return { principal, credential: token }; }; const parent = await enroll('parent', 'P'.repeat(41) + 'AQ', '00000000-0000-4000-8000-000000000901'); const foreign = await enroll('foreign', 'F'.repeat(41) + 'AQ', '00000000-0000-4000-8000-000000000902'); const cube = await environment.admin.createCube('Attachment Recovery'); const role = await environment.admin.createRole(cube, { roleClass: 'worker', isHumanSeat: false }); const otherRole = await environment.admin.createRole(cube, { roleClass: 'worker', isHumanSeat: false }); await environment.admin.grantCube(parent.principal, cube, 'write'); await environment.admin.grantCube(foreign.principal, cube, 'write'); const requestFor = async (token: string): Promise => ({ receipt: await deriveAttachmentReceipt(token), cube_id: cube.id, role_id: role.id, action: 'inspect', }); const call = (request: ReconcileAttachmentRequest, action: ReconcileAttachmentAction, credential = parent.credential) => environment.operations.reconcileAttachment(credential, createProtocolEnvelope(`attachment-${action}`, { ...request, action })); const result = async (request: ReconcileAttachmentRequest, action: ReconcileAttachmentAction) => { const response = await call(request, action); expectStatus(response, 200, `Attachment ${action}`); return decodeReconcileAttachmentResponseEnvelope(response.body, action).payload; }; const attach = (token: string, tuple: Partial> = {}, credential = parent.credential) => environment.operations.attach(credential, createProtocolEnvelope('attachment-attach', { cube_id: cube.id, role_id: role.id, session_credential: token, ...tuple, })); const attachPayload = async (token: string) => { const response = await attach(token); expectStatus(response, 200, 'Ordinary attachment'); return decodeAttachResponseEnvelope(response.body).payload; }; const token = 'a'.repeat(43); const request = await requestFor(token); const fakeSecret = 'synthetic-attachment-secret-' + 'S'.repeat(43); expectSecretFreeError(await environment.operations.reconcileAttachment(parent.credential, createProtocolEnvelope('attachment-malformed', { ...request, [fakeSecret]: fakeSecret })), 400, ErrorCode.INVALID_INPUT, 'Malformed reconciliation diagnostic', [fakeSecret, request.receipt]); expectSecretFreeError(await environment.operations.reconcileAttachment(parent.credential, { protocol_version: '14', request_id: 'attachment-old-tag', payload: { [fakeSecret]: fakeSecret }, }), 426, ErrorCode.UNSUPPORTED_PROTOCOL_VERSION, 'Previous protocol reconciliation', [fakeSecret]); invariant(same(await result(request, 'inspect'), { disposition: 'absent' }), 'Absent inspection created an operation.'); expectError(await call(request, 'finalize'), 404, ErrorCode.NOT_FOUND, 'Absent finalization'); const initial = await attachPayload(token); const identity = { drone_id: initial.drone.id, session_id: initial.session.id }; invariant(same(await result(request, 'inspect'), { disposition: 'accepted', ...identity }), 'Accepted identity differs.'); expectStatus(await environment.operations.append(token, cube, createProtocolEnvelope('attachment-intervening-log', { post_id: '00000000-0000-4000-8000-000000000903', message: 'After attachment', to: 'broadcast', })), 201, 'Intervening activity before retry'); // An unobserved first response and concurrent duplicates must still reuse one native identity/cursor. for (const response of await Promise.all([attach(token), attach(token)])) { expectStatus(response, 200, 'Concurrent ordinary retry'); const retry = decodeAttachResponseEnvelope(response.body).payload; invariant(retry.result === 'reused' && same(retry.session, initial.session) && retry.drone.id === initial.drone.id && same(retry.initial_log_cursor, initial.initial_log_cursor), 'Ordinary retry replaced its attachment/session/cursor.'); } const rosterBefore = await environment.operations.listDrones(parent.credential, cube); expectStatus(rosterBefore, 200, 'Attachment roster baseline'); invariant(same(listedDroneIds(rosterBefore), [initial.drone.id]), 'Concurrent retries created duplicate drones.'); const explicitPrior = await attach(token, { prior_drone_id: initial.drone.id }); expectStatus(explicitPrior, 200, 'Same-bearer retry with explicit current prior'); const explicitPriorPayload = decodeAttachResponseEnvelope(explicitPrior.body).payload; invariant(explicitPriorPayload.result === 'reused' && same(explicitPriorPayload.session, initial.session) && same(explicitPriorPayload.initial_log_cursor, initial.initial_log_cursor), 'Optional prior changed session/cursor.'); const otherCube = await environment.admin.createCube('Other Granted Attachment Cube'); const otherCubeRole = await environment.admin.createRole(otherCube, { roleClass: 'worker', isHumanSeat: false }); await environment.admin.grantCube(parent.principal, otherCube, 'write'); for (const changed of [ { role_id: otherRole.id }, { prior_drone_id: otherRole.id }, { cube_id: otherCube.id, role_id: otherCubeRole.id }, ]) expectSecretFreeError(await attach(token, changed), 401, ErrorCode.SESSION_REJECTED, 'Ordinary changed tuple', [token, request.receipt]); expectSecretFreeError(await attach(token, {}, foreign.credential), 401, ErrorCode.SESSION_REJECTED, 'Ordinary foreign bearer retry', [token, request.receipt]); for (const changed of [ { ...request, role_id: otherRole.id }, { ...request, prior_drone_id: initial.drone.id }, ]) expectSecretFreeError(await call(changed, 'retire'), 401, ErrorCode.SESSION_REJECTED, 'Changed immutable tuple', [token, request.receipt]); expectSecretFreeError(await call(request, 'retire', foreign.credential), 404, ErrorCode.NOT_FOUND, 'Foreign receipt', [token, request.receipt]); invariant(same(await result(request, 'inspect'), { disposition: 'accepted', ...identity }), 'Denied operation mutated attachment.'); invariant(same(listedDroneIds(await environment.operations.listDrones(parent.credential, cube)), listedDroneIds(rosterBefore)), 'Denied operation mutated roster.'); const unchangedRetry = await attachPayload(token); invariant(unchangedRetry.role.id === role.id && unchangedRetry.drone.id === initial.drone.id && same(unchangedRetry.session, initial.session) && same(unchangedRetry.initial_log_cursor, initial.initial_log_cursor), 'Refused ordinary attach changed original tuple/session/cursor.'); await environment.admin.revokeCubeGrant(parent.principal, cube); expectError(await call(request, 'retire'), 404, ErrorCode.NOT_FOUND, 'Revoked current grant'); await environment.admin.grantCube(parent.principal, cube, 'write'); invariant(same(await result(request, 'inspect'), { disposition: 'accepted', ...identity }), 'Grant denial mutated operation.'); invariant(same(await result(request, 'finalize'), { disposition: 'finalized', ...identity }), 'Finalize changed identity.'); invariant(same(await result(request, 'finalize'), { disposition: 'finalized', ...identity }), 'Lost-ACK retry changed identity.'); expectError(await call(request, 'retire'), 409, ErrorCode.ATTACHMENT_FINALIZED, 'Retiring finalized attachment'); invariant(same(await result(request, 'inspect'), { disposition: 'finalized', ...identity }), 'Finalized refusal mutated operation.'); invariant((await attachPayload(token)).session.id === initial.session.id, 'Finalized bearer retry changed session.'); for (const admitted of [false, true]) { const pendingToken = (admitted ? 'b' : 'c').repeat(43); const pending = await requestFor(pendingToken); const accepted = admitted ? await attachPayload(pendingToken) : null; invariant(same(await result(pending, 'retire'), { disposition: 'retired' }), 'Retirement did not commit.'); invariant(same(await result(pending, 'retire'), { disposition: 'retired' }), 'Repeated retirement changed result.'); invariant(same(await result(pending, 'inspect'), { disposition: 'retired' }), 'Retired inspection exposed identity.'); await environment.admin.revokeCubeGrant(parent.principal, cube); expectError(await call(pending, 'retire'), 404, ErrorCode.NOT_FOUND, 'Retirement retry after grant revocation'); await environment.admin.grantCube(parent.principal, cube, 'write'); expectError(await attach(pendingToken), 409, ErrorCode.ATTACHMENT_RETIRED, 'Late original attach'); expectError(await call(pending, 'finalize'), 409, ErrorCode.ATTACHMENT_RETIRED, 'Late original finalize'); if (accepted) { invariant(!listedDroneIds(await environment.operations.listDrones(parent.credential, cube)).includes(accepted.drone.id), 'Retired drone remains usable in roster.'); expectError(await environment.operations.read(pendingToken, cube, createProtocolEnvelope('attachment-retired-read', { cursor: null, limit: 1 })), 410, ErrorCode.DRONE_EVICTED, 'Retired session remains usable'); } } // A foreign pre-arrival tombstone cannot fence the real parent's later attach. const scopedToken = 'd'.repeat(43); const scoped = await requestFor(scopedToken); expectStatus(await call(scoped, 'retire', foreign.credential), 200, 'Foreign own-scope absent cancellation'); await attachPayload(scopedToken); invariant((await result(scoped, 'inspect')).disposition === 'accepted', 'Foreign tombstone fenced another parent.'); for (const [terminal, finalized] of (['revoked', 'evicted', 'superseded'] as const) .flatMap((terminal) => [false, true].map((finalized) => [terminal, finalized] as const))) { const terminalToken = ({ revoked: 'e', evicted: 'f', superseded: 'g' }[terminal]).repeat(42) + (finalized ? 'Q' : 'A'); const terminalRequest = await requestFor(terminalToken); const attached = await attachPayload(terminalToken); const target = { id: attached.drone.id }; // Check accepted cleanup AND idempotent finalized acknowledgments against replacements/terminal state. if (finalized) await result(terminalRequest, 'finalize'); if (terminal === 'revoked') await environment.admin.revokeManagedDroneSession(target); const replacement = terminal === 'superseded' ? await environment.admin.issueManagedDroneSession(target) : null; if (terminal === 'evicted') { await environment.admin.grantCube(parent.principal, cube, 'manage'); expectStatus(await environment.operations.evictDrone(parent.credential, cube, target, createProtocolEnvelope('attachment-external-evict', {})), 200, 'External eviction'); } const terminalRoster = await environment.operations.listDrones(parent.credential, cube); expectStatus(terminalRoster, 200, 'Terminal ordinary retry roster baseline'); expectSecretFreeError(await attach(terminalToken), terminal === 'evicted' ? 410 : 401, terminal === 'evicted' ? ErrorCode.DRONE_EVICTED : terminal === 'revoked' ? ErrorCode.SESSION_REVOKED : ErrorCode.SESSION_REJECTED, `Ordinary ${terminal} retry`, [terminalToken, terminalRequest.receipt]); const afterTerminalRetry = await environment.operations.listDrones(parent.credential, cube); expectStatus(afterTerminalRetry, 200, 'Terminal ordinary retry roster readback'); invariant(same(listedDroneIds(afterTerminalRetry), listedDroneIds(terminalRoster)) && listedDrone(afterTerminalRetry, target.id)?.role_id === listedDrone(terminalRoster, target.id)?.role_id, 'Terminal ordinary retry mutated roster/role state.'); if (replacement) expectStatus(await environment.operations.read(replacement, cube, createProtocolEnvelope('attachment-replacement-read', { cursor: null, limit: 1 })), 200, 'Superseding session after refused ordinary retry'); for (const action of ['inspect', 'finalize', 'retire'] as const) { expectError(await call(terminalRequest, action), terminal === 'evicted' ? 410 : 401, terminal === 'evicted' ? ErrorCode.DRONE_EVICTED : terminal === 'revoked' ? ErrorCode.SESSION_REVOKED : ErrorCode.SESSION_REJECTED, `Externally ${terminal} attachment ${action}`); } } const raceToken = 'h'.repeat(43); const race = await requestFor(raceToken); await attachPayload(raceToken); const outcomes = await Promise.all([call(race, 'finalize'), call(race, 'retire')]); invariant(outcomes.filter((response) => response.status === 200).length === 1, 'Finalize/retire did not serialize.'); const state = await result(race, 'inspect'); const loser = outcomes.find((response) => response.status !== 200)!; expectError(loser, 409, state.disposition === 'finalized' ? ErrorCode.ATTACHMENT_FINALIZED : ErrorCode.ATTACHMENT_RETIRED, 'Finalize/retire race loser'); invariant(state.disposition === 'finalized' || state.disposition === 'retired', 'Race has no terminal disposition.'); await environment.admin.revokePrincipal(parent.principal); expectError(await call(race, 'inspect'), 401, ErrorCode.SESSION_REVOKED, 'Revoked enrolled parent'); return { same_session_retry: true, pending_only_retirement: true, tombstone_fences_late_attach: true, parent_scoped_tombstone: true, terminal_refusals: true, serialized_finalize_retire: true }; }); const normalizedTranscript = results .filter((result) => !result.skipped) .map(({ id, observations }) => ({ id, observations })); return { ok: results.every((result) => result.ok), results, normalizedTranscript }; }